Search code examples
javascriptgoogle-mapszoomingpolygonbounds

Set google map zoom dynamically


It's possible to define a level of zoom depending of the height of polygon shapes (administrative boundaries)? This polygon going to be completely displayed into the map's div.


Solution

  • There is a map.fitBounds(my_bounds) function, which sets the viewport to contain the given bounds. It would set the map to the highest zoom level possible, in which you can see the whole bounds.

    For that you need to determine the bounds of your polygon. If you use google.maps.Polygon to display your polygons, check out this solution.

    In this case you would have:

    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;
    }
    
    ...
    map.fitBounds(my_polygon.getBounds());
    

    If you use Data layer to display polygons, check out this SO answer. It provides example on how to calculate bounds of Data.Feature if it's a polygon.

    If you have some other means of determining the bounds of polygon, then just use this:

    map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(SouthWestCornerLat, SouthWestCornerLng), new google.maps.LatLng(NorthEastCornerLat, NorthEastCornerLng));