How to make map cover all markers in javascript?

435 views Asked by At

I have an issue with Google Map in javascript, I can not make all markers fit bounds. Only the first marker is visible. This is the error thrown in console:

uncaught exception: InvalidValueError: not a LatLngBounds or LatLngBoundsLiteral: not an Object

And this is the code I am using:

var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: parseFloat(lat), lng:parseFloat(lng)},
    zoom: 11
});

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

for(var i = 0; i < coordinates.length; i++){

    var coords = {lat: parseFloat(lat), lng:parseFloat(lng)}

    var marker = new google.maps.Marker({position: coords, map: map});
    var infowindow = new google.maps.InfoWindow();

    infowindow.setContent(lat);
    infowindow.open(map, marker);

    bounds.extend(marker.position);

}

map.setCenter(bounds.getCenter());
map.fitBounds(bounds);  

I have 4 markers on the map, but map is zoomed and centered to the last one added, as seen in the image below:

enter image description here

If I zoom out the map I can see all other markers, but fitbounds is not working to make all markers fit the bounds.

1

There are 1 answers

0
Pagemag On

Are you getting the coordinates of your markers from an Array? You need to check the value of coordinates that you are passing if they are proper latLng objects. As you have not yet provided a sample code, I created a working fiddle where I used the fitbounds on the map.

sample code snippet:

 var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 20,
    center: {lat: -33.9, lng: 151.2}
  });

var markerArray = [
  ['Bondi Beach', -33.890542, 151.274856],
  ['Coogee Beach', -33.923036, 151.259052],
  ['Cronulla Beach', -34.028249, 151.157507],
  ['Manly Beach', -33.80010128657071, 151.28747820854187],
  ['Maroubra Beach', -33.950198, 151.259302]
];

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

  for (var i = 0; i < markerArray.length; i++) {
    var marker = markerArray[i];
    var markerCoord = new google.maps.LatLng(marker[1],marker[2]);

    var marker = new google.maps.Marker({
      position: markerCoord,
      map: map
    });

     bounds.extend(markerCoord);
  }
  map.fitBounds(bounds);
}

Hope this helps!