Delete a layer in OpenLayers

I do not know why this does not work. I would suggest that the answer is really simple. I need to remove a layer before adding a new one.

if (graphic) { window.map.removeLayer(graphic); } var graphic = new OpenLayers.Layer.Image( 'Sightline'+''+SC, url, new OpenLayers.Bounds(derWesten[0].firstChild.nodeValue,derSueden[0].firstChild.nodeValue,derOsten[0].firstChild.nodeValue, derNorden[0].firstChild.nodeValue), new OpenLayers.Size(0,0), options ); window.map.addLayer(graphic); 

It just keeps overlays on layers and doesn't remove them. Any help?

+4
source share
3 answers

Your if will always evaluate to false because you re-declare graphic every time you run this piece of code. The variable will be raised, and the value will be undefined when if is evaluated.

You need to declare a variable in another scope:

 var graphic; function removeAddLayer() { if (graphic) { window.map.removeLayer(graphic); } graphic = new OpenLayers.Layer.Image( /* stuff */); // note: no 'var' in front of graphic window.map.addLayer(graphic); } 
+10
source

Use map.getLayersByName(layerName) to get the layers. You may need to keep track of the names of the layers in some kind of array or something like

The method returns an array, so you look at the array of layers and use map.removeLayer(layer) .

You can screen this solution in another function if you want, and it works.

+7
source

I experimentally found out that deleting a layer does not clear the memory in the client browser (in my case, these are about 2 hinddreds of wms layers that get about 2 GB of memory in firefox). Therefore, the only approach that worked for me was to create only one layer of wms and mergeNewParams. Hope this helps.

0
source

All Articles