在处理GPS数据时,经常会给出两点的距离,来计算两点之间的距离,这个距离大致可看作直线距离,python版本代码如下所示:
from math import radians, cos, sin, asin, sqrt
def get_distance(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# 将十进制度数转化为弧度
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine公式
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # 地球平均半径,单位为公里
return c * r * 1000
# 如第一个点的经纬度为(lon1, lat1),第二个点的经纬度为(lon2, lat2)
print(get_distance(lon1, lat1, lon2, lat2))