Google Maps v3 fitBounds() Zoom too close for single marker

前端 未结 17 2106
别那么骄傲
别那么骄傲 2020-12-12 23:28

Is there a way to set a max zoom level for fitBounds()? My problem is that when the map is only fed one location, it zooms in as far as it can go, which really

17条回答
  •  庸人自扰
    2020-12-12 23:54

    This gives you a direct control upon max allowed zoom on bounds fitting.

    var fitToMarkers = function(map, markers, maxZoom) {
        if (typeof maxZoom == 'undefined') maxZoom = 15;
    
        google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
            if (this.getZoom() > maxZoom) {
                this.setZoom(maxZoom);
            }
        });
    
        var bounds = new google.maps.LatLngBounds();
        for (var m = 0; m < markers.length; m++) {
            var marker = markers[m];
            var latlng = marker.getPosition();
            bounds.extend(latlng);
        }
    
        map.fitBounds(bounds);
    };
    

提交回复
热议问题