djangosqlitecoordinatesgeographic-distance

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?


Solution

  • 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)))