Edit

Lazy Source

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.

index.html<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Lazy Source</title>
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></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="index.js"></script>
  </body>
</html>
index.jsimport 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';

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);
};
package.json{
  "name": "lazy-source",
  "dependencies": {
    "ol": "6.1.1"
  },
  "devDependencies": {
    "parcel": "1.11.0"
  },
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build --experimental-scope-hoisting --public-url . index.html"
  }
}