在使用 fitBounds() 和 Google Maps API V3 后使用 setZoom() [英] Using setZoom() after using fitBounds() with Google Maps API V3
问题描述
我正在使用 fitBounds() 在我的地图上设置缩放级别,也包括当前显示的所有标记.但是,当我只有一个标记可见时,缩放级别为 100%(...我认为缩放级别为 20...).但是,我不希望它放大那么远,这样用户就可以调整标记的位置而不必缩小.
I'm using fitBounds() to set the zoom level on my map too include all the markers currently displayed. However, when I have only one marker visible, the zoom level is 100% (... which zoom level 20 I think...). However, I don't want it to be that far zoomed in so the user can adjust the position of the marker without having to zoom out.
我有以下代码:
var marker = this.map.createMarker(view.latlng, this.markerNumber);
this.map.bounds.extend(view.latlng);
this.map.map.setCenter(this.map.bounds.getCenter());
this.map.map.fitBounds(this.map.bounds);
if (this.markerNumber === 1) {
this.map.map.setZoom(16);
}
this.markerNumber++;
this.map.bounds 之前定义为:
where this.map.bounds was previously defined as:
this.map.bounds = new google.maps.LatLngBounds();
但是,我遇到的问题是 this.map.map.setZoom(16);
如果我使用 this.map.map.fitBounds(this.map.bounds);
,但是,我知道这行代码是正确的,因为当我注释掉 fitBound() 行时,setZoom() 会神奇地开始运行.
However, the problem I am having is that the line this.map.map.setZoom(16);
doesn't work if I use this.map.map.fitBounds(this.map.bounds);
, however, I know that line of code is correct because when I comment out the fitBound() line, the setZoom() magically starts functioning.
任何想法我如何解决这个问题?如果无法正常工作,我正在考虑将 maxZoom 级别设置为替代方案.
Any ideas how I resolve this? I'm thinking of setting a maxZoom level as an alternative if I can't get this working.
推荐答案
好的,我想通了.显然,fitbounds() 是异步发生的,因此您必须在设置缩放工作之前等待 bounds_changed
事件.
Alright, I've figured it out. Apparently, the fitbounds() happens asynchronously, so you have to wait for a bounds_changed
event before setting zoom works.
map = this.map.map;
map.fitBounds(this.map.bounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(16);
}
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);
更新:使用 addListenerOnce
查看@Nequin 的回答,以获得不需要超时的更好解决方案.
Update: See @Nequin's answer using addListenerOnce
for a better solution that doesn't require a timeout.
这篇关于在使用 fitBounds() 和 Google Maps API V3 后使用 setZoom()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!