0xED0
0xED0

Reputation: 73

GeoDjango with PostGIS - distance calculation is wrong

I'm trying to use GeoDjango with PostGIS in order to measure distances but the results I'm getting are off by 20%.

For testing I chose 2 random points in the ocean: (40.607532, -72.829369) and (40.366040, -73.556856).

To get the expected result I used 2 different methods:

Both give me the same result of 41.71 miles. Django gives me 50.49.

Here is my code:

# models.py

from django.contrib.gis.db import models

class Location(models.Model):
    point = models.PointField(null=True)

Then from the django shell:

>>> from loc.models import Location
>>> from django.contrib.gis.geos import Point
>>> from django.contrib.gis.db.models.functions import Distance
>>> loc = Location(point=Point(40.366040, -73.556856, srid=4326))
>>> loc.save()
>>> pnt = Point(40.607532, -72.829369, srid=4326)
>>> qs = Location.objects.annotate(distance=Distance('point', pnt))
>>> qs[0].distance.mi
50.4954671273202

Upvotes: 0

Views: 477

Answers (1)

0xED0
0xED0

Reputation: 73

Ok. I got it. The lat and lng were reversed. Point should have the lng as the first argument and lat as second. Google maps has it the other way around.

After switching, TADA...

>>> qs[0].distance.mi
41.7114806274482

Upvotes: 2

Related Questions