【发布时间】:2019-07-31 15:34:39
【问题描述】:
我正在制作一个涉及打开和关闭两个 GeoJSON 图层的 web 地图。我以前使用 Mapbox JS 通过删除图层并在单击时使用自定义 HTML 按钮添加它们来执行此操作,但是使用 Mapbox GL JS 完成此操作时遇到问题。我要做的就是使用 HTML 按钮而不是附加到创建的 CSS 菜单的链接来打开和关闭两层(显示和隐藏):
var layers = document.getElementById('menu');
layers.appendChild(link);
我想我可以将函数绑定到按钮元素,但不能让它正常工作:
document.getElementById("toggle-layer-one").onclick = function() {};
HTML:
<button data-balloon="Campsite" data-balloon-pos="right" id="toggle-layer-one"></button>
CSS
#toggle-layer-one {
background-image: url("../Assets/Campsite.svg");
background-size: 70px 70px;
height: 70px;
width: 70px;
border-top: 1px solid #fff;
}
JS
map.on('style.load', function () {
map.addSource("sample", {
type: "geojson",
data: "https://raw.githubusercontent.com/aarontaveras/Sample-GeoJSON-Data/master/sample.geojson"
});
map.addLayer({
"id": "sample-point-one",
"type": "symbol",
"source": "sample",
"filter": ["==", "$type", "Point"],
"layout": {
"icon-image": "circle-15",
"icon-size": 1,
"icon-anchor": "center",
}
});
map.setFilter('sample-point-one', ['==', 'region', 'Africa']);
map.addLayer({
"id": "sample-point-two",
"type": "symbol",
"source": "sample",
"filter": ["==", "$type", "Point"],
"layout": {
"icon-image": "circle-15",
"icon-size": 1,
"icon-anchor": "center",
}
});
map.setFilter('sample-point-two', ['==', 'region', 'Asia']);
});
// Toggle layers
var toggleableLayerIds = ["sample-point-one", "sample-point-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);
}
谢谢!
【问题讨论】:
标签: javascript html css mapbox-gl-js mapbox-gl