How can I fitBounds for all shapes on the map?

UserMat picture UserMat · Nov 10, 2013 · Viewed 7.8k times · Source

There are a lot of shapes on the map and they are all saved inside this array array_shapes_object[]. How can I show all of them on the map by fitBounds method?

I can use something like:

map.fitBounds(circle.getBounds());

or

map.fitBounds(rectangle.getBounds());

or

var points = new google.maps.LatLng(arrayLatitude[aa], arrayLongitude[aa]);
bounds.extend(points);
map.fitBounds(bounds);

but they all work for just a shape and not more than one. Seems that there is just three type of shapes. (Circle, rectangle, polygon).

I want to fitBounds all shapes on the map when I click on a button that is run a function.

Answer

geocodezip picture geocodezip · Nov 10, 2013

You need to create a google.maps.LatLngBounds object that is the union of the bounds of all the objects that you want displayed.

union(other:LatLngBounds) | LatLngBounds | Extends this bounds to contain the union of this and the given bounds.

pseudo code (you need to add the bounds of all the shapes you want displayed on the map to it):

var bounds = circle.getBounds();
bounds.union(rectangle.getBounds();
for (var aa=0; aa < arrayLatitude.length; aa++) {
  var points = new google.maps.LatLng(arrayLatitude[aa], arrayLongitude[aa]);
  bounds.extend(points);
}
map.fitBounds(bounds);