OpenLayers – Troubleshooting Why Layers Are Not Displayed in OpenLayers

openlayers

I am creating a map that contains some layers, all defined in an array called basemapsArray

var map = new ol.Map({
    layers: basemapsArray,
    controls : ol.control.defaults({
        zoom : false
    }),
    target: 'map',
    ...

The layers need to be defined when the map is created, but none should be loaded right away; the user needs to pick one by clicking a checkbox first.

How would I go about not displaying any layers when the application loads?

I know I can loop through them and use .setVisible(), but perhaps there is a more elegant way?

Best Answer

Set visible to false while defining each layer as visible istrue by default.

{ visible: false }

Example:

var layers = [
        new ol.layer.Tile({
          source: new ol.source.OSM(),
          visible: false
        }),
        new ol.layer.Tile({
          extent: [-13884991, 2870341, -7455066, 6338219],
          visible: false,
          source: new ol.source.TileArcGISRest({
            url: url
          })
        })
      ];

You can find the properties to be set for a layer in below:
http://openlayers.org/en/v3.6.0/apidoc/ol.layer.Base.html