Using minZoom and maxZoom to control layer visibility.
Layers support minZoom
and maxZoom
options for controlling visibility based on the view's zoom level. If min or max zoom are set, the layer will only be visible at zoom levels greater than the minZoom
and less than or equal to the maxZoom
. After construction, the layer's setMinZoom
and setMaxZoom
can be used to set limits. This example shows an OSM layer at zoom levels 14 and lower and a USGS layer at zoom levels higher than 14.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Layer Zoom Limits</title>
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="index.js"></script>
</body>
</html>
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import XYZ from 'ol/source/XYZ';
import {transformExtent, fromLonLat} from 'ol/proj';
var mapExtent = [-112.261791, 35.983744, -112.113981, 36.132062];
var map = new Map({
target: 'map',
layers: [
new TileLayer({
maxZoom: 14, // visible at zoom levels 14 and below
source: new OSM()
}),
new TileLayer({
minZoom: 14, // visible at zoom levels above 14
source: new XYZ({
attributions: 'Tiles © USGS, rendered with ' +
'<a href="http://www.maptiler.com/">MapTiler</a>',
url: 'https://tileserver.maptiler.com/grandcanyon/{z}/{x}/{y}.png'
})
})
],
view: new View({
center: fromLonLat([-112.18688965, 36.057944835]),
zoom: 15,
maxZoom: 18,
extent: transformExtent(mapExtent, 'EPSG:4326', 'EPSG:3857'),
constrainOnlyCenter: true
})
});
{
"name": "layer-zoom-limits",
"dependencies": {
"ol": "6.1.1"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}