根据地图上两个点的经纬度,算出他们的距离,通过python代码来实现:
import math
def haversine(lat1, lon1, lat2, lon2):
# 将经纬度转换为弧度
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
# haversine公式
dlat = lat2 - lat1
dlon = lon2 - lon1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
# 地球平均半径,单位:千米
earth_radius = 6371
distance = c * earth_radius
return distance
# 示例:计算北京(39.9042, 116.4074)与上海(31.2304, 121.4737)之间的距离
distance = haversine(39.9042, 116.4074, 31.2304, 121.4737)
print("两个点之间的距离为: {:.2f} 千米".format(distance))
文章评论