calculateBestCenter method

TLocationComponents calculateBestCenter({
  1. required Set<TLocationComponents> locations,
  2. required double threshold,
  3. required DistanceUnit distanceUnit,
})

Calculates the best center for a set of locations. This is the geometric center unless the distance to the closest marker is greater than the threshold, then the closest marker is used. The distanceUnit is the unit of the threshold.

Implementation

TLocationComponents calculateBestCenter({
  required Set<TLocationComponents> locations,
  required double threshold,
  required DistanceUnit distanceUnit,
}) {
  if (locations.isEmpty) {
    return (
      latitude: 0.0,
      longitude: 0.0,
      altitude: 0.0,
    );
  }
  var center = calculateGeometricCenter(locations);
  var closestMarker = locations.first;
  var minDistance = calculateHavershire3DDistance(
    location1: center,
    location2: closestMarker,
    unit: distanceUnit,
  );
  for (final marker in locations.skip(1)) {
    final distance = calculateHavershire3DDistance(
      location1: center,
      location2: marker,
      unit: distanceUnit,
    );
    if (distance < minDistance) {
      closestMarker = marker;
      minDistance = distance;
    }
  }
  if (minDistance > threshold) {
    center = closestMarker;
  }
  return center;
}