Google Maps API v3: Can I setZoom after fitBounds?

前端 未结 23 2524
执笔经年
执笔经年 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 09:38

    To chime in with another solution - I found that the "listen for bounds_changed event and then set new zoom" approach didn't work reliably for me. I think that I was sometimes calling fitBounds before the map had been fully initialized, and the initialization was causing a bounds_changed event that would use up the listener, before fitBounds changed the boundaries and zoom level. I ended up with this code, which seems to work so far:

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

提交回复
热议问题