C++ 如何计算两个gps 的距离
C++ 完全可以计算 三维空间中的 WGS84 坐标点之间的精确欧氏距离。关键是:
要先把经纬度 + 海拔 (lat, lon, alt) 转换成 ECEF(地心地固坐标系),然后计算欧氏距离即可。
✅ 使用 GeographicLib::Geocentric
实现三维距离计算(官方推荐)
#include <GeographicLib/Geocentric.hpp>
#include <cmath>using namespace GeographicLib;double Compute3DDistance(double lat1, double lon1, double alt1,double lat2, double lon2, double alt2) {const Geocentric& earth = Geocentric::WGS84();double x1, y1, z1;earth.Forward(lat1, lon1, alt1, x1, y1, z1); // WGS84 → ECEFdouble x2, y2, z2;earth.Forward(lat2, lon2, alt2, x2, y2, z2);// 欧氏距离(单位:米)return std::sqrt((x1 - x2) * (x1 - x2) +(y1 - y2) * (y1 - y2) +(z1 - z2) * (z1 - z2));
}
✅ 安装 GeographicLib(Ubuntu)
sudo apt install libgeographic-dev
✅ 示例调用
double dist = Compute3DDistance(31.2304, 121.4737, 20.0, // 上海市,海拔 20m39.9042, 116.4074, 80.0); // 北京市,海拔 80m
printf("3D distance = %.2f meters\n", dist);
// 算出来是 3D distance = 1064608.92 meters
🔍 说明
- 使用
Geocentric::Forward()
代替自己写 ECEF 转换公式,可避免误差。 - 支持任意经纬度 + 高度(甚至负值,如海底)。
CMake Error at CMakeLists.txt:16 (find_package):By not providing "FindGeographicLib.cmake" in CMAKE_MODULE_PATH thisproject has asked CMake to find a package configuration file provided by"GeographicLib", but CMake did not find one.Could not find a package configuration file provided by "GeographicLib"with any of the following names:GeographicLibConfig.cmakegeographiclib-config.cmake
这个错误说明 GeographicLib
没有提供标准的 CMake 配置文件 (GeographicLibConfig.cmake
) 或你没有正确告诉 CMake 去哪里找它。
✅ 最简解决方案(不再使用 find_package
)
因为 GeographicLib
在很多系统上不带 CMake 配置文件,你可以手动添加头文件和链接库路径,不需要 find_package
,改成下面这样即可:
🔧 修改 CMakeLists.txt
(推荐方法)
假设你是在 Ubuntu 上用 apt
安装的:
# 添加头文件路径
include_directories(/usr/include)# 链接 GeographicLib 的核心库
target_link_libraries(your_target_nameGeographic
)
/usr/include
是 GeographicLib 默认头文件位置(GeographicLib/Geocentric.hpp
就在那)。Geographic
是实际要链接的动态库(libGeographic.so
)。
✅ 验证库存在
ls /usr/lib/x86_64-linux-gnu/libGeographic.so
如果有,说明你可以直接 target_link_libraries(... Geographic)
。
✅ 示例完整片段
add_executable(my_example main.cpp)include_directories(/usr/include)target_link_libraries(my_exampleGeographic
)
🛠️ 如果你是从源码安装 GeographicLib
你需要告诉 CMake:
cmake .. -DGeographicLib_DIR=/your/install/path/lib/cmake/GeographicLib
或者在 CMakeLists.txt
中手动指定:
set(GeographicLib_DIR "/your/install/path/lib/cmake/GeographicLib")
find_package(GeographicLib REQUIRED)