Utilizing JavaScript and jQuery to make a query to mySQL

Looking to solve a SQL database query challenge using JavaScript or jQuery? Here's the scenario: I have a SQL db and typically use the following query to retrieve data based on distance from specified coordinates:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(-122) ) + sin( radians(37) ) * sin( radians( latitude ) ) ) ) AS distance FROM stores HAVING distance < 12925 ORDER BY distance LIMIT 0 , 20;

The coordinates used in the query are 37 and -122. Now, I've exported this SQL db as a JavaScript array and need to perform the same kind of sorting operation purely with JavaScript or jQuery. Is there a way to achieve this effectively?

Edit - Can JavaScript be used to alter arrays based on complex queries similar to what can be done with MySQL?

Answer №1

Unfortunately, there doesn't seem to be a magical SQL-like way to achieve this automatically. However, you can experiment with the code below:

Check out a live demonstration here.

/* To convert degrees to radians */
function radians(deg) {
    return deg * Math.PI / 180;
}

/* Calculate distance from coordinates (37, -122) */
var cos37 = Math.cos(radians(37));
var sin37 = Math.sin(radians(37));
function distance(lat, long) {
    var dist = 3959 
               * Math.acos(cos37
                               * Math.cos(radians(lat))
                               * Math.cos(radians(long) 
                                          - radians(-122))
                           + sin37 
                               * Math.sin(radians(lat)));
    return dist;
}

/* Create a 2D array with entries in the format [id, latitude, longitude] */
var allArr = ...;     // [[id1, latitude1, longitude1],[id2, latitude2, longitude2],...]

/* Generate a new array with [id, distance] for entries within 12925 miles of (37, -122) */
var newArr = [];
for (var i = 0; i < allArr.length; i++) {    
    var dist = distance(allArr[i][1]/*latitude*/, 
                        allArr[i][2]/*longitude*/);
    if (dist < 12925) {
        newArr.push([allArr[i][0]/*id*/, 
                     dist]);
    }
}

It seems highly unlikely to find any two locations on Earth separated by more than 12925 miles, unless your application involves interstellar travel! So, double-check your requirements just in case :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of React Leaflet and the exciting possibilities of React Leaflet

I'm currently in the process of implementing the draw functions on a leaflet map. I started off by creating a new app with just react-leaflet installed. I used npx create-react-app and installed the following packages: npm install react react-dom lea ...

In Laravel 5, the firstOrCreate method ensures that a new record is created if one doesn't already

Displayed below is the code snippet from my app's Cart.php use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Cart extends Model { use SoftDeletes; protected $table = &apo ...

Issue encountered when transferring properties to create a search bar

My goal is to create a search input that filters based on the user's input. I have two components - one with the search input (app.js) and the other with the table (table.js). In the search input component (app.js), I can retrieve the current value b ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

Using Sequelize to update all values in a JSON file through an Express router.put operation

I've been working on a feature in my Express router that updates data in a MySQL schema for 'members' of clubs. The members table has various columns like member_id, forename, surname, address, etc. I've successfully created an Express ...

What methods can I use to adjust my HTML content once I have parsed my JSON file?

<script type="text/javascript"> window.alert = function(){}; var defaultCSS = document.getElementById('bootstrap-css'); function changeCSS(css){ if(css) $('head > link').filter(':first').replaceWit ...

What are the steps to rectify the issue of displaying data accurately on

I am working on my ReactJS project and using devextreme to create a unique circular gauge. However, I'm facing an issue where certain values are not being displayed correctly. For instance, instead of showing the value 5011480286.78, it is displaying ...

Having issues with Facebook's login API for JavaScript?

Apologies for the improper formatting. I am encountering errors in my JavaScript compiler while working with the Facebook Login API... Error: Invalid App Id - Must be a number or numeric string representing the application id." all.js:53 "FB.getL ...

Unable to use the same hexadecimal HTML entity in the value props of a React JSX component

Can someone explain why this code snippet displays dots as password and the other displays plain hexadecimal codes? <Field label="Password" value="&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;" type="password" /> While this one disp ...

The issue of anchors with jQuery.ajax()

Hello everyone, I'm encountering an issue with anchors and dynamic content loaded through $.ajax(). Take a look at my jQuery code: $("a.false").live("click", function() { var data = $(this).attr("href"); $("div#text").hide("fast"); $("di ...

Substitute the images with links provided in an external text file

I have a function that I use to replace avatars of players with custom images. Currently, I have three replacement links hardcoded into a Chrome extension. However, I want the function to read an external txt file to dynamically build an array so that I ca ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

Unable to retrieve the parent element using jQuery

I am facing an issue with my html structure that is generated dynamically through a foreach loop. I have attempted to remove the entire <a> element by accessing it from its ACTIVE HYPERLINK. However, all my efforts seem to be in vain as I am unable t ...

Error Alert: UnhandledPromiseRejectionWarning in Async Series Causes Concern

I am currently working on a function in my project that uses the async series method to ensure specific tasks are executed in a certain order. In this case, function1 needs to be completed before function2, which must then be completed before function3. a ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Ways to store a filestream coming from Node.js into AngularJS

When using my express server, I have a post-request set up to retrieve a pdf file from Amazon S3 and then send it back to Angular. This is the endpoint in my express server: var fileStream = s3.getObject(options).createReadStream(); fileStream.pipe(res); ...

Cleaning up database queries in MySQL without the use of prepared statements (PHP + outdated MySQL module)

Hello there! I recently came across an interesting issue regarding SQL injection in a PHP script that I downloaded called phpsimplechat. The author of the script created their own SQL layer which unfortunately turned out to be vulnerable to SQL Injection a ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

Issues with rendering of triangles in WebGL

My current project involves creating a webGL application for rendering randomly generated terrains. While the terrain rendering works smoothly, I've encountered an issue with rendering a simple quad to represent water - the triangles of the water are ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...