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