若知道地球表面两点之间的经纬度,那么便可以计算两点之间的实际距离,其数学公式推导可参考:
https://download.youkuaiyun.com/download/niu_88/10759266
下面函数中三种方法等价,都可直接使用。
/*
* 计算北京<=====>深圳距离:
北京经度--》116.46 纬度--》39.92
深圳经度--》114.058 纬度--》22.54
计算得距离:1947.98公里
*/
#include "stdio.h"
#include "math.h"
#include "iostream"
using namespace std;
typedef unsigned int uint32_t;
typedef int int32_t;
typedef char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
/*===================================================================================
函数名 :GpsDistance(int32_t nLng1, int32_t nLat1, int32_t nLng2, int32_t nLat2)
输入参数 :当前经纬度 nLng1, nLat1
前者经纬度 nLng2, nLat2
单位 度*1e7
输出参数 :无
返回值 :地球两点之间表面距离,单位:m
作者 :牛哥哥
创建时间 :2018.11.02
修改历史 :xxx
=================================================================================== */
double GpsDistance(int32_t nLng1, int32_t nLat1, int32_t nLng2, int32_t nLat2)
{
double dLat1, dLat2, dDeltLng, R, dInAngelRad;
double dPi = 3.1415926;
R = 6378137.0;
dLat1 = nLat1*dPi / 180.0 / (1.0e7f);
dLat2 = nLat2*dPi / 180.0 / (1.0e7f);
dDeltLng = (nLng2 - nLng1)*dPi / 180.0 / (1.0e7f);
//方法1
//dInAngelRad = acos(cos(dLat2 - dLat1) + cos(dLat1)*cos(dLat2)*(cos(dDeltLng) - (double)1.0));
//方法2
//dInAngelRad = acos(sin(dLat1)*sin(dLat2) + cos(dLat1)*cos(dLat2)*cos(dDeltLng));
//方法3
dInAngelRad = 2 * asin(sqrt(sin((dLat1 - dLat2) / 2)*sin((dLat1 - dLat2) / 2) + sin(dDeltLng / 2)*sin(dDeltLng / 2)*cos(dLat1)*cos(dLat2)));
R = R*dInAngelRad;
return R;
}
int main()
{
double distance;
distance = GpsDistance(114.058e7, 22.54e7, 116.46e7, 39.92e7);
cout << "北京到深圳的是 " << distance/1000.0f << " 公里" << endl;
return 0;
}