我正在设置一个小程序,从用户那里获取2个地理坐标,然后计算它们之间的距离(考虑到地球的曲率)。所以我查看维基百科的公式是here。
我基本上是基于它设置了我的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的新手,所以一些帮助或建议将不胜感激!
答案 0 :(得分: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
答案 1 :(得分:4)
您可以使用具有内置功能的geopy模块进行距离计算,向下滚动到"计算距离"在以下链接中: https://pypi.python.org/pypi/geopy
答案 2 :(得分:4)
这是有效的(根据工作示例@ http://en.wikipedia.org/wiki/Great-circle_distance,打印f返回2887.26 km):
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)
答案 3 :(得分:3)
我认为你在开始时错过了一个math.sin(d_long),应该是这个:
c = math.atan((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)) / ((math.sin(start_lat)*math.sin(end_lat)) + (math.cos(start_lat)*math.cos(end_lat)*math.cos(d_long))) )