我的程序在给定两个纬度和经度值的情况下计算两公里之间的距离(公里数)。
#include<iostream>
#include <cmath>
#define pi 3.14159265358979323846
using namespace std;
double calculateDistance(double lat1, double long1, double lat2, double long2) {
double dist;
dist = sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(long1 - long2);
dist = acos(dist);
dist = (6371 * pi * dist) / 180;
return dist;
}
int main() {
cout << calculateDistance(51.752021, -1.257726, 51.507351, -0.127758);
return 0;
}
这是我试图实施的公式:
我用来测试输出的计算器http://www.movable-type.co.uk/scripts/latlong.html表示答案应该是82.60km。 (我得到33.6227公里)
答案 0 :(得分:1)
这样的事情应该有效(尽管没有经过测试):
double toRad(double degree) {
return degree/180 * pi;
}
double calculateDistance(double lat1, double long1, double lat2, double long2) {
double dist;
dist = sin(toRad(lat1)) * sin(toRad(lat2)) + cos(toRad(lat1)) * cos(toRad(lat2)) * cos(toRad(long1 - long2));
dist = acos(dist);
// dist = (6371 * pi * dist) / 180;
//got dist in radian, no need to change back to degree and convert to rad again.
dist = 6371 * dist;
return dist;
}
答案 1 :(得分:0)
您可以尝试一下,对我来说,它的工作原理更为精确。 我为此使用了Haversine公式。
#include <iostream>
#include <math.h>
#include <algorithm>
#define PI 3.14159265358979323846
#define RADIO_TERRESTRE 6372797.56085
#define GRADOS_RADIANES PI / 180
using namespace std;
float CalcGPSDistance(float latitud1, float longitud1, float latitud2, float longitud2){
double haversine;
double temp;
double distancia_puntos;
latitud1 = latitud1 * GRADOS_RADIANES;
longitud1 = longitud1 * GRADOS_RADIANES;
latitud2 = latitud2 * GRADOS_RADIANES;
longitud2 = longitud2 * GRADOS_RADIANES;
haversine = (pow(sin((1.0 / 2) * (latitud2 - latitud1)), 2)) + ((cos(latitud1)) * (cos(latitud2)) * (pow(sin((1.0 / 2) * (longitud2 - longitud1)), 2)));
temp = 2 * asin(min(1.0, sqrt(haversine)));
distancia_puntos = RADIO_TERRESTRE * temp;
return distancia_puntos;
}
int main(){
cout << CalcGPSDistance(37.824574,-2.533276,37.821897,-2.537297)<< endl;
return 0;
}