Nick Developer Nick Developer - 3 months ago 14
Javascript Question

how to center markers using setbounds

I have a map which contains multiple markers with infowindows. I need a way for the the map to be centered using setbounds around all of the markers - so that they are all visible.

Here is my code:
https://jsfiddle.net/nickbuus/kzsetxke/

I have seen examples of how to use setbounds for this - but when I am using a loop I am unsure where to set the bounds for the map. here is my loop:

for (var i = 0; i < locations.length; i++) {
gmarkers[locations[i][0]] =
createMarker(new google.maps.LatLng(locations[i][3], locations[i][4]), locations[i][1] + "<br>" + locations[i][2]);

Answer

You can create new google.maps.LatLngBounds and while creating the markers, extend this bounds by the marker position using getPosition() method, like this:

// Create bounds    
var bounds = new google.maps.LatLngBounds();

// Create marker for each location
for (var i = 0; i < locations.length; i++) {
    var m = createMarker(new google.maps.LatLng(locations[i][3], locations[i][4]), locations[i][1] + "<br>" + locations[i][2]);
    gmarkers[locations[i][0]] = m;

    // Extend bound by the marker position
    bounds.extend(m.getPosition());
}

// Fit map
map.fitBounds(bounds);

Here is your original fiddle with the mentioned change https://jsfiddle.net/tez50m5t/