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)
Asked
Active
Viewed 2.7k times
3 Answers
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);
}
});

Dr.Molle
- 116,463
- 16
- 195
- 201
-
This does not apply to MultiPolygon? – manu29.d Apr 23 '15 at 07:31
-
where add more coordinates ? Or modify the coordinates(Lat,Lng) ? – Kevin Faccin Aug 17 '16 at 11:24
-
1@manu29.d at v3, the geometry type check is not necessary. Just calling e.feature.getGeometry().forEachLatLng(function(path) { bounds.extend(path); } ) worked for me on a multipolygon. – jon_two Dec 08 '16 at 13:12
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
-
How do you implement this? After I use this function can I then call getBounds()? I have no idea what the code is trying to do here or how it helps me. – Mark Tomlin Nov 26 '19 at 19:00
-