Google Maps v3: Enforcing min. zoom level when using fitBounds

前端 未结 8 2075
攒了一身酷
攒了一身酷 2020-12-12 15:02

I\'m drawing a series of markers on a map (using v3 of the maps api).

In v2, I had the following code:

  bounds = new GLatLngBounds();

  ... loop th         


        
8条回答
  •  生来不讨喜
    2020-12-12 15:29

    In my case, I simply wanted to set the zoom level to one less than what google maps chose for me during fitBounds. The purpose was to use fitBounds, but also ensure no markers were under any map tools, etc.

    My map is created early and then a number of other dynamic components of the page have an opportunity to add markers, calling fitBounds after each addition.

    This is in the initial block where the map object is originally created...

    var mapZoom = null;
    

    Then this is added to each block where a marker is added, right before the map.fitBounds is called...

    google.maps.event.addListenerOnce(map, 'bounds_changed', function() { 
        if (mapZoom != map.getZoom()) { 
            mapZoom = (map.getZoom() - 1); 
            map.setZoom(mapZoom); 
        } 
    });
    

    When using 'bounds_changed' without the check in place, the map zoomed out once for every marker regardless of whether it needed it or not. Conversely, when I used 'zoom_changed', I would sometimes have markers under map tools because the zoom didn't actually change. Now it is always triggered, but the check ensures that it only zooms out once and only when needed.

    Hope this helps.

提交回复
热议问题