Adjust layer opacity based on user input
The layer.setOpacity()
method can be called to adjust the opacity of a layer.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import ImageTile from 'ol/source/ImageTile.js';
import OSM from 'ol/source/OSM.js';
const key = 'Get your own API key at https://www.maptiler.com/cloud/';
const imagery = new TileLayer({
className: 'ol-layer-imagery',
source: new ImageTile({
attributions:
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> ',
url: 'https://api.maptiler.com/maps/satellite/{z}/{x}/{y}.jpg?key=' + key,
tileSize: 512,
maxZoom: 20,
}),
});
const osm = new TileLayer({
source: new OSM(),
});
const map = new Map({
layers: [imagery, osm],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
const opacityInput = document.getElementById('opacity-input');
const opacityOutput = document.getElementById('opacity-output');
function update() {
const opacity = parseFloat(opacityInput.value);
osm.setOpacity(opacity);
opacityOutput.innerText = opacity.toFixed(2);
}
opacityInput.addEventListener('input', update);
update();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Layer Opacity</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>
<label>
Layer opacity
<input id="opacity-input" type="range" min="0" max="1" step="0.01" value="1" />
<span id="opacity-output"></span>
</label>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "layer-opacity",
"dependencies": {
"ol": "10.5.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}