20

I have a lot of polygonal features loaded with loadGeoJson and I'd like to get the latLngBounds of each. Do I need to write a function that iterates through every lat long pair in the polygon and does an extend() on a LatLngBounds for each, or is there a better way? (If not, I can probably figure out how to iterate through the polygon vertices but pointers to an example of that would be welcome)

Lucas Walter
  • 942
  • 3
  • 10
  • 23

3 Answers3

31

The Polygon-features doesn't have a property that exposes the bounds, you have to calculate it on your own.

Example:

   //loadGeoJson  runs asnchronously, listen to the addfeature-event
   google.maps.event.addListener(map.data,'addfeature',function(e){

      //check for a polygon
      if(e.feature.getGeometry().getType()==='Polygon'){

          //initialize the bounds
          var bounds=new google.maps.LatLngBounds();

          //iterate over the paths
          e.feature.getGeometry().getArray().forEach(function(path){

             //iterate over the points in the path
             path.getArray().forEach(function(latLng){

               //extend the bounds
               bounds.extend(latLng);
             });

          });

          //now use the bounds
          e.feature.setProperty('bounds',bounds);

        }
  });

Demo: http://jsfiddle.net/doktormolle/qtDR6/

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
15

In Google Maps JavaScript API v2, Polygon had a getBounds() method, but that doesn’t exist for v3 Polygon. Here’s the solution:

if (!google.maps.Polygon.prototype.getBounds) {
    google.maps.Polygon.prototype.getBounds = function () {
        var bounds = new google.maps.LatLngBounds();
        this.getPath().forEach(function (element, index) { bounds.extend(element); });
        return bounds;
    }
}
Kristopher
  • 819
  • 14
  • 31
1

Here's another solution for v3 Polygon :

var bounds = new google.maps.LatLngBounds();

map.data.forEach(function(feature){
  if(feature.getGeometry().getType() === 'Polygon'){
    feature.getGeometry().forEachLatLng(function(latlng){
      bounds.extend(latlng);
    });
  }
});
Fab
  • 1,080
  • 12
  • 19