OpenLayers 5 – How to Hide a Layer

openlayers

How can you show/hide a layer (not a feature) in openlayers 5?

There is a visible parameter to the TileLayer object i'm working with, but changing that value does nothing. https://openlayers.org/en/latest/apidoc/module-ol_layer_Tile-TileLayer.html

Best Answer

You have two choices

When instanciating the layer

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';

var osm = new TileLayer({
  source: new OSM(),
  visible: false
});
var map = new Map({
  layers: [osm],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

After instanciation of the layer

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';

var osm = new TileLayer({
  source: new OSM()
});
var map = new Map({
  layers: [osm],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});
osm.setVisible(false);

setVisible method is inherited from http://openlayers.org/en/latest/apidoc/module-ol_layer_Base-BaseLayer.html

PS: At the moment, the API is more readable in version 4.6.5 of the docs. as you have all inherited properties shown in one place. Since version 5.0, a refactoring of the docs related to TypeScript/Typedoc is ongoing but not finished, hence the poor readability at the moment.

Related Question