views:

453

answers:

2

I use the following code to set markers on my map:

  var latLngs = []
  $.each(locations.markers, function(i, m){
   var myLatLng = new google.maps.LatLng(m.latitude, m.longitude);
   latLngs[i] = myLatLng                                          
   var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    shadow: shadow,
    icon: image,
    shape: shape,
    title: m.city,
    zIndex: i
   });
  }) 

the markers show up on my map. now i would like to center & zoom the map on these markers. How can i accomplish that? I have tried:

map.fitBounds(getBoundsForLatLngs(latLngs));

the console.log of latLngs gives out:

 [(46.793182, 7.146903) { b=46.793182,  more...}, (46.8077779, 7.1709386) { b=46.8077779,  more...}]

But it seams not work and i get no error in the console. What i am doing wrong?

+1  A: 

did you try adding:

zoom: 10,
center: myLatlng,

to your marker object ?

I've also find this fix that zooms to fit all markers

Update: another fix I've found online:

// map: an instance of GMap3
// latlng: an array of instances of GLatLng
var latlngbounds = new google.maps.LatLngBounds();
latlng.each(function(n){
   latlngbounds.extend(n);
});
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 
vsync
this centers the map on one point i want to center the map on all shown points
meo
try this! http://blog.shamess.info/2009/09/29/zoom-to-fit-all-markers-on-google-maps-api-v3/
vsync
it worked i had to use LatLngBounds just like your example. I passed my array directly to `fitBounds()`. Thx for you fast support
meo
I'm glad it worked out for you :)
vsync
A: 

Can you trace the latLngs in console? I think your array mignt not be a continuous one (e.g. [0, 1, 2, 3, 5]) or some of the latlngs in that array might have invalid lat/lng values.

Salman A
this is the result of the console: ` [(46.793182, 7.146903) { b=46.793182, more...}, (46.8077779, 7.1709386) { b=46.8077779, more...}]`
meo
How could i be so silly to forget that I wrote an article about centering + zooming to fit all markers.
Salman A