distanceTo method

double distanceTo(
  1. GeoPoint other, {
  2. UnitOfLength unitOfLength = UnitOfLength.meters,
})

Calculates distance to another geographical point.

Example

final sanFrancisco = GeoPoint(37.7749, -122.4194);
final london = GeoPoint(51.5074, -0.1278);

// Meters
final distance = london.distanceTo(sanFrancisco);

// Miles
final distanceInMiles = london.distanceTo(
  sanFrancisco,
  unitOfLength: UnitOfLength.miles,
);

Implementation

double distanceTo(GeoPoint other,
    {UnitOfLength unitOfLength = UnitOfLength.meters}) {
  final lat0 = _toRadians(latitude);
  final lon0 = _toRadians(longitude);
  final lat1 = _toRadians(other.latitude);
  final lon1 = _toRadians(other.longitude);
  final dlon = lon1 - lon0;
  final dlat = lat1 - lat0;
  final a = pow(sin(dlat / 2), 2.0) +
      cos(lat0) * cos(lat1) * pow(sin(dlon / 2), 2.0);
  final c = 2 * atan2(sqrt(a), sqrt(1 - a));
  const _radius = 6378137.0;
  return UnitOfLength.meters.convertDouble(c * _radius, to: unitOfLength);
}