distanceTo method

double distanceTo(
  1. Coordinate other, {
  2. DistanceUnit? unit,
})

Returns the distance to a different Coordinate in meters or specified unit. Uses the Haversine formula to calculate the distance between two points.

Example:

Coordinate(1, 2).distanceTo(Coordinate(3, 4)); // 314635.33

Implementation

double distanceTo(Coordinate other, {DistanceUnit? unit}) {
  final lat1 = latitude * (pi / 180);
  final lon1 = longitude * (pi / 180);
  final lat2 = other.latitude * (pi / 180);
  final lon2 = other.longitude * (pi / 180);

  final dLat = lat2 - lat1;
  final dLon = lon2 - lon1;

  final a = sin(dLat / 2) * sin(dLat / 2) +
      cos(lat1) * cos(lat2) * sin(dLon / 2) * sin(dLon / 2);
  final c = 2 * atan2(sqrt(a), sqrt(1 - a));

  return convertDistance(
    6371000 * c,
    DistanceUnits.meters,
    unit ?? DistanceUnits.meters,
  );
}