繁体   English   中英

使用fitBounds()和Google Maps API V3后使用setZoom()

[英]Using setZoom() after using fitBounds() with Google Maps API V3

我正在使用fitBounds()在我的地图上设置缩放级别,也包括当前显示的所有标记。 但是,当我只有一个标记可见时,缩放级别为100%(...我认为缩放级别为20 ......)。 但是,我不希望它被放大,因此用户可以调整标记的位置而不必缩小。

我有以下代码:

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先前定义为:

this.map.bounds = new google.maps.LatLngBounds();

但是,我遇到的问题是该行this.map.map.setZoom(16); 如果我使用this.map.map.fitBounds(this.map.bounds); 但是,我知道这行代码是正确的,因为当我注释掉fitBound()行时,setZoom()会神奇地开始运行。

我有什么想法解决这个问题? 我正在考虑设置一个maxZoom级别作为替代,如果我不能让它工作。

好吧,我已经明白了。 显然,fitbounds()是异步发生的,因此在设置缩放工作之前必须等待bounds_changed事件。

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的答案,以获得不需要超时的更好解决方案。

google.maps.event.addListenerOnce(yourMap, 'bounds_changed', function(event) {
  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});

此解决方案效果更好...而不是等待超时删除侦听器。 在使用fitBounds之前直接调用它(我相信调用后也会起作用)。

我发现额外的变焦有点刺耳。 如果在调用fitBounds之前设置maxZoom选项(然后在回调中取消设置),则可以避免它:

map.setOptions({
    maxZoom: 10
});

map.setCenter(new google.maps.LatLng(-89, -179)); // make sure it changes so the idle listener gets called back

map.fitBounds(bounds);

var listener = google.maps.event.addListenerOnce(map, "idle", function()
{
    map.setOptions({
        maxZoom: 999
    });
});

我有简单而肮脏的解决方案。
使用如果否则......

var marker = this.map.createMarker(view.latlng, this.markerNumber);
this.map.bounds.extend(view.latlng);
this.map.map.setCenter(this.map.bounds.getCenter()); 
if (this.markerNumber === 1) {
  this.map.map.setZoom(16);
} else {
   this.map.map.fitBounds(this.map.bounds);
}       
this.markerNumber++;

我刚刚在函数addBounds(position)添加了一行并修复了它,如下所示:

    addBounds: function(position) {
        this.get('bounds', new google.maps.LatLngBounds()).extend(this._latLng(position));
        this.get('map').fitBounds(this.get('bounds'));
        this.get('map').setZoom(16);//line added
        return this;
    },

我认为正确的方法是你需要在map.fitBounds(bounds)之后设置缩放级别。 只需在map.fitBounds(bounds)之后添加map.setZoom(16) map.fitBounds(bounds) 这对我来说可以。

所有带有事件监听器的解决方案对我都不起作用(this.getZoom()在回调中始终未定义,this.setZoom()无效)。

我提出了这个解决方案很好用:

function set_zoom() {
    if(map.getZoom()) {map.setZoom(map.getZoom() - 1);}
    else {setTimeout(set_zoom, 5);}
}
setTimeout(set_zoom, 5);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM