使用自定义控件的Mapbox GL JS切换图层

时间:2019-03-08 23:36:15

标签: javascript mapbox-gl-js

我一直在使用下面的Mapbox GL JS示例来切换图层的开关选项。本示例(https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)中使用的文本按钮效果很好,但是我现在需要创建带有图标的自定义按钮,这些图标可以切换具有唯一ID的一系列地图图层的图层。关于如何最好地实现这一点,我一直有一些不同的想法,但是还没有走太远。有没有办法用菜单中的图标或某种其他类型的按钮替换附加的链接?谢谢!

var toggleableLayerIds = ['sample-one', "sample-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);
}

1 个答案:

答案 0 :(得分:0)

您可以通过在添加菜单元素之前创建其他元素来实现此目的

请参见下面的代码:

var toggleableLayerIds = ['sample-one', "sample-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 button = document.createElement('div');
    var icon = document.createElement('img');
    icon.src = '[path to your icon]';
    button.appendChild(img);
    button.appendChild(link);
    var layers = document.getElementById('menu');
    layers.appendChild(button);
}

在这里,我创建一个包含图像元素和链接的div。 您可以根据需要自定义菜单。