Google Maps JavaScript API v3: method Polygon.getBounds


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

}

Here, we present a simplified method:

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
}

}

Image copyright: Google maps

Leave a Reply