Python计算经纬度两点之间距离

在Python中计算两个经纬度之间的距离有多种方法,常用的包括Haversine公式和Vincenty公式。下面是这两种方法的实现示例。

  1. Haversine公式

Haversine公式是一种简单且常用的计算地球表面两点之间最短距离(大圆距离)的方法。

复制代码
import math

def haversine_distance(lat1, lon1, lat2, lon2):
    # 地球半径,单位:公里
    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

# 示例使用
lat1, lon1 = 34.052235, -118.243683  # 洛杉矶的经纬度
lat2, lon2 = 40.712776, -74.005974   # 纽约的经纬度

distance = haversine_distance(lat1, lon1, lat2, lon2)
print(f"Distance using Haversine formula: {distance} km")
  1. Vincenty公式

Vincenty公式提供了更高的精度,适用于需要精确测量的情况。

第一种使用geographiclib库

复制代码
pip install geographiclib

from geographiclib.geodesic import Geodesic

def vincenty_distance(lat1, lon1, lat2, lon2):
    geod = Geodesic.WGS84  # 使用WGS84椭球体模型
    result = geod.Inverse(lat1, lon1, lat2, lon2)
    distance = result['s12'] / 1000.0  # 距离单位:公里
    return distance

# 示例使用
lat1, lon1 = 34.052235, -118.243683  # 洛杉矶的经纬度
lat2, lon2 = 40.712776, -74.005974   # 纽约的经纬度

distance = vincenty_distance(lat1, lon1, lat2, lon2)
print(f"Distance using Vincenty formula: {distance} km")

第二种使用geopy库

复制代码
pip install geopy

from geopy.distance import geodesic

def calculate_distance_with_geopy(lat1, lon1, lat2, lon2):
    # 定义两个点
    point1 = (lat1, lon1)
    point2 = (lat2, lon2)
    
    # 计算两点之间的距离
    distance = geodesic(point1, point2).kilometers
    return distance

# 示例使用
lat1, lon1 = 34.052235, -118.243683  # 洛杉矶的经纬度
lat2, lon2 = 40.712776, -74.005974   # 纽约的经纬度

distance = calculate_distance_with_geopy(lat1, lon1, lat2, lon2)
print(f"Distance using Vincenty formula: {distance} km")

总结

Haversine公式:简单易用,适合大多数情况。

Vincenty公式:更高精度,适用于需要精确测量的情况。

相关推荐
廿士14 分钟前
python脚本使用相关
python
青 春 记 忆30 分钟前
零基础入门python19:Flask账本第一步——应用工厂、蓝图和健康检查
python·flask·后端开发
朦胧之34 分钟前
Python 后端核心知识
python
mqiqe1 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim1 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
denggun123451 小时前
yield
前端·数据库·python
脉动数据行情1 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股
爱学习的小邓同学1 小时前
Golang --- (1)第一个Golang程序
开发语言·后端·golang
zx_741484812 小时前
【Python 入门】面向对象基础:类、对象、成员变量与构造方法
开发语言·python
招财小梗2 小时前
沈阳商贸公司AI企业服务优势几何?
大数据·人工智能·python