Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

javascript - Google MAP API v3: Center & Zoom on displayed markers

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 this? 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 doesn't seem to work, and I get no error in the console. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

LatLngList: an array of instances of latLng, for example:

// "map" is an instance of GMap3

var LatLngList = [
                     new google.maps.LatLng (52.537,-2.061), 
                     new google.maps.LatLng (52.564,-2.017)
                 ],
    latlngbounds = new google.maps.LatLngBounds();

LatLngList.forEach(function(latLng){
   latlngbounds.extend(latLng);
});

// or with ES6:
// for( var latLng of LatLngList)
//    latlngbounds.extend(latLng);

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...