I’d like a problem that for once hasn’t already been solved by someone else.
I had a set of markers which needed to be all on screen, and for some reason there’s no .zoomToShow method. Fortunately it’s pretty simple to create yourself.
// Make an array of the LatLng's of the markers you want to show
var LatLngList = array (new google.maps.LatLng (52.537,-2.061), new google.maps.LatLng (52.564,-2.017));
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds ();
// Go through each...
for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
// And increase the bounds to take this point
bounds.extend (LatLngList[i]);
}
// Fit these bounds to the map
map.fitBounds (bounds);
And that’s pretty much it. Then, of course, I found that someone had already done this before, but for version two of the API.
Just wanted to send you a quick thanks for this little snippet. My version which was much longer stopped working in version 3 — this one is much simpler.
Do you know of a way to zoom to fit all markers while keeping the center of the map at a certain lat/long or marker?
Thanks for the code snippet, it worked beautifully with the new marker cluster (V3)
LatLngList.count() was throwing an error at me, I changed it to LatLngList.length and everything appears to be working.
Thanks for explaining this so clearly – it was exactly what I was looking for!
.count is not a valid javascript property. Please update your code to use the .length property.
As matt said, change LatLngList.count() to be LatLngList.length
Note: it’s a property, not a method, so leave out the parens ().
Ah, you’re right. I’ve changed that.
I probably used .count() since I come from jQuery development.
it is really great snippet, I searched but I couldn’t find a solution that works with APIv3, they were all APIv2.
Thanks a lot ;)
Thanks! This works well. V3 has changed for the better.
Pingback: Dibujando rutas en Google Maps | Scipion Strikes Back
Thanks, this trick worked in V3!
This is exactly what I was looking for… Thanks!
If you have a list of markers and want to zoom and center them on screen, you can also keep extending bounds object while adding markers to list. So when you want to center map, you will not need to loop all markers again. Good luck
var fMapBounds = new google.maps.LatLngBounds();
function PlotMarker(Position) { //add a marker to map
var latlng = new google.maps.LatLng(Position.Longitude);
var googMarker = new google.maps.Marker({
position: latlng,
map: map,
});
fMapBounds.extend();
return googMarker;
}
function CenterMap() { //just fit it
if (fMapBounds!= undefined) {
map.fitBounds(fMapBounds);
}
}
thanks, worked perfect!
A big help. Thank you.
This works !!
Thanks
Nice one.
Happy coding.
Great! Very helpful.
I will use it in my code. Thanks a lot.
Great tip! Saved me a headache, thankyou :)