I'm trying to write a function that let's me hide / show leaflet layers. The data on which layer is to be shown / hidden is fetched from a data attribute.
Obviously, as the latter is a string, leaflet will throw errors (leaflet.js:5 Uncaught TypeError: Cannot create property '_leaflet_id' on string 'someLayer')
Here's my code:
<div class="single-filter" data-layer="someLayer">
let someLayer = L.layerGroup([
L.marker([2131.25, 2854.25], { icon: someIcon })
]).addTo(map);
$('.single-filter').on('click', setFilter);
function setFilter() {
let layer = $(this).data('layer');
toggleLayer(layer);
}
function toggleLayer(layer) {
if (map.hasLayer(layer)) {
map.removeLayer(layer);
} else {
map.addLayer(layer);
}
}
How would I be editing this so it actually recieves the right data format? (e.g. the object someLayer instead of the string someLayer).
Thanks for your assistance!