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

相关推荐
李昊哲小课2 小时前
fastapi sse websocket 奶茶店实时订单看板
人工智能·python·websocket·网络协议·fastapi·sse
格林威2 小时前
多相机微秒级对齐:硬件触发 vs PTP(IEEE 1588)方案实战对比
开发语言·人工智能·数码相机·机器学习·计算机视觉·视觉检测·机器视觉
初级代码游戏3 小时前
iOS开发 Swift 速记2:三种集合类型 Array Set Dictionary
开发语言·ios·swift
2401_844582954 小时前
工具包:软件架构设计的实用技巧与经验分享
python
RFID固定资产管理系统4 小时前
适配媒体行业的固定资产管理软件有哪些功能与核心优势
大数据·人工智能·python·媒体
SunnyDays10114 小时前
Python 为 PowerPoint 添加动画:进入、退出、动作路径与文本动画(详解)
python·powerpoint·动画·动画效果·文本动画
峥嵘life5 小时前
Android WiFi 热点 Channel 信道 和 Frequency 频率 转换总结
android·开发语言
wgego5 小时前
基础的反序列化一些总结(php和java)
java·开发语言·笔记
冻柠檬飞冰走茶5 小时前
PTA基础编程题目集 7-8超速判断(C++语言实现)
开发语言·数据结构·c++·算法
难以怀瑾6 小时前
pytest.param`与 allure.dynamic.title()全解析
python