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 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import TileLayer from 'ol/layer/Tile';
import View from 'ol/View';
var source = new OSM();
var layer = new TileLayer();
var 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>
<title>Lazy Source</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;
}
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 src="main.js"></script>
</body>
</html>
{
"name": "lazy-source",
"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"
}
}