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公式:更高精度,适用于需要精确测量的情况。

相关推荐
Ray Liang1 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮4 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽5 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健20 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞21 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python