Example of setting a layer source after construction.
Typically, the source for a layer is provided to the layer constructor. If you need to set a layer source after construction, this can be done with the layer.setSource()
method.
The layer in the map above is constructed with no source. Use the links below to set/unset the layer source. A layer is not rendered until its source is set.
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.js';
const source = new OSM();
const layer = new TileLayer();
const map = new Map({
layers: [layer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});
document.getElementById('set-source').onclick = function () {
layer.setSource(source);
};
document.getElementById('unset-source').onclick = function () {
layer.setSource(null);
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lazy Source</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
button.code {
font-family: Monaco,Menlo,Consolas,"Courier New",monospace;
font-size: 12px;
padding: 5px;
margin: 0 5px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<button id="set-source" class="code">layer.setSource(source)</button>
<button id="unset-source" class="code">layer.setSource(null)</button>
<script type="module" src="main.js"></script>
</body>
</html>
{
"name": "lazy-source",
"dependencies": {
"ol": "10.4.0"
},
"devDependencies": {
"vite": "^3.2.3"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}