简体   繁体   中英

remove layer from open layers not working

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);
}

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]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM