加入另一个解决方案 - 我发现“监听 bounds_changed 事件然后设置新的缩放”方法对我来说并不可靠。我认为我有时会fitBounds
在地图完全初始化之前调用,并且在fitBounds
更改边界和缩放级别之前,初始化会导致会用完侦听器的 bounds_changed 事件。我最终得到了这段代码,到目前为止它似乎有效:
// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.
var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
console.log(map.getZoom());
if (map.getZoom() > 15) {
map.setZoom(15);
}
if (!removeListener) {
removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
console.log('remove');
google.maps.event.removeListener(listener);
});
}
});