Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find items within a certain range of given coordinate

I have a django based web app which stores locations.

I have an android mobile app which pulls the locations from the web app and saves locations to the web app. The locations returned back to me I load on a mapoverlay in my app.

I would like to send my current coordinates and return a list of locations which are within a certain range. For example I send my location and get back items within a radius of 2km. (Similar to how the Google Places API works, just searching my data).

It is probably best to send the location coordinates and do all this logic in my python django app, Then return a list of correct locations and just display the places on my map.

I don't know where to begin doing this. How can I filter out my stored locations within certain radius(km) based off a given set of coordinates?

like image 726
darren Avatar asked Dec 09 '22 23:12

darren


1 Answers

Haversine Equation is the answer to your question. However it is slightly difficult to decrypt so here I provide you with a simple explanation:

To put it simply:

Here's the sample/example SQL statement that will find the closest 20 locations that are within a radius of 25 miles to the 37, -122 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude (given by lat/lng in the equation below), and then asks for only rows where the distance value is less than 25, orders the whole query by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

You can convert the sql to anything you desire. I mean the principle remains the same.

like image 108
Yavar Avatar answered Jan 19 '23 11:01

Yavar