我在地图上设置了多个标记,我可以静态地设置缩放级别和中心,但我想要的是,覆盖所有标记,尽可能放大,让所有市场可见

可用的方法如下

setZoom(缩放:数字)

and

setCenter (latlng: latlng)

setCenter都不支持多位置或位置数组输入,setZoom也没有这种类型的功能


您需要使用fitBounds()方法。

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

文档来自developers.google.com/maps/documentation/javascript:

fitBounds(范围、填充) 参数: “界限”(“LatLngBounds”):[1]| [' LatLngBoundsLiteral '] [1] ' padding '(可选):number|[' padding '][1] 返回值:无 设置视口以包含给定的边界。 注意:当映射设置为display: none时,fitBounds函数将映射的大小读取为0x0,因此不执行任何操作。要在地图隐藏时更改视口,请将地图设置为visibility: hidden,从而确保地图div具有实际大小。

用一些有用的技巧来扩展给定的答案:

var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
   bounds.extend(markers[i].getPosition());
}

//center the map to a specific spot (city)
map.setCenter(center); 

//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());

map.fitBounds(bounds);

//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1); 

// set a minimum zoom 
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
  map.setZoom(15);
}

//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
    map.setMaxZoom(15);
    map.fitBounds(bounds);
    map.setMaxZoom(Null)
}

更新: 对该主题的进一步研究表明,fitBounds()是异步的 在调用Fit Bounds之前,最好使用定义的监听器进行缩放操作。 谢谢@Tim, @xr280xr,关于这个主题的更多例子:SO:setzoom-after-fitbounds

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  this.setZoom(map.getZoom()-1);

  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});
map.fitBounds(bounds);

有这个MarkerClusterer客户端实用程序可用于谷歌地图,如谷歌地图开发人员文章中所述,这里简要介绍了它的用法:

有很多方法可以达到你的要求:

基于网格的聚类 距离聚类 视口标记管理 融合表 标记Clusterer运算 MarkerManager

你可以在上面提供的链接上阅读它们。

标记Clusterer使用基于网格的聚类来聚集所有希望网格的标记。基于网格的聚类工作原理是将地图划分为一定大小的正方形(每次缩放时大小都会变化),然后将标记分组到每个网格正方形中。

在聚类之前

聚类后

我希望这是你一直在寻找的&这将解决你的问题:)

数组的大小必须大于零。 Οtherwise你会有意想不到的结果。

function zoomeExtends(){
  var bounds = new google.maps.LatLngBounds();
  if (markers.length>0) { 
      for (var i = 0; i < markers.length; i++) {
         bounds.extend(markers[i].getPosition());
        }    
        myMap.fitBounds(bounds);
    }
}