Hide/Show layerGroups in Leaflet with own Buttons

前端 未结 2 547
孤街浪徒
孤街浪徒 2021-01-02 06:41

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:

<
相关标签:
2条回答
  • 2021-01-02 07:01

    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/

    0 讨论(0)
  • 2021-01-02 07:04

    First you need the classnames for the three buttons (restaurants, sports and sights). Then in Javscript you add: `

        <script>
            var restaurants = document.getElementsByClassName("restaurants");
            var sports = document.getElementsByClassName("sports");
            var sights = document.getElementsByClassName("sights");
    
            restaurants.onclick = function(e){
    
                // setFilter takes a feature object and returns 
                   true to show it and false to hide
                map.featureLayer.setFilter(function(f) {
                    return f.properties['marker-symbol'] === 'restaurants';
                });
                return false;
            };
    

    It is the setFilter-function that you will want to use and here is a good example Mpabox - Filtering Markers.

    The solution from @FranceImage should also work just fine.

    0 讨论(0)
提交回复
热议问题