Fit Bounds for Multiple Polygons google Maps

3.9k views Asked by At

I'm trying to extend the map boundaries for several polygons, but it seems it is only extending the boundaries for the last polygon in the loop. Any suggestions for where I am going wrong?

 function FitBounds(){
    for (var i=0; i < shapes2.length; i++){
        var paths = shapes2[i].getPaths();
        var bounds= new google.maps.LatLngBounds();
        paths.forEach(function(path){
           var ar = path.getArray();
           for(var i=0, l = ar.length; i <l; i++){
              bounds.extend(ar[i]);
           }
        })
    }
    map.fitBounds(bounds)
 }
3

There are 3 answers

0
geocodezip On BEST ANSWER

Create the bounds outside of the loop.

function FitBounds(){
    var bounds= new google.maps.LatLngBounds();
    for (var i=0; i < shapes2.length; i++){
        var paths = shapes2[i].getPaths();
        paths.forEach(function(path){
           var ar = path.getArray();
           for(var i=0, l = ar.length; i <l; i++){
              bounds.extend(ar[i]);
           }
        })
    }
    map.fitBounds(bounds)
 }
0
Deepesh Kumar On

You can make use of the Polygon method getPaths() to achieve the same in a simplified form.

    const bounds = new google.maps.LatLngBounds();
    polygonList.forEach((polygon) => {
      polygon.getPaths().forEach((path) => {
        path.forEach((point) => {
          bounds.extend(point);
        });
      });
    });
    map.fitBounds(bounds);
0
DanLatimer On

FYI for other people getting here there are helper methods by the google maps library making it easier to get the bounds of a collection of shapes:

function FitBounds(){
    var bounds = shapes2.reduce((boundsAccumulator, shape) => 
      boundsAccumulator.union(shape.getBounds()), new google.maps.LatLngBounds())
    
    map.fitBounds(bounds)
 }

or if you're not a fan of reduce

function FitBounds(){
    var bounds = new google.maps.LatLngBounds()
    
    shapes2.forEach(shape) => bounds.union(shape.getBounds()))
    
    map.fitBounds(bounds)
 }