Dar*_*nom 8 python great-circle latitude-longitude
我正在建立一个小程序,从用户那里获取2个地理坐标,然后计算它们之间的距离(考虑到地球的曲率).所以我查看维基百科,了解这里的公式.
基本上我基本上设置了我的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
Run Code Online (Sandbox Code Playgroud)
问题是结果真的不准确.我是python的新手,所以一些帮助或建议将不胜感激!
Joh*_*hin 11
你有4或5或6个问题:
(1)end_lat = math.radians(end_long)应该end_lat = math.radians(end_lat)
(2)你错过了一些人已经提到过的东西,很可能是因为
(3)你的代码难以理解(行太长,冗余的括号,17个无数的"数学"实例.)
(4)您没有注意到维基百科关于使用的文章中的注释 atan2()
(5)输入坐标时,您可能已经交换了lat和lon
(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
Run Code Online (Sandbox Code Playgroud)