LatLngBounds.fromPoints constructor

LatLngBounds.fromPoints(
  1. List<LatLng> points, {
  2. bool drawInSingleWorld = false,
})

Create a new LatLngBounds from a list of LatLng points. This calculates the bounding box of the provided points.

Implementation

factory LatLngBounds.fromPoints(
  List<LatLng> points, {
  bool drawInSingleWorld = false,
}) {
  assert(
    points.isNotEmpty,
    'LatLngBounds cannot be created with an empty List of LatLng',
  );
  if (drawInSingleWorld) {
    const double halfWorld = 180;
    double previousLongitude = points.first.longitude;
    double minX = previousLongitude;
    double maxX = minX;
    double minY = maxLatitude;
    double maxY = minLatitude;
    for (final point in points) {
      double longitude = point.longitude;
      while (longitude - previousLongitude >= halfWorld) {
        longitude -= 2 * halfWorld;
      }
      while (longitude - previousLongitude <= -halfWorld) {
        longitude += 2 * halfWorld;
      }
      if (minX > longitude) {
        minX = longitude;
      }
      if (maxX < longitude) {
        maxX = longitude;
      }
      if (point.latitude < minY) minY = point.latitude;
      if (point.latitude > maxY) maxY = point.latitude;
      previousLongitude = longitude;
    }
    return LatLngBounds.worldSafe(
      north: maxY,
      south: minY,
      longitudeCenter: (maxX + minX) / 2,
      longitudeWidth: maxX - minX,
    );
  }
  // initialize bounds with max values.
  double minX = maxLongitude;
  double maxX = minLongitude;
  double minY = maxLatitude;
  double maxY = minLatitude;
  // find the largest and smallest latitude and longitude
  for (final point in points) {
    if (point.longitude < minX) minX = point.longitude;
    if (point.longitude > maxX) maxX = point.longitude;
    if (point.latitude < minY) minY = point.latitude;
    if (point.latitude > maxY) maxY = point.latitude;
  }
  return LatLngBounds.unsafe(
    north: maxY,
    south: minY,
    east: maxX,
    west: minX,
  );
}