Search code examples
fluttergoogle-mapsdartlatitude-longitudebounds

Flutter. GoogleMap. I need to find LatLngBounds from a list of LatLng(latitude, longitude) on screen?


I am using this package: [google_maps_flutter: ^2.0.1][1]

And i have this list of LatLng:

List<LatLng> _list = [
  LatLng(PointA.lat, PointA.lng), // Point A
  LatLng(PointB.lat, PointB.lng), // Point B
  LatLng(PointC.lat, PointC.lng), // Point C
  LatLng(PointD.lat, PointD.lng), // Point D
];

I need a CameraPosition which contains all this Points:

  final _cameraPosition = CameraUpdate.newLatLngBounds(
    LatLngBounds(
      southwest: LatLng(southwestPoint.lat,southwestPoint.lng), // southwest Point
      northeast: LatLng(northeastPoint.lat,northeastPoint.lng)  // northeast Point
      ), padding);

Graphically demonstrating enter image description here


Solution

  • You can use LatLngBounds.extend:

    var bounds = LatLngBounds();
    for (var latlng in _list) bounds.extend(latlng);
    

    Edit: this code works with the google_maps package but the LatLng in google_maps_flutter doesn't expose this method.

    A simple solution is to compute the max/min of lat/lng:

    LatLngBounds computeBounds(List<LatLng> list) {
      assert(list.isNotEmpty);
      var firstLatLng = list.first;
      var s = firstLatLng.latitude,
          n = firstLatLng.latitude,
          w = firstLatLng.longitude,
          e = firstLatLng.longitude;
      for (var i = 1; i < list.length; i++) {
        var latlng = list[i];
        s = min(s, latlng.latitude);
        n = max(n, latlng.latitude);
        w = min(w, latlng.longitude);
        e = max(e, latlng.longitude);
      }
      return LatLngBounds(southwest: LatLng(s, w), northeast: LatLng(n, e));
    }