I have a map that displays pins and infowindow for each pin. The zoom level is 9 and at that zoom level, some pins are not displayed. I need to control the zoom level dynamically as to show all the pins in the map canvas at a time.
Asked
Active
Viewed 1,821 times
2 Answers
3
Have a LatLngBounds object. As you're creating each marker, you want to expand the bounds to include each marker's location. Then at the end you call the fitBounds method to resize the map to fit all the markers.
function initialize() {
var arrPoints = [
{
lat: 51.498725,
lng: -0.17312,
description: "One",
price: 1.11
},
{
lat: 51.4754091676,
lng: -0.186810493469,
description: "Two",
price: 2.22
},
{
lat: 51.4996066187,
lng: -0.113682746887,
description: "Three",
price: 3.33
},
{
lat: 51.51531272,
lng: -0.176296234131,
description: "Four",
price: 4.44
}
];
var centerLatLng = new google.maps.LatLng(51.532315,-0.1544);
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: centerLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// create the Bounds object
var bounds = new google.maps.LatLngBounds();
var homeMarker = new google.maps.Marker({
position: centerLatLng,
map: map,
icon: "http://maps.google.com/mapfiles/ms/micons/green-dot.png"
});
for (var i = 0; i < arrPoints.length; i++) {
position = new google.maps.LatLng(arrPoints[i].lat, arrPoints[i].lng);
var marker = new google.maps.Marker({
position: position,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
// extend the bounds to include this marker's position
bounds.extend(position);
}
// make sure we include the original center point
bounds.extend(centerLatLng);
// resize the map
map.fitBounds(bounds);
}

duncan
- 31,401
- 13
- 78
- 99
0
You can use the map.fitBounds
function to zoom to a specific bounding area. To get this area you just have to loop through all the pins and take the minimum / maximum of the coordinates.
There is already a final solution in the shamess blog.

Alex
- 32,506
- 16
- 106
- 171
-
Alex, the link does not work now. – Muhammad Usama Mashkoor Apr 18 '22 at 12:47
-
@usama sorry, maybe we should linke archive.org waybackmachine? – Alex Apr 19 '22 at 13:33