Python中的ST_Distance_Sphere()?

2024-03-28 23:09:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个Python项目中有两个lat/long对,我想计算它们之间的距离。在其他项目中,我用ST_distance_Sphere(a.loc_point,b.loc_point)计算了Postgres中的距离,但我不想为了计算距离差而将所有数据加载到Postgres中。我已经搜索过了,但是没有找到我想要的东西,这是一个纯粹的Python实现,所以我不必将数据加载到Postgres中。在

我知道还有其他的距离计算方法,把地球当作一个完美的球体,但是由于精度不高,这些计算还不够好,这就是为什么我要使用PostGIS ST_distance_sphere()函数(或等效函数)。在

下面是几个纬度/经度的样本,我想计算它们之间的距离:

Lat, Long 1: (49.8755, 6.07594)
Lat, Long 2: (49.87257, 6.0784)

我无法想象我是第一个问这个问题的人,但是有没有人知道一种方法可以完全从Python脚本中使用ST_Distance_Sphere()进行横向/远距离计算?在


Tags: 数据项目函数距离postgresloclongdistance
3条回答

我推荐geopy包-请参阅文档中的Measuring Distance部分。。。在

对于您的特殊情况:

from geopy.distance import great_circle

p1 = (49.8755, 6.07594)
p2 = (49.87257, 6.0784)

print(great_circle(p1, p2).kilometers)

这是一个基本函数,用于计算半径=地球半径的完美球体上两个坐标之间的距离

from math import pi , acos , sin , cos
def calcd(y1,x1, y2,x2):
   #
   y1  = float(y1)
   x1  = float(x1)
   y2  = float(y2)
   x2  = float(x2)
   #
   R   = 3958.76 # miles
   #
   y1 *= pi/180.0
   x1 *= pi/180.0
   y2 *= pi/180.0
   x2 *= pi/180.0
   #
   # approximate great circle distance with law of cosines
   #
   x = sin(y1)*sin(y2) + cos(y1)*cos(y2)*cos(x2-x1)
   if x > 1:
       x = 1
   return acos( x ) * R

希望这有帮助!在

看这个How can I quickly estimate the distance between two (latitude, longitude) points?

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

作者:Aaron D

您可以通过添加miles = km * 0.621371将其修改为返回英里数

相关问题 更多 >