我正在编写一个应用程序,该应用程序大量使用geodjango(在PostGis上)和空间查找。数据库端的距离查询效果很好,但现在我必须计算应用程序的 python 端两点之间的距离(这些点来自使用单独查询获得的模型)。
我可以想到很多方法来计算这个距离,但我想知道以与数据库输出一致的方式进行计算。
是否有任何神奇的Python函数可以计算在给定的SRID中测量的两点之间的距离?如果不是,您可以提出什么其他方法。
最佳答案
您可以使用haversine function from this question :
>>> from math import radians, cos, sin, asin, sqrt
>>>
>>> def haversine(lon1, lat1, lon2, lat2):
... """
... Calculate the great circle distance between two points
... on the earth (specified in decimal degrees)
... """
... # convert decimal degrees to radians
... lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
... # haversine formula
... dlon = lon2 - lon1
... dlat = lat2 - lat1
... a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
... c = 2 * asin(sqrt(a))
... km = 6367 * c
... return km
...
>>> haversine(-1.7297, 53.3205, -1.6997, 53.3186)
2.0025842109026413
关于python - 如何以与数据库一致的方式计算应用程序的Python端点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11703407/