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 Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import {fromLonLat} from 'ol/proj.js';
import OSM from 'ol/source/OSM.js';
import TileJSON from 'ol/source/TileJSON.js';
const key = 'Get your own API key at https://www.maptiler.com/cloud/';
const 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-v2/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>
<meta charset="UTF-8">
<title>Layer Zoom Limits</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "layer-zoom-limits",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}