我在我的地图上设置了多个标记,我可以静态设置缩放级别和中心,但我想要的是,覆盖所有标记并尽可能缩放,让所有市场都可见
可用的方法如下
和
setCenter
不支持多个位置或位置数组输入,setZoom
也不具有此类功能
https://i.stack.imgur.com/Bkqjl.jpg
您需要使用 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(bounds[, padding]) 参数:`bounds`:[`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1] `padding`(可选):number|[`Padding`][1] 返回值: None 将视口设置为包含给定的边界。注意:当地图设置为 display: none 时,fitBounds 函数将地图的大小读取为 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)
}
更新:
对该主题的进一步研究表明 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);
yourMap
、map
和 this
。也许让它更加一致是个好主意。
数组的大小必须大于零。 Ο否则你会得到意想不到的结果。
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);
}
}
在 Google Map developer Articles 上指定了此 MarkerClusterer
客户端实用程序可用于 google 地图,这里简要介绍了它的用法:
有很多方法可以满足您的要求:
基于网格的聚类
基于距离的聚类
视口标记管理
融合表
标记聚类器
标记管理器
您可以在上面提供的链接上阅读它们。
Marker Clusterer
使用 基于网格的聚类 对希望网格的所有标记进行聚类。基于网格的聚类的工作原理是将地图划分为一定大小的正方形(每次缩放时大小都会发生变化),然后将标记分组到每个网格正方形中。
https://i.stack.imgur.com/Fffx0.png
https://i.stack.imgur.com/3V6oc.png
我希望这是您正在寻找的东西,这将解决您的问题:)
不定期副业成功案例分享
getPosition
方法从何而来?LatLngLiteral
而不是 Marker 实例。例如,bounds.extend({lat: 123, lng: 456})
。getPosition
总是返回未定义的。我通过每次创建标记时调用bounds.extend
来解决此问题。fitBounds(bounds, int)
定义填充,这将允许您在标记和地图边缘之间留出一点空间(或者如果需要,可以减少空间)。 See Documentation