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

V. *_*ndy 4 python distance haversine

我有一张地图,他们可以在其中找到几个点(纬度/经度)并想知道它们之间存在的距离。

那么,给定一组纬度/经度坐标,我如何在 python 中计算它们之间的距离?

cs9*_*s95 6

我曾经写过这个答案的 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)))
Run Code Online (Sandbox Code Playgroud)

确保传递给函数的坐标以弧度为单位。如果它们以度为单位,您可以先转换它们:

lng_1, lat_1, lng_2, lat_2 = map(math.radians, [lng_1, lat_1, lng_2, lat_2])
Run Code Online (Sandbox Code Playgroud)

  • 您必须先转换为弧度: lon_1, lat_1, lon_2, lat_2 = map(math.radians, [lon_1, lat_1, lon_2, lat_2]) (2认同)
  • @pepece我隐含地假设坐标以弧度为单位,因为这就是我为自己编写函数的方式。在答案中添加了注释,感谢您指出! (2认同)