Question

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.

Was it helpful?

Solution

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

OTHER TIPS

<script>
//This function get the canter of map in a way that all shapes are shown on the map.
function get_center()
{
    var bounds = new google.maps.LatLngBounds();
    var points = new Array();

    for(var counter = 0; counter < array_shapes_object.length; counter++)
    {
        switch(array_shapes_object[counter].type)
        {           
            case "rectangle":
            case "circle":                                            
              points = new google.maps.LatLng(array_shapes_object[counter].getBounds().getNorthEast().lat(), array_shapes_object[counter].getBounds().getNorthEast().lng());
              bounds.extend(points);

              points = new google.maps.LatLng(array_shapes_object[counter].getBounds().getSouthWest().lat(), array_shapes_object[counter].getBounds().getSouthWest().lng());
              bounds.extend(points);
            break;

            case "polygon":
              var paths;
              paths = array_shapes_object[counter].getPath();

              for(var i = 0; i < paths.length; i++)
              {
                  points = new google.maps.LatLng(paths.getAt(i).lat(), paths.getAt(i).lng());
                  bounds.extend(points);                  
              }

            break;
        }

        map.fitBounds(bounds);
    }               
}
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top