How do I get Google Maps to show a whole polygon?

Viewed 26894

I have a set of GPolygon objects which are attached to objects in my domain model and are added to a map on my page. The domain objects are being shown in a list on the same page and when the user clicks on one of them I want to show the associated polygon.

I want the whole polygon to be showing and ideally I want the map to be centred on the polygon centre.

I was hoping that there would be a maps API call along the lines of...

myMap.makeSureYouCanSeeAllThisPolygon(aPolygon);

but I haven't been able to find one.

If I have to do this manually, then I can obviously figure out the centering easily, but how do I figure out the zoom?

6 Answers

You can get the centre point of a polygon by using aPolygon.getBounds().getCenter(); and then using the GLatLng returned with the myMap.setCenter() method.

To get the zoom level, you can use myMap.getBoundsZoomLevel(aPolygon.getBounds()); then use this with myMap.setZoom() method.

A shorter version from the getBounds function written in ES6

google.maps.Polygon.prototype.getBounds = function () {
    let bounds = new google.maps.LatLngBounds();
    this.getPaths().forEach(p => {
        p.forEach(element => bounds.extend(element));
    });
    return bounds;
}

To center the map

map.fitBounds(poly.getBounds());
Related