DJI_Lisa
lvl.4
Hong Kong
Offline
|
Since the earth is a sphere, the spherical law of cosines is needed to calculate the distance between two latitude and longitude coordinates. The formula is:
S = R · arccos [cosβ1cosβ2cos (α1-α2) + sinβ1sinβ2]
The corresponding calculation code is:
double getDistance (double lat1, double lng1, double lat2, double lng2)
{
double s = acos (cos (lat1) * cos (lat2) * cos (lng1-lng2) + sin (lat1) * sin (lat2));
s = s * EarthCenter; // EarthCenter = 6378137 return s; // The unit of return value is m
}
Note #1: the function of the parameters are all latitude and longitude expressed in radians. Longitude to radian only needs to be multiplied by 0.0174533 to get the cos (lng1-lng2) term in the spherical cosine formula above.
Note #2: the cosine formula will give a result of 0.99999 resulting in a larger rounding error.
The Haversine Formula method performs a transformation to eliminate the cos (lng1-lng2) term, which avoids the rounding error problem. The code is as follows:
double getDistance (double lat1, double lng1, double lat2, double lng2)
{
double a = lat1-lat2;
double b = lng1-lng2;
double s = 2 * asin (sqrt (pow (sin (a / 2), 2) + cos (lat1) * cos (lat2) * pow (sin (b / 2), 2)));
s = s * EarthCenter ;
return s;
}
|
|