center property

LatLng get center

Calculates the center of a collection of geo coordinates

The function rounds the result to 6 decimals

Implementation

LatLng get center {
  if (coordinates.isEmpty) {
    throw AssertionError('Coordinates must not be empty!');
  }

  var X = 0.0;
  var Y = 0.0;
  var Z = 0.0;

  double lat, lon, hyp;

  for (final coordinate in coordinates) {
    lat = coordinate.latitudeInRad;
    lon = coordinate.longitudeInRad;

    X += cos(lat) * cos(lon);
    Y += cos(lat) * sin(lon);
    Z += sin(lat);
  }

  final nrOfCoordinates = coordinates.length;
  X = X / nrOfCoordinates;
  Y = Y / nrOfCoordinates;
  Z = Z / nrOfCoordinates;

  lon = atan2(Y, X);
  hyp = sqrt(X * X + Y * Y);
  lat = atan2(Z, hyp);

  return _latLngFactory(round(radianToDeg(lat)), round(radianToDeg(lon)));
}