How can I get information about the nearest locations from the database?
I store coordinates as latitude latitude pairs in my database. Now I need to get all records that are in a given radius from a given lat-long coordinate. For example, if the given coordinates are 48.796777, 2.371140 and the distance is 20 kilometers, it will retrieve all records within 20 kilometers from that point.
If it provides any simplification or results in less processor time, it is accurate enough to compute a "straight" distance between points, i.e. there is no need to influence the curvature of the earth.
How can this be done with Django? More specifically, how should a view (and possibly a model) be built for such a query?
You must be using GeoDjango . It allows you to perform remote queries on your geographic database records.
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)))
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()
I think the best way is to go with GeoDjango as Timmy suggests, but then you should have a Geo Backend secure (like PosGis). However, I do not think it is possible to use this if you have a model containing the Latitude and Longitude custom field, for example
class CustomGeoModel(models.Model):
lat = models.CharField(max_length=30)
lon = models.CharField(max_length=30)
try this code. I am using python, sqlalchemy
this sqlalchemy query returns the nearest objects at a given point. It works correctly. But this query returns all models. But his work is wonderful.
my model class
#class City(Base):
__tablename__ = "tbl_City"
city_id = Column(Integer, primary_key=True, unique=True)
geo_coordinates = Column(Geometry('POINT', srid=4326))
my request
#point = city.geo_coordinates
near_citylist = City.query.order_by(City.geo_coordinates.distance_box(point))