8

我正在设置一个小程序来从用户那里获取 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

问题是结果出来真的不准确。我是 python 新手,所以非常感谢一些帮助或建议!

4

4 回答 4

12

你有 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
于 2012-01-14T02:25:06.543 回答
4
于 2012-01-14T01:04:31.623 回答
4

您可以使用具有内置功能的 geopy 模块进行距离计算,向下滚动到以下链接中的“计算距离”: https ://pypi.python.org/pypi/geopy

于 2012-01-13T23:59:55.633 回答
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))) )
于 2012-01-14T00:01:26.693 回答