2017-02-16 22 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