python - 如何以与数据库一致的方式计算应用程序的Python端点之间的距离

标签 python django gis postgis geodjango

我正在编写一个应用程序,该应用程序大量使用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/

相关文章:

python - nbytes 和 getsizeof 返回不同的值

javascript - 上传图像文件并发送到rest API

map - 有哪些有效的 Geohash 边界框覆盖算法?

r - 如何使用 R 中的 sf 包旋转网格?

javascript - Openlayers 3 : how to select a feature programmatically using ol. 交互。选择?

python - 正则表达式并使用 python 替换字符串

Python Pandas - groupby() 和 apply() 和rolling() 非常慢

python - 导入键盘出现 python 错误

django - 如何在 django 模板中迭代查询集字典

python - Django 查询上的 value() 方法后的计数和最大值