Reputation: 297
I'm new to open layers and currently trying to implement a map where i will display set of information when a layer has been check. currently i have this code to display the layer tiles
new LayerGroup({
title: 'Sample Layer Group',
fold: 'open',
layers: [
new Tile({
title: 'Layer 1',
visible: false,
source: new TileWMS({
url: '',
....
]
})
}),});
What i want to do is whenever i check or uncheck this layer I'll be able to get the state if it's visible or not.
I tried using map.getLayerGroup().getActive()
but only receiving true
every time.
thank you for the help!
Upvotes: 0
Views: 2339
Reputation: 5270
If I understand you correctly, you are actually looking for getVisible
method. Take a look at this example I made for you, based on some OL examples.
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js"></script>
<title>Group Layer</title>
</head>
<body>
<div style="margin: 1rem;">
<input type="checkbox" id="groupVisible" checked>Group |
<input type="checkbox" id="layer1Visible" checked>Layer 1 |
<input type="checkbox" id="layer2Visible" checked>Layer 2
</div>
<div id="map" class="map"></div>
<script type="text/javascript">
const layer1 = new ol.layer.Tile({
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'ne:ne', 'TILED': true},
serverType: 'geoserver',
crossOrigin: 'anonymous'
})
});
const layer2 = new ol.layer.Tile({
extent: [-13884991, 2870341, -7455066, 6338219],
source: new ol.source.TileWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states', 'TILED': true},
serverType: 'geoserver',
// Countries have transparency, so do not fade tiles:
transition: 0
})
});
const groupLayer = new ol.layer.Group({
layers: [layer1, layer2]
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
groupLayer
],
view: new ol.View({
center: [-10997148, 4569099],
zoom: 4
})
});
const groupChk = document.getElementById('groupVisible');
const layer1Chk = document.getElementById('layer1Visible');
const layer2Chk = document.getElementById('layer2Visible');
function log() {
console.log(
`group: ${groupLayer.getVisible()} layer1: ${layer1.getVisible()} layer2: ${layer2.getVisible()}`
);
}
groupChk.addEventListener('click', function () { groupLayer.setVisible(groupChk.checked); log(); });
layer1Chk.addEventListener('click', function () { layer1.setVisible(layer1Chk.checked); log(); });
layer2Chk.addEventListener('click', function () { layer2.setVisible(layer2Chk.checked); log(); });
</script>
</body>
</html>
Let me know if this is what you were looking for.
Upvotes: 2