我正在设置一个小程序,从用户那里获取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的新手,所以对您的帮助或建议将不胜感激!

最佳答案

您遇到了4或5或6个问题:

(1)end_lat = math.radians(end_long)应该是end_lat = math.radians(end_lat)
(2)您缺少某些人已经提到的东西,很可能是因为

(3)您的代码难以辨认(行太长,括号多余,“math”的17个无意义的实例。)

(4)您没有注意到Wikipedia文章中有关使用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

10-06 15:08