-1

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

0

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.

  • Thanks, i need your option #2, but i guess what was tripping me up is that this doesn't work for me: mapObj.getLayers().forEach(function (lyr) { if (itemGUID === lyr.WMSLayerGUID) { lyr.visible = !lyr.visible; } }); – Phil Sep 23 '18 at 0:36
  • lyr.visible is always 'undefined', even after i use the 'setvisible' function – Phil Sep 23 '18 at 0:37
  • Related to bad use of Openlayers in your loop, not to setVisible... – ThomasG77 Sep 23 '18 at 0:46
  • mapObj.getLayers().forEach(function (lyr) { if (itemGUID === lyr.get('WMSLayerGUID')) { lyr.setVisible(!lyr.getVisible()); } }); – ThomasG77 Sep 23 '18 at 0:46
  • 1
    I was wrong maybe (tried to guess only from your code and misunderstood it seems) lyr.visible will always be undefined and it's normal. Property visible is only accessible via lyr.getVisible() – ThomasG77 Sep 23 '18 at 1:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.