haversine_distance python
时间: 2023-07-30 14:03:23 浏览: 241
Haversine_distance是一种用于计算两个经纬度之间距离的方法,通常用于地理定位应用程序中。在Python中,我们可以使用Haversine公式来计算两个坐标点之间的距离。
首先,我们需要导入math模块来使用数学函数。然后,我们可以定义一个函数haversine_distance来计算距离,该函数接受四个参数,分别是两个经度和纬度坐标对。
```
import math
def haversine_distance(lon1, lat1, lon2, lat2):
# 将经纬度从度数转换为弧度
lon1 = math.radians(lon1)
lat1 = math.radians(lat1)
lon2 = math.radians(lon2)
lat2 = math.radians(lat2)
# Haversine公式计算
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.pow(math.sin(dlat/2), 2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin(dlon/2), 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
r = 6371 # 地球平均半径,单位为千米
distance = c * r
return distance
```
以上代码会将输入的经纬度转换为弧度,然后使用Haversine公式计算两点之间的距离。最后,代码将距离返回。
要使用这个函数,你可以提供两个点的经纬度坐标作为输入,并调用函数来获取它们之间的距离,例如:
```
distance = haversine_distance(113.948105, 45.348085, 121.516145, 31.245944)
print("两个点之间的距离为:", distance, "千米")
```
上述代码的输出将会是两个点之间的距离,单位为千米。你可以根据自己的需求进行修改和扩展这个函数。
阅读全文
相关推荐


















