可以使用haversine公式或geopy库计算两地间的大圆距离。1. 手动实现haversine公式,通过经纬度转弧度、计算球面差值与地球半径乘积得距离;2. 推荐使用geopy库的geodesic方法,基于WGS-84椭球模型更精确;3. 注意坐标顺序为(纬度, 经度),避免颠倒,且长距离需考虑地球曲率,单位可选千米、米或英里。

已知两个坐标的经纬度,可以使用Python中的地理距离计算方法来求它们之间的距离。最常用的方式是利用haversine公式计算地球表面两点间的**大圆距离**(近似直线距离)。也可以使用第三方库简化操作。
假设两个点的经纬度分别为 (lat1, lon1) 和 (lat2, lon2),单位为度。以下是实现代码:
import math <p>def calculate_distance(lat1, lon1, lat2, lon2):</p><h1>地球半径(千米)</h1><pre class='brush:python;toolbar:false;'>R = 6371.0 # 将经纬度转换为弧度 lat1_rad = math.radians(lat1) lon1_rad = math.radians(lon1) lat2_rad = math.radians(lat2) lon2_rad = math.radians(lon2) # 计算差值 dlat = lat2_rad - lat1_rad dlon = lon2_rad - lon1_rad # haversine 公式 a = math.sin(dlat / 2)**2 + math.cos(lat1_rad) * math.cos(lat2_rad) * math.sin(dlon / 2)**2 c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) # 距离(千米) distance = R * c return distance
beijing = (39.9042, 116.4074) shanghai = (31.2304, 121.4737)
dist = calculate_distance(beijing[0], beijing[1], shanghai[0], shanghai[1]) print(f"两地距离约为: {dist:.2f} 千米")
更简单的方法是使用 geopy 库,它封装了多种距离计算方式。
立即学习“Python免费学习笔记(深入)”;
# 安装命令:pip install geopy
<p>from geopy.distance import geodesic</p><h1>坐标格式:(纬度, 经度)</h1><p>point1 = (39.9042, 116.4074) # 北京
point2 = (31.2304, 121.4737) # 上海</p><h1>计算距离</h1><p>distance = geodesic(point1, point2).kilometers
print(f"两地距离为: {distance:.2f} 千米")</p>geopy 使用的是更精确的椭球模型(WGS-84),比球面假设更准确。
基本上就这些,根据是否允许安装第三方库选择合适方法。
以上就是如何使用Python已知两坐标求距离?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号