5

I use Postgis with Django to store geographic points. I have a model like the following:

from django.contrib.gis.db import models
class Event(models.Model)
    position = models.PointField()

I have two events(ev1, ev2). Here is the position value of each:

SRID=4326;POINT (-73.6335140000000052 45.5472019999999986)
SRID=4326;POINT (-73.6267909999999972 45.5459189999999978)

My goal is to get distance in meters between those two points. If i do:

ev1.position.distance(ev2.position)

I get 0.006844327432269004 How can I convert this value in meters?

Thanks!

Michael
  • 1,557
  • 2
  • 18
  • 38
  • If you use the Geography type, the distance result will be in meters. See: https://docs.djangoproject.com/en/1.9/ref/contrib/gis/model-api/#django.contrib.gis.db.models.GeometryField.geography – emily Jun 06 '16 at 16:41

4 Answers4

5

I was able to make it work, but only through a queryset. Here I wanted to get the distance between Event 3 and all other Events:

from django.contrib.gis.measure import Distance

p2 = Event.objects.get(id=3).position
for event in Event.objects.all().exclude(id=3).annotate(distance=Distance('position', p2)):
    print('{0} - {1}'.format(event.id, event.distance.m))

"position" is the name of the PointField

Sanyam Khurana
  • 1,336
  • 1
  • 14
  • 27
Michael
  • 1,557
  • 2
  • 18
  • 38
3

pnt.distance(pnt2) * 100

will give you distance in km.Change accordingly

Yaswanth
  • 113
  • 1
  • 1
  • 7
0

Instead of the class Distance, the database function Distance is used to perform the annotation:

    from django.contrib.gis.db.models.functions import Distance
kinuax
  • 25
  • 8
-2

according to this: https://docs.djangoproject.com/en/1.9/ref/contrib/gis/measure/#example

if you have:

in_meters = ev1.position.distance(ev2.position).m

you will get results in meters

joel goldstick
  • 4,393
  • 6
  • 30
  • 46
  • 12
    The distance function returns only a float. I get this error: AttributeError: 'float' object has no attribute 'm' – Michael Mar 15 '16 at 22:44