简体   繁体   中英

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:

  • The google maps "measure distance" feature.
  • My own python code using the great arc distance calculation.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM