How to calculate distance between two PointField?

狂风中的少年 提交于 2019-12-10 11:08:26

问题


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!


回答1:


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




回答2:


pnt.distance(pnt2) * 100

will give you distance in km.Change accordingly




回答3:


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



来源:https://stackoverflow.com/questions/36020805/how-to-calculate-distance-between-two-pointfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!