distance method

double distance(
  1. Coordinates other, {
  2. bool ignoreAltitude = false,
})

Calculates the distance in meters between this coordinate and other.

The distance is computed using the Haversine (great-circle) formula. If both points contain non-null altitude values and ignoreAltitude is false, the vertical difference is included using Pythagorean combination.

Parameters

  • other: The other Coordinates to measure distance to.
  • ignoreAltitude: When false (default) and both coordinates have altitude values, include altitude difference in the final distance calculation.

Example

final coordinates1 = Coordinates(latitude: 48.858844, longitude: 2.294351);
final coordinates2 = Coordinates(latitude: 48.854520, longitude: 2.299751);

double distance = coordinates1.distance(coordinates2);

Returns

  • Distance in meters between this coordinate and other.

Implementation

double distance(final Coordinates other, {bool ignoreAltitude = false}) {
  const double earthRadius = 6371000; // Earth's radius in meters

  double toRadians(final double value) {
    return value * pi / 180; // Convert degrees to radians
  }

  final double deltaLatitude = toRadians(other.latitude - latitude);
  final double deltaLongitude = toRadians(other.longitude - longitude);

  final double a =
      sin(deltaLatitude / 2) * sin(deltaLatitude / 2) +
      cos(toRadians(latitude)) *
          cos(toRadians(other.latitude)) *
          sin(deltaLongitude / 2) *
          sin(deltaLongitude / 2);

  final double c = 2 * atan2(sqrt(a), sqrt(1 - a));

  double altitudeDifference = 0;
  if (!ignoreAltitude && other.altitude != null && altitude != null) {
    altitudeDifference = other.altitude! - altitude!;
  }

  final double distance = sqrt(
    (c * c * earthRadius * earthRadius) +
        (altitudeDifference * altitudeDifference),
  );

  return distance;
}