C++大地计算,由两点经纬度计算距离方位
时间: 2023-11-09 14:07:00 浏览: 222
利用经纬度计算两点之间的距离
5星 · 资源好评率100%
使用C++可以通过以下公式计算两点之间的距离和方位:
1. 将经度和纬度转换为弧度:
```
double deg2rad(double deg) {
return (deg * PI / 180);
}
double lat1_rad = deg2rad(lat1);
double lon1_rad = deg2rad(lon1);
double lat2_rad = deg2rad(lat2);
double lon2_rad = deg2rad(lon2);
```
其中,PI为圆周率,需要定义。
2. 计算两点之间的距离:
```
double dlon = lon2_rad - lon1_rad;
double dlat = lat2_rad - lat1_rad;
double a = pow(sin(dlat / 2), 2) + cos(lat1_rad) * cos(lat2_rad) * pow(sin(dlon / 2), 2);
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
double distance = R * c;
```
其中,R为地球半径,需要定义。
3. 计算两点之间的方位:
```
double y = sin(dlon) * cos(lat2_rad);
double x = cos(lat1_rad) * sin(lat2_rad) - sin(lat1_rad) * cos(lat2_rad) * cos(dlon);
double angle = atan2(y, x);
double bearing = fmod((angle * 180 / PI + 360), 360);
```
其中,bearing为方位角,需要定义。
完整代码如下:
```c++
#include <iostream>
#include <cmath>
#define PI 3.14159265358979323846
#define R 6371 // 地球半径,单位为千米
double deg2rad(double deg) {
return (deg * PI / 180);
}
int main() {
double lat1, lon1, lat2, lon2;
std::cout << "请输入第一个点的纬度和经度(以度为单位,用逗号隔开):" << std::endl;
std::cin >> lat1 >> lon1;
std::cout << "请输入第二个点的纬度和经度(以度为单位,用逗号隔开):" << std::endl;
std::cin >> lat2 >> lon2;
double lat1_rad = deg2rad(lat1);
double lon1_rad = deg2rad(lon1);
double lat2_rad = deg2rad(lat2);
double lon2_rad = deg2rad(lon2);
double dlon = lon2_rad - lon1_rad;
double dlat = lat2_rad - lat1_rad;
double a = pow(sin(dlat / 2), 2) + cos(lat1_rad) * cos(lat2_rad) * pow(sin(dlon / 2), 2);
double c = 2 * atan2(sqrt(a), sqrt(1 - a));
double distance = R * c;
double y = sin(dlon) * cos(lat2_rad);
double x = cos(lat1_rad) * sin(lat2_rad) - sin(lat1_rad) * cos(lat2_rad) * cos(dlon);
double angle = atan2(y, x);
double bearing = fmod((angle * 180 / PI + 360), 360);
std::cout << "两点之间的距离为:" << distance << "千米" << std::endl;
std::cout << "两点之间的方位为:" << bearing << "度" << std::endl;
return 0;
}
```
阅读全文