Google Maps API v3: Can I setZoom after fitBounds?

前端 未结 23 2488
执笔经年
执笔经年 2020-11-27 09:35

I have a set of points I want to plot on an embedded Google Map (API v3). I\'d like the bounds to accommodate all points unless the zoom level is too low (i.e., zoomed out

23条回答
  •  死守一世寂寞
    2020-11-27 10:02

    I had the same issue and I was able to solve it using the following code. This listener (google.maps.addListenerOnce()) event will only get fired once, right after map.fitBounds() is executed. So, there is no need to

    1. Keep track of and manually remove the listener, or
    2. Wait until the map is idle.

    It sets the appropriate zoom level initially and allows the user to zoom in and out past the initial zoom level because the event listener has expired. For example, if only google.maps.addListener() was called, then the user would never be able to zoom-in past the stated zoom level (in the case, 4). Since we implemented google.maps.addListenerOnce(), the user will be able to zoom to any level he/she chooses.

    map.fitBounds(bounds);
    
    var zoom_level_for_one_marker = 4;
    
    google.maps.event.addListenerOnce(map, 'bounds_changed', function(event){
       if (this.getZoom() >= zoom_level_for_one_marker){  
           this.setZoom(zoom_level_for_one_marker) 
       }
    });
    

提交回复
热议问题