通过2组经纬度计算距离
可执行程序在附件中,双击执行后如下图所示依次输入两组经纬度即可
代码实现也比较简单,如下所示:
#include <chrono>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <windows.h>
#define PI 3.1415926535897932384626433832795
#define EARTH_RADIUS 6378.137 // 地球长半径 KM
// 角度→弧度
double degreesToRadians(double degree)
{
return degree * PI / 180.0;
}
// lat1第一个点纬度,lng1第一个点经度,lat2第二个点纬度,lng2第二个点经度
double calculateDistance(double lat1, double lng1, double lat2, double lng2)
{
double a;
double b;
double radLat1 = degreesToRadians(lat1);
double radLat2 = degreesToRadians(lat2);
a = radLat1 - radLat2;
b = degreesToRadians(lng1) - degreesToRadians(lng2);
double s = 2 * asin(sqrt(pow(sin(a / 2), 2) + cos(radLat1) * cos(radLat2) * pow(sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = s * 1000;
return s;
}
int main(int argc, char* argv[])
{
while (1)
{
double lat1, lon1, lat2, lon2;
std::cout << "请输入第1个Lat:";
std::cin >> lat1;
std::cout << "请输入第1个Lon:";
std::cin >> lon1;
std::cout << "请输入第2个Lat:";
std::cin >> lat2;
std::cout << "请输入第2个Lon:";
std::cin >> lon2;
double result = calculateDistance(lat1, lon1, lat2, lon2);
std::cout << "测量距离为:" << result << "米" << std::endl;
}
return 0;
}