remove layer from open layers not working

5.8k Views Asked by At

I am trying to add layers from GeoServer; it's working fine but removing layers is not working. This is my code:

function loadTOCLayer(layerName) {
  var tl = new ol.layer.Tile({
    extent: [-20037508.34, -20037508.34, 20037508.34, 20037508.34],
    source: new ol.source.TileWMS( /** @type {olx.source.TileWMSOptions} */ ({
      url: 'http://172.16.1.58:8080/geoserver/KBJNL/gwc/service/wms',
      params: {
        'LAYERS': layerName,
        'TILED': true
      },
      serverType: 'geoserver'
    }))
  });

  map.addLayer(tl);
}


function removeTOCLayer(ss) {
  map.removeLayer(ss);
}
1

There are 1 best solutions below

0
On BEST ANSWER

You are mixing layer name and layer reference. You'll have to keep an index of layers by name. Try this:

var layersByName = {};
function loadTOCLayer(layerName) {
  var tl = new ol.layer.Tile({
    extent: [-20037508.34, -20037508.34, 20037508.34, 20037508.34],
    source: new ol.source.TileWMS( /** @type {olx.source.TileWMSOptions} */ ({
      url: 'http://172.16.1.58:8080/geoserver/KBJNL/gwc/service/wms',
      params: {
        'LAYERS': layerName,
        'TILED': true
      },
      serverType: 'geoserver'
    }))
  });

  layersByName[layerName] = tl;

  map.addLayer(tl);
}


function removeTOCLayer(ss) {
  map.removeLayer(layersByName[ss]);
}