Google MAP API v3:显示标记的中心和缩放

meo*_*meo 55 javascript jquery google-maps-api-3

我使用以下代码在我的地图上设置标记:

  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
   });
  }) 
Run Code Online (Sandbox Code Playgroud)

标记显示在我的地图上.现在我想在这些标记上居中并缩放地图.我怎么能做到这一点?我试过了:

map.fitBounds(getBoundsForLatLngs(latLngs));
Run Code Online (Sandbox Code Playgroud)

latLngs的console.log给出:

 [(46.793182, 7.146903) { b=46.793182,  more...}, (46.8077779, 7.1709386) { b=46.8077779,  more...}]
Run Code Online (Sandbox Code Playgroud)

但它似乎不起作用,我在控制台中没有错误.我究竟做错了什么?

vsy*_*ync 127

我也发现这个修正缩放以适应所有标记

LatLngList:latLng实例的数组,例如:

// "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); 
Run Code Online (Sandbox Code Playgroud)

  • 试试这个!http://blog.shamess.info/2009/09/29/zoom-to-fit-all-markers-on-google-maps-api-v3/ (9认同)
  • 什么样的数组是`latlng`?它是如何得到'each`功能的?JQuery的? (2认同)

Paw*_*lik 18

如果你喜欢更多的功能风格:

// map - instance of google Map v3
// markers - array of Markers
var bounds = markers.reduce(function(bounds, marker) {
    return bounds.extend(marker.getPosition());
}, new google.maps.LatLngBounds());

map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
Run Code Online (Sandbox Code Playgroud)