google-mapsgoogle-maps-api-3polygons

Fit Bounds for Multiple Polygons google Maps


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)
 }

Solution

  • 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)
     }