Search code examples
arcgisarcgis-js-apiesri-maps

Panning the map to certain extent javascript API


I want to limit map extent to the initial extent of the map and limit user from panning more than certain extent.

I tried following but nothing has changed:

map = new Map( "map" , {
        basemap: "gray",    
        center: [-85.416, 49.000],
        zoom : 6,
        logo: false,
        sliderStyle: "small"
    });


    dojo.connect(map, "onExtentChange", function (){
    var initExtent = map.extent;
    var extent = map.extent.getCenter();
    if(initExtent.contains(extent)){}
    else{map.setExtent(initExtent)}
    });

Solution

  • Just to flesh out Simon's answer somewhat, and give an example. Ideally you need two variables at the same scope as map:

    initExtent to store the boundary of your valid extent, and

    validExtent to store the last valid extent found while panning, so that you can bounce back to it.

    I've used the newer dojo.on event syntax as well for this example, it's probably a good idea to move to this as per the documentation's recommendation - I assume ESRI will discontinue the older style at some point.

    var map;
    var validExtent;
    var initExtent;
    
    [...]
    
        require(['dojo/on'], function(on) {
            on(map, 'pan', function(evt) {
                if ( !initExtent.contains(evt.extent) ) {
                    console.log('Outside bounds!');
                } else {
                    console.log('Updated extent');
                    validExtent = evt.extent;
                }
            });
    
            on(map, 'pan-end', function(evt) {
                if ( !initExtent.contains(evt.extent) ) {
                    map.setExtent(validExtent);
                }
            });
        });
    

    You can do the same with the zoom events, or use extent-change if you want to trap everything. Up to you.