Javascript 在 OpenLayers 中删除图层

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12126067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:09:44  来源:igfitidea点击:

Removing a layer in OpenLayers

javascriptopenlayers

提问by Mitchell Ingram

I don't know why this isn't working. I would assume 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 piling on the layers and not removing any. Any help?

它只是不断地堆积在层上,而不是去除任何层。有什么帮助吗?

回答by batzkoo

Your ifstatement will always evaluate to false because you re-declare graphicevery time you run that part of code. The variable is hoistedand the value of it will be undefined when the ifis evaluated.

您的if语句将始终评估为 false,因为您graphic每次运行该部分代码时都会重新声明。变量被提升并且在评估时它的值将是未定义的if

You need to declare the variable in a different 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);
}

回答by M-k

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

使用map.getLayersByName(layerName)获取图层。您可能需要跟踪某个数组或其他东西中的图层名称

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

该方法返回一个数组,因此您可以遍历层数组并使用map.removeLayer(layer).

You can externalize this solution in a different function if you want and it works.

如果需要,您可以在不同的函数中将此解决方案外部化,并且它可以工作。

回答by gis_wild

Experimentially I found out that removing a layer doesn't clean the memory in the client browser(in my case it's about 2 hyndreds of wms layers that get about 2gb of memory in firefox). So the only approach that worked for me is to create only one wms layer and to mergeNewParams. Hope it will help.

通过实验,我发现删除图层不会清除客户端浏览器中的内存(在我的例子中,它是大约 2 个 wms 图层,在 firefox 中获得大约 2GB 的内存)。所以对我有用的唯一方法是只创建一个 wms 层并合并新参数。希望它会有所帮助。