需要帮助计算地理距离
我正在设置一个小程序,让用户输入两个地理坐标,然后计算它们之间的距离(还要考虑地球的弯曲)。所以我在维基百科上查了查这个公式,具体内容可以在这里找到。
我基本上是根据那个公式写了我的Python函数,结果是这样的:
def geocalc(start_lat, start_long, end_lat, end_long):
start_lat = math.radians(start_lat)
start_long = math.radians(start_long)
end_lat = math.radians(end_long)
end_long = math.radians(end_long)
d_lat = start_lat - end_lat
d_long = start_long - end_long
EARTH_R = 6372.8
c = math.atan((math.sqrt( (math.cos(end_lat)*d_long)**2 +( (math.cos(start_lat)*math.sin(end_lat)) - (math.sin(start_lat)*math.cos(end_lat)*math.cos(d_long)))**2)) / ((math.sin(start_lat)*math.sin(end_lat)) + (math.cos(start_lat)*math.cos(end_lat)*math.cos(d_long))) )
return EARTH_R*c
问题是,计算出来的结果非常不准确。我刚学Python,所以如果有人能给我一些帮助或建议,我会非常感激!
4 个回答
4
这个代码可以正常运行(打印出来的结果是2887.26公里,和示例中的计算结果一致,具体可以参考这个链接:http://en.wikipedia.org/wiki/Great-circle_distance):
import math
def geocalc(start_lat, start_long, end_lat, end_long):
start_lat = math.radians(start_lat)
start_long = math.radians(start_long)
end_lat = math.radians(end_lat)
end_long = math.radians(end_long)
d_lat = math.fabs(start_lat - end_lat)
d_long = math.fabs(start_long - end_long)
EARTH_R = 6372.8
y = ((math.sin(start_lat)*math.sin(end_lat)) + (math.cos(start_lat)*math.cos(end_lat)*math.cos(d_long)))
x = math.sqrt((math.cos(end_lat)*math.sin(d_long))**2 + ( (math.cos(start_lat)*math.sin(end_lat)) - (math.sin(start_lat)*math.cos(end_lat)*math.cos(d_long)))**2)
c = math.atan(x/y)
return EARTH_R*c
f = geocalc(36.12, -86.67, 33.94, -118.40)
print f
请注意你提交的代码中这一行:end_lat = math.radians(end_long)
4
你可以使用geopy这个模块,它里面有一个内置的功能可以用来计算距离。你可以在下面的链接中找到相关信息,往下滚动到“计算距离”的部分:https://pypi.python.org/pypi/geopy
12
你遇到了4到6个问题:
(1) end_lat = math.radians(end_long)
应该改成 end_lat = math.radians(end_lat)
(2) 你缺少了一些东西,正如有人提到的,可能是因为
(3) 你的代码看起来很乱(行太长了,多余的括号,还有17个没必要的“math.”)
(4) 你没有注意到维基百科文章中提到的使用 atan2()
的建议
(5) 你在输入坐标时可能搞混了纬度和经度
(6) delta(latitude)
的计算是多余的;在公式中并没有用到它
把这些问题放在一起看:
from math import radians, sqrt, sin, cos, atan2
def geocalc(lat1, lon1, lat2, lon2):
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
dlon = lon1 - lon2
EARTH_R = 6372.8
y = sqrt(
(cos(lat2) * sin(dlon)) ** 2
+ (cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)) ** 2
)
x = sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(dlon)
c = atan2(y, x)
return EARTH_R * c
>>> geocalc(36.12, -86.67, 33.94, -118.40)
2887.2599506071115
>>> geocalc(-6.508, 55.071, -8.886, 51.622)
463.09798886300376
>>> geocalc(55.071, -6.508, 51.622, -8.886)
414.7830891822618