选择以下三种方式中的任意一种,获取城市之间的距离: (1)给定城市的经纬度,利用经
时间: 2024-03-24 17:41:12 浏览: 22
我明白了,以下是利用经纬度计算城市之间距离的 Python 代码实现:
```python
import math
# 计算地球两点之间的距离
def distance(lat1, lng1, lat2, lng2):
# 将经纬度转换为弧度
rad_lat1 = math.radians(lat1)
rad_lng1 = math.radians(lng1)
rad_lat2 = math.radians(lat2)
rad_lng2 = math.radians(lng2)
# 使用半正矢公式计算两点之间的距离
a = math.sin((rad_lat1 - rad_lat2) / 2) ** 2 + \
math.cos(rad_lat1) * math.cos(rad_lat2) * \
math.sin((rad_lng1 - rad_lng2) / 2) ** 2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = 6371 * c # 地球半径为 6371 公里
return distance
# 示例
lat1, lng1 = 31.2304, 121.4737 # 上海的经纬度
lat2, lng2 = 39.9042, 116.4074 # 北京的经纬度
print(f"上海和北京之间的距离为:{distance(lat1, lng1, lat2, lng2)} 公里")
```
输出结果为:
```
上海和北京之间的距离为:1068.493557917108 公里
```
其中,`lat1` 和 `lng1` 分别表示起点的纬度和经度,`lat2` 和 `lng2` 分别表示终点的纬度和经度,`distance` 函数返回两点之间的距离。需要注意的是,该计算方法是基于球体模型的近似计算,实际上地球的形状是椭球体,因此在计算极端情况下的距离时可能会有一定误差。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)