Last Updated: February 25, 2016
·
3.673K
· jairtrejo

Distance calculation in GeoDjango

The distance method of GEOS objects performs a simple geometric calculation, disregarding units. It's equivalent to:

>> d = lambda x0, y0, x1, y1 : math.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2)
>> d(-117.1549874, 32.7158105, -117.1563889, 32.7152778)
0.0014993236942038364

Which is not very useful, since all the coordinates are in degrees.

What you need to do is to first project your lat, lng coordinates to an SRID that keeps coordinates in distance units, and then use the point's distance method:

pnt = fromstr(
    'POINT(-117.1549874 32.7158105)', srid=4326
).transform(900913, clone=True)
pnt1 = fromstr(
    'POINT(-117.1563889 32.7152778)', srid=4326
).transform(900913, clone=True)
if pnt.distance(pnt1) > 200:
    print "Points are more than 200 m apart."
else:
    print "Points are within 200 m of each other."

I'm using SRID=900913, which is "Google map's projection". It is not particularly precise, but it suffices. It stores coordinate values in meters, which is convenient in this case, but if it didn't you could always use the django.contrib.gis.measure.D object for conversions.