2017-02-16 23 views
1

我正在一个Python项目中,我有两个经纬度对,我想计算它们之间的距离。在其他项目中,我使用ST_Distance_Sphere(a.loc_point,b.loc_point)计算了Postgres中的距离,但是我想避免将所有数据加载到Postgres中,以便我可以计算距离差异。我搜索了,但一直没有找到我想要的,这是一个纯粹的Python实现,所以我不必将我的数据加载到Postgres中。Python中的ST_Distance_Sphere()?

我知道还有其他的距离计算将地球视为一个完美的球体,但由于准确性较差,这些计算不够好,这就是为什么我想使用PostGIS ST_Distance_Sphere()函数(或等效函数)。

这里有几个样品纬度/多头的,我想计算的距离:

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

我不能想象我的第一人问这个,但没有人知道的如何使用ST_Distance_Sphere()纯粹从Python脚本中进行经纬度计算?

回答

1

这是用于计算半径=半径地球

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 

希望这有助于一个完美的球体两个坐标之间距离的初步功能!

+0

如何使用此解决方案以米为单位获得答案? –

+0

在R = 3958.76#英里的线上,R简单地将R设置为地球半径(以米计算)(6.371亿米),并且应该返回以米为单位的答案 –

1

看到这个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 

通过亚伦d

你可以修改它通过添加miles = km * 0.621371

3

返回英里我会建议geopy包 - 见Measuring Distance文档中...

For your particulates ular案例:

from geopy.distance import great_circle 

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

print(great_circle(p1, p2).kilometers) 
0

我从那以后找到了另外一种方法,除了这里提供的答案。使用python的haversine模块。

from haversine import haversine as h 

# Return results in meters (*1000) 
print '{0:30}{1:12}'.format("haversine module:", h(a, b)*1000) 

我测试了所有三个答案加上haversine模块与我在Postgres中使用ST_Distance_Sphere(a,b)得到的结果。所有答案都非常好(谢谢),但Sishaar Rao的所有数学答案(计算)都是最接近的。以下是结果:

# Short Distance Test 
ST_Distance_Sphere(a, b):  370.43790478  
vincenty:      370.778186438 
great_circle:     370.541763803 
calcd:      370.437386736 
haversine function:   370.20481753 
haversine module:    370.437394767 

#Long Distance test: 
ST_Distance_Sphere(a, b):  1011734.50495159 
vincenty:      1013450.40832 
great_circle:     1012018.16318 
calcd:      1011733.11203 
haversine function:   1011097.90053 
haversine module:    1011733.11203