计算两个经纬度之间的实际距离(Haversine公式)----c++

来源:https://www.open-open.com/lib/view/open1430573897802.html

原理亦可参考:https://blog.csdn.net/gaocuisheng/article/details/126060795

cpp 复制代码
#include <cmath>
#define EARTH_RADIUS  6371.0;// 地球半径,单位千米

static double HaverSin(double theta)
{
    double v = sin(theta / 2);
    return v * v;
}

static double ConvertDegreesToRadians(double degrees)
{
    return degrees * M_PI / 180;
}

	/// <summary>
	/// 计算2个经纬度之间的距离
	/// </summary>
	/// <param name="from_lon">起始点经度</param>
	/// <param name="from_lat">起始点纬度</param>
	/// <param name="to_lon">目标点经度</param>
	/// <param name="to_lat">目标点纬度</param>
	/// <returns></returns>
static double TwoPointToDistance(double from_lon, double from_lat, double to_lon, double to_lat)
{
    // 用 haversine 公式计算球面两点间的距离。
    // 经纬度转换成弧度
    from_lon = ConvertDegreesToRadians(from_lon);
    from_lat = ConvertDegreesToRadians(from_lat);
    to_lon = ConvertDegreesToRadians(to_lon);
    to_lat = ConvertDegreesToRadians(to_lat);
    // 差值
    double vLon = std::abs(from_lon - to_lon);
    double vLat = std::abs(from_lat - to_lat);
    // h is the great circle distance in radians, great circle 就是一个球体上的切面,它的圆心即是球心的一个周长最大的圆。
    double h = HaverSin(vLat) + cos(from_lat) * cos(to_lat) * HaverSin(vLon);
    auto sh = sqrt(h);
    double distance = 2 * (asin(sqrt(h))) * EARTH_RADIUS;

    // 将距离转换为米
    distance *= 1000;

    return distance;
}

int main() {
    // 39.94607,116.32793  31.24063,121.42575
    std::cout << TwoPointToDistance(39.94607, 116.32793, 31.24063, 121.42575) << " meters" << std::endl;

    return 0;
}
相关推荐
superior tigre5 分钟前
22 括号生成
算法·深度优先
炘爚25 分钟前
C语言(文件操作)
c语言·开发语言
阿蒙Amon28 分钟前
C#常用类库-详解SerialPort
开发语言·c#
凸头1 小时前
CompletableFuture 与 Future 对比与实战示例
java·开发语言
wuqingshun3141591 小时前
线程安全需要保证几个基本特征
java·开发语言·jvm
君义_noip1 小时前
信息学奥赛一本通 1952:【10NOIP普及组】三国游戏 | 洛谷 P1199 [NOIP 2010 普及组] 三国游戏
c++·信息学奥赛·csp-s
Moksha2621 小时前
5G、VoNR基本概念
开发语言·5g·php
努力也学不会java1 小时前
【缓存算法】一篇文章带你彻底搞懂面试高频题LRU/LFU
java·数据结构·人工智能·算法·缓存·面试
jzlhll1231 小时前
kotlin Flow first() last()总结
开发语言·前端·kotlin
W.D.小糊涂1 小时前
gpu服务器安装windows+ubuntu24.04双系统
c语言·开发语言·数据库