distanceTo method
Returns the distance from the current position to destination
along a
rhumb line.
Parameters:
radius
: The radius of earth (defaults to mean radius in metres).
The distance between this position and the destination is measured in same units as the given radius.
Examples:
const p1 = Geographic(lat: 51.127, lon: 1.338);
const p2 = Geographic(lat: 50.964, lon: 1.853);
final d = p1.rhumb.distanceTo(p2); // 40.31 km
Implementation
@override
double distanceTo(
Geographic destination, {
double radius = 6371000.0,
}) {
if (position == destination) return 0.0;
// see www.edwilliams.org/avform.htm#Rhumb
final lat1 = position.lat.toRadians();
final lat2 = destination.lat.toRadians();
final dlat = lat2 - lat1;
var dlon = (destination.lon - position.lon).toRadians();
// if dlon over 180° take shorter rhumb line across the anti-meridian:
if (dlon.abs() > pi) {
dlon = dlon > 0.0 ? -(2.0 * pi - dlon) : (2.0 * pi + dlon);
}
// on Mercator projection, longitude distances shrink by latitude
// q is the 'stretch factor'
// q becomes ill-conditioned along E-W line (0/0)
// use empirical tolerance to avoid it (note ε is too small)
final dlatProj =
log(tan(lat2 / 2.0 + pi / 4.0) / tan(lat1 / 2.0 + pi / 4.0));
final q = dlatProj.abs() > 10e-12 ? dlat / dlatProj : cos(lat1);
// distance is pythagoras on 'stretched' Mercator projection, √(Δφ² + q²·Δλ²)
final dst =
sqrt(dlat * dlat + q * q * dlon * dlon); // angular distance in radians
return dst * radius;
}