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?
4 Answers
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,
...
});
-
But in openlayers.org/en/v3.0.0/apidoc/ol.View.html there is not such option– DavidddOct 15, 2014 at 14:42
-
A lot is not documented, or experimental and only visible when stable is not checked Oct 15, 2014 at 19:33
-
5This isn't a real extent. It just keeps the extents within view, meaning there is ugly white space all around the extent. Oct 22, 2015 at 21:40
-
Meanwhile,
extent
has become a proper documented feature: openlayers.org/en/latest/apidoc/module-ol_View-View.html (as of writing, "latest" = v5.3.0) Jan 25, 2019 at 11:23
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')
})
});
...
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()
})
});
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');
.
.
.
)}
)}