python根据经纬度计算距离
时间: 2023-08-31 19:09:51 浏览: 88
可以使用haversine公式来计算两个地点的距离。haversine公式是根据地球上两点的经纬度计算它们之间距离的一种公式。
以下是一个用Python实现haversine公式的例子:
```python
import math
def distance(lat1, lon1, lat2, lon2):
R = 6371 # 地球的半径,单位为公里
dLat = math.radians(lat2 - lat1)
dLon = math.radians(lon2 - lon1)
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
a = (math.sin(dLat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) *
math.sin(dLon / 2) ** 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
```
函数的参数是两个地点的纬度和经度。它返回的距离单位是公里。
相关问题
python 两经纬度计算距离
可以使用Python中的geopy库来计算两个经纬度之间的距离。下面是一个示例代码:
```python
from geopy.distance import geodesic
# 定义两个经纬度
coord1 = (31.2304, 121.4737) # 上海经纬度
coord2 = (39.9042, 116.4074) # 北京经纬度
# 计算两个经纬度之间的距离
distance = geodesic(coord1, coord2).km
print("两个经纬度之间的距离是:", distance, "千米")
```
输出结果为:
```
两个经纬度之间的距离是: 1068.9273170769022 千米
```
在上面的代码中,我们首先导入了geopy库中的geodesic函数。然后,我们定义了两个经纬度坐标,分别是上海和北京的经纬度。最后,我们使用geodesic函数计算了这两个经纬度之间的距离,并将结果以千米为单位打印出来。
python计算经纬度之间距离
以下是两种Python计算经纬度之间距离的方法:
1. 使用haversine公式计算经纬度之间的距离:
```python
import math
def haversine(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.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
distance = 6371 * c * 1000 # 结果以米为单位
return distance
# 示例使用
lon1 = 102.8083989
lat1 = 24.8962294
lon2 = 102.471938
lat2 = 24.912491
distance = haversine(lon1, lat1, lon2, lat2)
print("距离:", distance, "米")
```
2. 使用scipy库中的cdist函数计算经纬度之间的距离:
```python
from scipy.spatial.distance import cdist
lonlat1 = [[102.8083989, 24.8962294]] # 经度、纬度
lonlat2 = [[102.471938, 24.912491]] # 经度、纬度
distance = cdist(lonlat1, lonlat2, metric='euclidean')
distance = list(list(list(distance))[0] * 100000)[0] # 结果以米为单位
print("距离:", distance, "米")
```