使用自己的按钮在 Leaflet 中隐藏/显示 layerGroups [英] Hide/Show layerGroups in Leaflet with own Buttons

查看:112
本文介绍了使用自己的按钮在 Leaflet 中隐藏/显示 layerGroups的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张传单地图,里面有几个标记.我已将这些标记放在图层组"中,以便能够显示和隐藏标记类别.这些是我的标记:

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]);

当我使用 Layers Control 和 overlayMaps 时效果很好:

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); 

但现在我希望能够使用我自己的按钮"(图标)来完成这项工作(隐藏和显示图层组).我的html:

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>

我想使用 removeLayer 或类似的东西是可能的,但我只是不明白如何使它工作(显示和隐藏餐厅、运动和景点层).所以,我想实现当我单击标题中的图标时我的图层可见,并且当我第二次单击时它们会消失.非常感谢!

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!

推荐答案

首先你需要每个层的链接

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>

然后,对于每个链接,您可以编写这样的处理程序(jQuery 示例)

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');
   }
});

这里有一个例子http://jsfiddle.net/FranceImage/c5Yfb/

这篇关于使用自己的按钮在 Leaflet 中隐藏/显示 layerGroups的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆