Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the nearest location entries from a database?

I store coordinates as latitude longitude pairs in my database. Now, I need to retrieve all the entries that are within a given radius from a given lat-long coordinate. For example, if given coordinates 48.796777, 2.371140 and distance of 20 kilometers, it would retrieve all the records within 20 kilometers from that point.

If it provides any simplification or results in less CPU time, it's accurate enough to calculate the "straight" distance between the points, i.e. there's no need to factor in the curvature of the earth.

How can this be achieved with Django? More specifically, how should the view (and possibly the model) be constructed for such a query?

like image 848
manabreak Avatar asked Apr 21 '15 06:04

manabreak


People also ask

How do I find the nearest location using latitude and longitude in Excel?

To get the latitude of the address in cell B2, use the formula = GetLatitude(B2) To get the longitude of the address in cell B2, use the formula = GetLongitude(B2) To get both the latitude and longitude of the address in cell B2, use the formula = GetCoordinates(B2)

How do I find the nearest location using latitude and longitude in C#?

Format("POINT({0} {1})", longitude, latitude)); var nearbyLocations = (from location in _context. Locations where // (Additional filtering criteria here...) select new { LocationID = location.ID, Address1 = location. Address1, City = location. City, State = location.


2 Answers

You should use GeoDjango. It allows you to perform distance queries on your geographic database entries.

from django.contrib.gis.measure import D
from django.contrib.gis.geos import *
from myapp.models import MyResult

pnt = fromstr('POINT(48.796777 2.371140 )', srid=4326)
qs = MyResult.objects.filter(point__distance_lte=(pnt, D(km=20)))
like image 187
Timmy O'Mahony Avatar answered Oct 18 '22 13:10

Timmy O'Mahony


You can use geopy

from geopy import distance  

_, ne = g.geocode('Newport, RI')  
_, cl = g.geocode('Cleveland, OH')  
distance.distance(ne, cl).miles  
# 538.37173614757057

To optimize a bit you can filter user objects to get a rough estimate of nearby users first. This way you don't have to loop over all the users in the db. This rough estimate is optional. To meet all your project requirements you maybe have to write some extra logic:

#The location of your user.
lat, lng = 41.512107999999998, -81.607044999999999 

min_lat = lat - 1 # You have to calculate this offsets based on the user location.
max_lat = lat + 1 # Because the distance of one degree varies over the planet.
min_lng = lng - 1
max_lng = lng + 1    

users = User.objects.filter(lat__gt=min_lat, lat__lt=max__lat, lat__gt=min_lat, lat__lt=max__lat)

# If not 20 fall back to all users.
if users.count() <= 20:
    users = User.objects.all()
like image 28
Mushahid Khan Avatar answered Oct 18 '22 14:10

Mushahid Khan