Mapbox GL Menu Doesn't Respond to First Click

Viewed 47

Similar to this question, the layer switcher in my Map does not react to the first click. I learned that this issue has something to do with the definition of the initial visibility on the layers.

Here is the code. Unfortunately I don't know how and where to insert default visibility - do you have an idea?

map.on('click', ({ point }) => {

const features = map.queryRenderedFeatures(point, {
layers: ['City'] // replace with your layer name
});
if (!features.length) {
return;
}

const feature = features[0]; const popup = new mapboxgl.Popup({offset: [0, -15], closeButton: false, closeOnMove: true})
.setMaxWidth("auto")
.setLngLat(feature.geometry.coordinates)
.setHTML(
      `<table>\
                <tr>\
                  <td>City</td>\
                  <td>${feature.properties.City}</td>
                </tr>\ </table>`
        )
.addTo(map); }); var toggleableLayerIds = ['City']
  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)
  }
0 Answers
Related