Hide/Show layerGroups in Leaflet with own Buttons
jquery, leaflet
Solution
First you need a link for each layer
<ul>
<li><a id="restaurants" href="#">restaurants</a></li>
<li><a id="sport" href="#">sport</a></li>
<li><a id="sights" href="#">sights</a></li>
</ul>
Then, for each link you can write a handler like this (example with jQuery)
$("#restaurants").click(function(event) {
event.preventDefault();
if(map.hasLayer(restaurants)) {
$(this).removeClass('selected');
map.removeLayer(restaurants);
} else {
map.addLayer(restaurants);
$(this).addClass('selected');
}
});
You have an example here http://jsfiddle.net/FranceImage/c5Yfb/
Problem
I have a leaflet map with several markers in it. I've put these markers in "Layer Groups" to be able to show and hide the marker-categories. These are my markers: ``` var aa = L.marker([48.185556, 11.620278]).bindPopup('AA'), bb = L.marker([48.152222, 11.592778]).bindPopup('BB'), cc = L.marker([48.161209, 11.597989]).bindPopup('CC'), dd = L.marker([48.14350, 11.58775]).bindPopup('DD'), ee = L.marker([48.14989, 11.59094]).bindPopup('EE'), ff = L.marker([48.15958, 11.60608]).bindPopup('FF'); var restaurants = L.layerGroup([aa, bb]); var sport = L.layerGroup([cc, dd]); var sights = L.layerGroup([ee, ff]); ``` That works quite well when I use Layers Control and overlayMaps: ``` var overlayMaps = { "Restaurants": restaurants, "Sport": sport, "Sights": sights }; L.control.layers(overlayMaps).addTo(map); ``` But now I want to be able to make that work (hide and show the layer groups) with my own "buttons" (icons). My html: ``` <div class="header"> <a href="#"> <span class="fontawesome-food"></span> <span class="fontawesome-heart-empty"></span> <span class="fontawesome-eye-open"></span> </a> </div> ``` I guess it's possible with removeLayer or something like that but I just don't get it how to make it work (show and hide restaurants-, sport- and sights-layer). So, I want to acchieve it that my layers are visible when I click on the Icons in my header and that they disappear when I click a second time. Thanks so much!