Google Maps API v3 - fitBounds only centers one marker

I have several markers that I draw and want to center the map. Yes, I read all the other answers, but it doesn't seem to work for me: Google Map API v3 - set boundaries and center

JS:

geocoder.geocode( {'address': loc}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var markerBounds = new google.maps.LatLngBounds(); var coordinate = results[0].geometry.location; var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44)); //create the marker var marker = new google.maps.Marker({ map: map, position: coordinate, visible: true, id: type, shadow: shadow, icon: icon }); markerBounds.extend(coordinate); map.fitBounds(markerBounds); } } 
+1
source share
2 answers

Your code always calls fitBounds with LatLngBounds with only one point, the last marker ... If you call this function several times, each time you call it, Bounds of the last marker will be used. You can define the markerBounds variable outside the geocoder.geocode function, so it will keep its value.

 var markerBounds = new google.maps.LatLngBounds(); geocoder.geocode( {'address': loc}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var coordinate = results[0].geometry.location; var icon = new google.maps.MarkerImage("images/icon-"+type+".png", new google.maps.Size(37, 44)); //create the marker var marker = new google.maps.Marker({ map: map, position: coordinate, visible: true, id: type, shadow: shadow, icon: icon }); markerBounds.extend(coordinate); map.fitBounds(markerBounds); } } 

The Bounds token is now initialized once and expanded with each new token.

+1
source

Actually, you can find out which coordinates are stored in your borders for registration:

 console.log("mapFitBounds:"+bounds); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

And then just check your log in the Chrome console. You will recognize the problem because I found there two duplicate coordinates within my borders, and then targeted the problem.

0
source

Source: https://habr.com/ru/post/1205029/


All Articles