Google Maps Api V3 - Fitbounds Centers Only One Marker
I have a few markers that I retrieve and want to center the map to. Yes, I have read all the other answers, but it doesn't seem to work for me: Google Map API v3 — set bounds an
Solution 1:
Your code is always calling fitBounds with a LatLngBounds of only one point, the last marker... If you are calling that function several times, each time you call it, will fitBounds of the last marker. You could define the markerBounds variable outside the geocoder.geocode function, so it will retain it's 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 markervar marker = new google.maps.Marker({
map: map,
position: coordinate,
visible: true,
id: type,
shadow: shadow,
icon: icon
});
markerBounds.extend(coordinate);
map.fitBounds(markerBounds);
}
}
Now, markerBounds is initialized once, and extended with each new marker.
Solution 2:
Actually, you can ouput the what coords are store in your bounds to log by:
console.log("mapFitBounds:"+bounds);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
And then just check your log in console of Chrome. You will know the problem, cuz I found it there's two duplicate coords in my bounds and then target the problem.
Post a Comment for "Google Maps Api V3 - Fitbounds Centers Only One Marker"