Recently I faced the issue to zoom to accommodate all markers in google map.In the google map, I included some polygons and lot of markers with landmarks and different locations.
Google Maps API v3 allows us to automatically center and zoom the map around a set of coordinates. It provides a LatLngBounds object to which we can add multiple LatLng objects. We can pass this to Map.fitBounds() function as below:
1 2 3 4 5 6 7 8 9 | var latlng = [ new google.maps.LatLng(3.23, 6.96), new google.maps.LatLng(9.89, 16.01) ]; var latlngbounds = new google.maps.LatLngBounds(); for (var i = 0; i < latlng.length; i++) { latlngbounds.extend(latlng[i]); } map.fitBounds(latlngbounds); |
The trick is to add all points that into a google.maps.LatLngBounds object using the extend() method.
Like this we can extend as many as latlng as we want and after that we need to use these latlngbounds with the Map.fitBounds() function.
But with polygon,It’s little bit tricky not so hard. A polygon itself is just an array of coordinates that define a shape. So we need to extend latlngbound with every coordinate of polygon and then need to pass in Map.fitBounds() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var bounds = new google.maps.LatLngBounds(); var i; // The Bermuda Triangle var polygonCoords = [ new google.maps.LatLng(26.874252, -70.190262), new google.maps.LatLng(20.466465, -76.116292), new google.maps.LatLng(33.321384, -74.755370), new google.maps.LatLng(23.774252, -70.191262) ]; for (i = 0; i < polygonCoords.length; i++) { bounds.extend(polygonCoords[i]); } Map.fitBounds(bounds); |
Like this, we can zoom to accommodate all markers in google map. If yo have any query regarding this post or google map, you are welcome to post on our site.
GOOD!
看看!