distanceCoordsHaversine function
Calculates the distance in meters between point A at spherical
(latitude, longitude) coordinates (latADeg
, longADeg
) and B at
(latBDeg
, longBDeg
) - all in degrees, using the haversine formula.
earthRadiusMeters
can be used to specify a radius to be used other than
the mean earth radius.
The result is very accurate for a perfectly spherical earth and has up to about 0.3% error compared to the ellipsoidal shape of the earth. Based on https://www.movable-type.co.uk/scripts/latlong.html.
Implementation
double distanceCoordsHaversine(
double latADeg, double longADeg, double latBDeg, double longBDeg,
{earthRadiusMeters = EarthRadiusMeters.mean}) {
final latARad = degToRad(latADeg);
final latBRad = degToRad(latBDeg);
final deltaLatRad =
degToRad(deltaLatitudeAbs(latADeg, latBDeg)); // latBRad - latARad;
final deltaLongRad =
degToRad(deltaLongitudeAbs(longADeg, longBDeg)); //longBDeg - longADeg);
final sinHalfDeltaLatRad = sin(deltaLatRad / 2);
final sinHalfDeltaLongRad = sin(deltaLongRad / 2);
final a = sinHalfDeltaLatRad * sinHalfDeltaLatRad +
cos(latARad) * cos(latBRad) * sinHalfDeltaLongRad * sinHalfDeltaLongRad;
final c = 2 * atan2(sqrt(a), sqrt(1 - a));
return earthRadiusMeters * c;
}