Calculate the distance between lat/lon coordinates
1532 2 2020-5-28
Uploading and Loding Picture ...(0/1)
o(^-^)o
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;
}


2020-5-28
Use props
hdrpano
lvl.4
Flight distance : 598458 ft
  • >>>
Switzerland
Offline

In Xcode iOS we can use the inbuild function. func distance(from location: CLLocation) -> CLLocationDistance

Example in Swift

var firstLocation = CLLocation(latitude: 54.54545, longitude: 56.64646)
var secondLocation = CLLocation(latitude: 59.326354, longitude: 55.072310)

let distance = firstLocation.distance(from: secondLocation) / 1000
2020-5-29
Use props
DJI_Lisa
lvl.4
Hong Kong
Offline

hdrpano Posted at 5-29 05:36
In Xcode iOS we can use the inbuild function. func distance(from location: CLLocation) -> CLLocationDistance

Example in Swift

This is great - thanks!!  
2020-5-29
Use props
Advanced
You need to log in before you can reply Login | Register now

Credit Rules