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.
import 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileJSON from 'ol/source/TileJSON';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
import {fromLonLat} from 'ol/proj';
var key = 'Get your own API key at https://www.maptiler.com/cloud/';
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 TileJSON({
url: 'https://api.maptiler.com/maps/outdoor/tiles.json?key=' + key,
tileSize: 512,
}),
}) ],
view: new View({
center: fromLonLat([-112.18688965, 36.057944835]),
zoom: 15,
maxZoom: 18,
constrainOnlyCenter: true,
}),
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Layer Zoom Limits</title>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="main.js"></script>
</body>
</html>
{
"name": "layer-zoom-limits",
"dependencies": {
"ol": "6.4.3"
},
"devDependencies": {
"parcel": "1.11.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --experimental-scope-hoisting --public-url . index.html"
}
}