15

I want to restrict where the user can pan on the map, but I can't seem to find any resources that tell how to set the max extent of a map view in OpenLayers 3. I know there was a solution in OpenLayers 2. Is it possible in the new version?

18

This can simply be done by defining extent in the View object. eg

var view = new ol.View({
    ...
    extent: [minx,miny,maxx,maxy]
    ...
});
var map = new ol.Map({
    ...
    view: view,
    ...
});
3

Another option is:

...
var map = new ol.Map({
          layers: [...],
          overlays: [...],
          target: document.getElementById('map'),
          view: new ol.View({
             center: ol.proj.transform([minx,miny,maxx,maxy], 
                     'EPSG:4326', 'EPSG:3857'),
             zoom: ...,    
             maxZoom: ..., 
             minZoom: ..., 
             extent: ol.proj.transform([minx-n,miny-n,maxx+n,maxy+n], 
                     'EPSG:4326', 'EPSG:3857')
             })
        });
...
1

Like Ragnagord already pointed out it is necessary to set the extent in your ol.view.

Depending on what you want to refer to the easiest way is to get the extent directly from your desired projection (ol.proj.Projection) or layer (any class of ol.layer) using the getExtent() function. In case of EPSG:3857 this works:

var map = new ol.Map({
    ...
    view: new ol.View({
        ...
        extent: ol.proj.get("EPSG:3857").getExtent()
  })
});
1

I have to point out if we consider the map projection, in my case between WGS84 and Spherical Mercator, there is an alternative with ol.proj.transformExtent. An answer was found here. Extent is assigned as follows:

var map = new ol.Map({
   .
   .
   .
   view: new ol.View({
        extent:  ol.proj.transformExtent([minx, miny, maxx, maxy], 'EPSG:4326', 'EPSG:3857');
         .
         .
         .
        )}
)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.