Google Maps v3 API doesn't natively support a getBounds()
method for the google.maps.Polygon class. This seems strange given the fact that the google.maps.Map class has a fitBounds()
method, which is exactly what you're looking for.. If you use the Google Maps API with any kind of frequency then this should be in your bag of tricks ::
getBounds()
method for the google.maps.Polygon class
google.maps.Polygon.prototype.getBounds = function() {
var bounds = new google.maps.LatLngBounds();
var paths = this.getPaths();
var path;
for (var i = 0; i < paths.getLength(); i++) {
path = paths.getAt(i);
for (var ii = 0; ii < path.getLength(); ii++) {
bounds.extend(path.getAt(ii));
}
}
return bounds;
}
Having this method on hand makes it very simple to center and fit a polygon on the map.
Note : If you're not familiar with getAt()
and getLength()
that's fine, they're methods unique to the google.maps.MVCArray class. When you call the getPaths()
method of a polygon it returns your array of LatLng's as a mutable MVCArray of LatLng's.. you can ready about MVCArrays here - Google Maps v3 API MVCArray class.
Moving on. Here's the framework, you'll have to implement the prototyped method above somewhere before this next bit of code.
var map = new google.maps.Map(container, opts); // I'll spare the details on this
var coords = [
new google.maps.LatLng(25.774252, -80.190262)
,new google.maps.LatLng(18.466465, -66.118292)
,new google.maps.LatLng(32.321384, -64.75737)
,new google.maps.LatLng(25.774252, -80.190262)
];
var myPolygon = new google.maps.Polygon({
paths: coords
,strokeColor: "#A80000"
,strokeOpacity: 0.8
,strokeWeight: 1
,fillColor: "#0b2a32"
,fillOpacity: 0.12
});
With the stage set, all you'd have to do to center and zoom on this (or any) polygon is ::
map.fitBounds(myPolygon.getBounds());