Matt Polers
Matt Polers

Reputation: 43

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

Upvotes: 3

Views: 4130

Answers (3)

Deepesh Kumar
Deepesh Kumar

Reputation: 114

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

Upvotes: 0

DanLatimer
DanLatimer

Reputation: 117

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

Upvotes: 1

geocodezip
geocodezip

Reputation: 161354

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

Upvotes: 11

Related Questions