我按照this Mapbox GL JS example一步一步地让我们的地图图层显示和隐藏。
然而,在这种情况下,如果我们的访客忘记关闭顶部的图层,就像“四月”一样,当他们点击“六月”时,六月的图层无法看到,因为它们位于四月层之下。
我有什么方法可以在图层之间切换?或者如果我有一个按钮,其他按钮将自动关闭?
我的代码如下。
HTML:
<div id='map'></div>
<nav id="menu"></nav>
JavaScript的:
mapboxgl.accessToken = 'pk.eyJ1IjoibWFyY3VzcGciLCJhIjoiY2l2NmdtZjdyMDAwMjJ6bDVhb2JndDlrMiJ9.EopxTk2v-1WrWsgbLmL_XA';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/marcuspg/cj6xc2cb49xpg2sqpuuwbob0u', // stylesheet location
//center:[]
//zoom:13
});
// add a map layer_3d buildings
map.on('load', function() {
map.addLayer({
'id': '3d-buildings',
'source': 'composite',
'source-layer': 'building',
'filter': ['==', 'extrude', 'true'],
'type': 'fill-extrusion',
'minzoom': 15,
'paint': {
'fill-extrusion-color': '#aaa',
'fill-extrusion-height': {
'type': 'identity',
'property': 'height'
},
'fill-extrusion-base': {
'type': 'identity',
'property': 'min_height'
},
'fill-extrusion-opacity': .6
}
});
});
// group two layers into one
toggleLayer(['April','April_2'], 'April');
toggleLayer(['June','June_2'], 'June');
toggleLayer(['September', 'September_2'], 'September');
toggleLayer(['December','December_2'], 'December');
function toggleLayer(ids, name) {
var link = document.createElement('a');
link.href = '#';
link.className = 'active';
link.textContent = name;
link.onclick = function (e) {
e.preventDefault();
e.stopPropagation();
for (layers in ids){
var visibility = map.getLayoutProperty(ids[layers], 'visibility');
if (visibility === 'visible') {
map.setLayoutProperty(ids[layers], 'visibility', 'none');
this.className = '';
} else {
this.className = 'active';
map.setLayoutProperty(ids[layers], 'visibility', 'visible');
}
}
};
var layers = document.getElementById('menu');
layers.appendChild(link);
}
CSS:
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
#menu {
background: #fff;
position: absolute;
z-index: 1;
top: 10px;
right: 10px;
border-radius: 3px;
width: 120px;
border: 1px solid rgba(0, 0, 0, 0.4);
font-family: 'Open Sans', sans-serif;
}
#menu a {
font-size: 13px;
color: #404040;
display: block;
margin: 0;
padding: 0;
padding: 10px;
text-decoration: none;
border-bottom: 1px solid rgba(0, 0, 0, 0.25);
text-align: center;
}
#menu a:last-child {
border: none;
}
#menu a:hover {
background-color: #f8f8f8;
color: #404040;
}
#menu a.active {
background-color: #3887be;
color: #ffffff;
}
#menu a.active:hover {
background: #3074a4;
}