I am currently developing a web map that requires toggling two GeoJSON layers on and off. In the past, I used Mapbox JS to accomplish this task by adding and removing layers with a custom HTML button click. However, I am facing some challenges in achieving the same functionality with Mapbox GL JS. My goal is simple - to toggle the visibility of two layers using HTML buttons instead of links attached to a CSS menu:
var layers = document.getElementById('menu');
layers.appendChild(link);
I attempted to bind the function to the button element but haven't been successful yet:
document.getElementById("toggle-layer-one").onclick = function() {};
HTML:
<button data-balloon="Campsite" data-balloon-pos="right" id="toggle-layer-one"></button>
CSS
#toggle-layer-one {
background-image: url("../Assets/Campsite.svg");
background-size: 70px 70px;
height: 70px;
width: 70px;
border-top: 1px solid #fff;
}
JS
map.on('style.load', function () {
map.addSource("sample", {
type: "geojson",
data: "https://raw.githubusercontent.com/aarontaveras/Sample-GeoJSON-Data/master/sample.geojson"
});
map.addLayer({
"id": "sample-point-one",
"type": "symbol",
"source": "sample",
"filter": ["==", "$type", "Point"],
"layout": {
"icon-image": "circle-15",
"icon-size": 1,
"icon-anchor": "center",
}
});
map.setFilter('sample-point-one', ['==', 'region', 'Africa']);
map.addLayer({
"id": "sample-point-two",
"type": "symbol",
"source": "sample",
"filter": ["==", "$type", "Point"],
"layout": {
"icon-image": "circle-15",
"icon-size": 1,
"icon-anchor": "center",
}
});
map.setFilter('sample-point-two', ['==', 'region', 'Asia']);
});
// Toggle layers
var toggleableLayerIds = ["sample-point-one", "sample-point-two"];
for (var i = 0; i < toggleableLayerIds.length; i++) {
var id = toggleableLayerIds[i];
var link = document.createElement('a');
link.href = '#';
link.className = 'active';
link.textContent = id;
link.onclick = function (e) {
var clickedLayer = this.textContent;
e.preventDefault();
e.stopPropagation();
var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
if (visibility === 'visible') {
map.setLayoutProperty(clickedLayer, 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
}
};
var layers = document.getElementById('menu');
layers.appendChild(link);
}
Thank you!