原理:哈弗赛恩公式
import math
def calculate_distance(lat1, lon1, lat2, lon2):
R = 6371 # 地球半径,单位为千米
rad = lambda angle: angle * math.pi / 180 # 将角度转换为弧度
lat1_rad = rad(lat1)
lon1_rad = rad(lon1)
lat2_rad = rad(lat2)
lon2_rad = rad(lon2)
dLat = lat2_rad - lat1_rad
dLon = lon2_rad - lon1_rad
a = math.sin(dLat / 2) ** 2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dLon / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c # 返回单位为千米的距离
return distance
# 示例用法
lat1 = 34.444444 # 北京的经纬度
lon1 = 112.257778
lat2 = 34.419 # 上海的经纬度
lon2 = 111.876
distance = calculate_distance(lat1, lon1, lat2, lon2)
print(distance) # 输出直线距离(单位:千米)