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?
Your if
statement will always evaluate to false because you re-declare graphic
every time you run that part of code. The variable is hoisted and the value of it will be undefined when the if
is evaluated.
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);
}