I need Little help.
I want to display my layer and legend with one single button. With this code i am adding both (legend and layer) But when i unchecked my button only layer is removing. I want to remove my legend too with the same button.
I am unable to adjust the code please guide me how to use multiple getelementByID with single if.
Button
<button type="button" class="btn btn-outline-warning"><label>Test Layer <input type="checkbox" id="testlayer" ></label></button>
and JS part is
testlayer.onclick = function() {
var testlayerr = new TileLayer({
source: new TileWMS({
url: 'http://127.0.0.1:8080/geoserver/wms',
params: { 'LAYERS': 'MYDB:SoilMap' },
serverType: 'geoserver',
transition: 0,
}),
});
var testlayer = new ImageWMS({
url: 'http://127.0.0.1:8080/geoserver/wms',
params: { 'LAYERS': 'MYDB:SoilMap' },
serverType: 'geoserver',
transition: 0,
});[![enter image description here][1]][1]
var updateLegend = function(resolution) {
var graphicUrl = testlayer.getLegendUrl(resolution);
var img = document.getElementById('legend');
img.src = graphicUrl;
};
var resolution = map.getView().getResolution();
updateLegend(resolution);
this.onclick = function() {
if (document.getElementById("testlayer").checked) {
map.addLayer(testlayerr);
} else {
map.removeLayer(testlayerr);
}
};
}
getElementById()
only ever returns one element. If you want to find multiple elements you can either use multiple getElementById() calls or instead add a class to the elements and use getElementsByClassName()
, which returns an HTMLCollection.
You have no code there to remove the legend. To hide the legend when the layer is hidden, your final onclick
function needs to be something like:
// your HTML doesn't include the legend ID, so I've set a placeholder of "yourLegendElementId"
this.onclick = function() {
// find the legend element
var legend = document.getElementById("yourLegendElementId");
if (document.getElementById("testlayer").checked) {
map.addLayer(testlayerr);
// make sure the legend is visible
legend.style.display = "block";
} else {
map.removeLayer(testlayerr);
// make sure the legend is hidden
legend.style.display = "none";
}
};