使用Python计算两个坐标之间的距离

5

我有一张地图,上面标记了多个点的纬度和经度,并想要知道它们之间的距离。

因此,给定一组纬度和经度坐标,在Python中如何计算它们之间的距离?


1个回答

10

我曾经写过一篇Python版本的这个答案。它详细介绍了使用Haversine公式来计算距离(以千米为单位)的方法。

import math

def get_distance(lat_1, lng_1, lat_2, lng_2): 
    d_lat = lat_2 - lat_1
    d_lng = lng_2 - lng_1 

    temp = (  
         math.sin(d_lat / 2) ** 2 
       + math.cos(lat_1) 
       * math.cos(lat_2) 
       * math.sin(d_lng / 2) ** 2
    )

    return 6373.0 * (2 * math.atan2(math.sqrt(temp), math.sqrt(1 - temp)))

确保传递给函数的坐标为弧度制。如果它们是以度数表示的,可以先进行转换:

lng_1, lat_1, lng_2, lat_2 = map(math.radians, [lng_1, lat_1, lng_2, lat_2])

输出结果是以米为单位吗?对我来说这并没有起作用。 - Gianmar
输出以公里为单位,若需要以米为单位,则需将数值乘以1000。 - Gianmar
3
你必须先将角度转换为弧度:lon_1、lat_1、lon_2、lat_2 = map(math.radians,[lon_1、lat_1、lon_2、lat_2]) - pepece
2
@pepece 我默认坐标是弧度制,因为这是我为自己编写函数的方式。在答案中添加了一条注释,感谢您指出! - cs95

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接