我正在我的地图上设置多个标记,我可以静态设置缩放级别和中心,但我想要的是覆盖所有标记并尽可能地缩放所有市场可见
可用的方法如下
setZoom(缩放:数字)
然后呢?
< code > setCenter(lat LNG:lat LNG)
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中的文档:
参数:
`bounds`: [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional): number|[`Padding`][1]
返回值:无
设置视口以包含给定的边界。
注意:当地图设置为显示:无
时,fitBones
函数将地图的大小读取为0x0
,因此不做任何事情。要在地图隐藏时更改视口,请将地图设置为可见性:隐藏
,从而确保地图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)
}
更新:
本主题的进一步研究表明,fitBones()是一种异步的,最好在调用Fit Bones之前使用定义的侦听器进行Zoom操作。
感谢@Tim,@xr280xr,有关该主题的更多示例:SO:setzoom-post-fitbones
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
数组的大小必须大于零。否则你会有意想不到的结果。
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);
}
}