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

前端 未结 17 2129
别那么骄傲
别那么骄傲 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 23:49

    I like mrt's solution (especially when you don't know how many points you will be mapping or adjusting for), except it throws the marker off so that it isn't in the center of the map anymore. I simply extended it by an additional point subtracting .01 from the lat and lng as well, so it keeps the marker in the center. Works great, thanks mrt!

    // Pan & Zoom map to show all markers
    function fitToMarkers(markers) {
    
        var bounds = new google.maps.LatLngBounds();
    
        // Create bounds from markers
        for( var index in markers ) {
            var latlng = markers[index].getPosition();
            bounds.extend(latlng);
        }
    
        // Don't zoom in too far on only one marker
        if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
           var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
           var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - 0.01, bounds.getNorthEast().lng() - 0.01);
           bounds.extend(extendPoint1);
           bounds.extend(extendPoint2);
        }
    
        map.fitBounds(bounds);
    
        // Adjusting zoom here doesn't work :/
    
    }
    

提交回复
热议问题