Google Maps API 3 - limit pan/map bounds

前端 未结 3 1699

I am completely new to Google Maps and am just creating my first map so that I can incorporate it into my website.

I am trying to limit the area that the user can m

相关标签:
3条回答
  • 2020-12-14 05:21

    Just for anyone who stumbles upon the now-outdated info on this page as I did, the maps API now provides a built-in way to restrict the map viewport bounds via the restriction property of the MapOptions interface, see docs here. This example restricts north-south panning from showing Antarctica:

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 20, lng: -52},
          zoom: 3,        
          restriction: {latLngBounds:{north: 83.8, south: -57, west: -180, east: 180}}
        }); 
    }
    
    0 讨论(0)
  • 2020-12-14 05:26

    You have your strictBounds mixed up - change the order of them and it should work fine.

    A LatLngBounds should be SW corner first, NE corner second: http://code.google.com/apis/maps/documentation/javascript/reference.html#LatLngBounds

    var strictBounds = new google.maps.LatLngBounds(
      new google.maps.LatLng(49.90878, -7.69042),
      new google.maps.LatLng(60.88770, -0.83496) 
    );
    
    0 讨论(0)
  • 2020-12-14 05:39

    Above code helped me, but didn't solve my issue. I needed to disable the panning based on polygon drawn on the map. I needed to limit panning to that particular window of the map. So user not pan faraway from the initial map.

    function disablePanning(enableBounds) {
    // listen to bound change event once to store the SW and NE corner
    
    google.maps.event.addListener(map, 'bounds_changed', function() {
        // only set it once
        if (enableBounds == null) {
            enableBounds = map.getBounds();
        }
    });
    var lastValidCenter=null;
    google.maps.event.clearListeners(map,'center_changed');
    google.maps.event.addListener(map, 'center_changed', function() {
        if(enableBounds!=null && lastValidCenter==null){
            lastValidCenter = enableBounds.getCenter();
        }
        if (enableBounds != null && enableBounds != 'undefined') {
            var ne = enableBounds.getNorthEast();
            var sw = enableBounds.getSouthWest();
            var allowedBounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(sw.lat(), sw.lng()),
                    new google.maps.LatLng(ne.lat(), ne.lng()));
    
            if (allowedBounds.contains(map.getCenter())) {
                // still within valid bounds, so save the last valid position
                lastValidCenter = enableBounds.getCenter();
                return;
            }
    
            // not valid anymore => return to last valid position
            if(lastValidCenter!=null)
                map.panTo(lastValidCenter);
        }
    });
    

    }

    0 讨论(0)
提交回复
热议问题