I want help in removing layer on map using openlayers 5 . I have done to add the the layer on map using checkbox . what i want is that if the checkbox of that is layer is checked the layer will appear on map , and if the checkbox is unchecked again the layer will br removed from the map. I have tried the following code the code adds the layer on map but not removing it.
var checkbase = $('#main-side input')
$(checkbase).change(function(){
let checked = $(this)
let checkedVal = $(this).val();
test = new ol.layer.Image({
source: new ol.source.ImageWMS({
url: "http://3.16.123.168:8080/geoserver/wms?",
params: {
LAYERS: `twmp:${checkedVal} `
},
ratio: 1,
serverType: "geoserver",
crossOrigin: "anonymous"
})
});
if (checked.is(':checked')) {
map.addLayer(test);
} else {
map.removeLayer(test);
}
})
I have tried several methods for this like map.removeLayer and map.dispose and if the checkbox is unchecked remove the layer but not working.
You should not set test
to a new layer before you remove the old value. You code should look something like this
var test;
var checkbase = $('#main-side input')
$(checkbase).change(function(){
let checked = $(this)
let checkedVal = $(this).val();
if (checked.is(':checked')) {
test = new ol.layer.Image({
source: new ol.source.ImageWMS({
url: "http://3.16.123.168:8080/geoserver/wms?",
params: {
LAYERS: `twmp:${checkedVal} `
},
ratio: 1,
serverType: "geoserver",
crossOrigin: "anonymous"
})
});
map.addLayer(test);
} else {
map.removeLayer(test);
}
})
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.