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

前端 未结 6 1080
一向
一向 2020-12-04 09:28

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%

6条回答
  •  没有蜡笔的小新
    2020-12-04 10:14

    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);
    

    Update: See @Nequin's answer using addListenerOnce for a better solution that doesn't require a timeout.

提交回复
热议问题