center property

LatLng center

Calculates the center of a collection of geo coordinates

The function rounds the result to 6 decimals

Implementation

LatLng get center {
  Validate.notEmpty(coordinates, "Coordinates must not be empty!");

  double X = 0.0;
  double Y = 0.0;
  double Z = 0.0;

  for (var coordinate in coordinates) {
    double lat = coordinate.latitudeInRad;
    double lng = coordinate.longitudeInRad;

    X += math.cos(lat) * math.cos(lng);
    Y += math.cos(lat) * math.sin(lng);
    Z += math.sin(lat);
  }

  int numCoordinates = coordinates.length;

  X = X / numCoordinates;
  Y = Y / numCoordinates;
  Z = Z / numCoordinates;

  double hyp = math.sqrt(X * X + Y * Y);
  double latitude = math.atan2(Z, hyp);
  double longitude = math.atan2(Y, X);

  latitude = round(radianToDeg(latitude));
  longitude = round(radianToDeg(longitude));

  return geoPositionFactory(latitude, longitude);
}