python怎么通过调用列表中的多个点的经纬度坐标的元组计算两点间距离,并在输出结果中显示结果显示两点名称,不用geopy库
时间: 2024-05-05 15:18:27 浏览: 110
Python中如何利用经纬度进行距离计算
你好,关于你的问题,你可以使用以下的代码来计算两个坐标点之间的距离:
```python
from math import radians, sin, cos, acos
def distance(lat1, lon1, lat2, lon2):
"""
Calculate the distance between two points using the haversine formula
"""
earth_radius = 6371 # in kilometers
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# haversine formula
dlat = lat2 - lat1
dlon = lon2 - lon1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * acos(a)
# calculate the distance
distance = earth_radius * c
return distance
# sample data
locations = [
{'name': 'Location 1', 'coordinates': (39.986749, 116.268007)},
{'name': 'Location 2', 'coordinates': (39.980114, 116.313288)},
{'name': 'Location 3', 'coordinates': (39.948938, 116.365868)}
]
# calculate the distances for all pairs of locations
for i in range(len(locations)):
for j in range(i+1, len(locations)):
loc1 = locations[i]
loc2 = locations[j]
dist = distance(loc1['coordinates'][0], loc1['coordinates'][1],
loc2['coordinates'][0], loc2['coordinates'][1])
print(f"{loc1['name']} and {loc2['name']} are {dist:.2f} kilometers apart.")
```
在上面的示例代码中,我们使用了海卫氏公式来计算地球上两个坐标点之间的距离。示例数据包含三个位置和它们的坐标点。我们使用嵌套循环来计算每对位置之间的距离,并将结果显示在屏幕上。
希望这可以帮助您解决问题。如果您有其他问题,请随时问我。
阅读全文