title: How to close a popup when marker layer is closed on click using Mapbox GL JS
body: <p>I am having trouble closing/removing popups when marker layers are closed on click. I have tried to use popup.remove in an onclick function, but haven't had much luck binding the function with the buttons used to show and hide the marker layers. Any help on having popups close when markers layers are closed or hidden would be much appreciated.</p>
  
  <p><strong>JS:</strong></p>
  
  <pre class="lang-js prettyprint-override"><code>    // add popup to layer
      map.on('click', function (e) {
          var features = map.queryRenderedFeatures(e.point, {
              layers: ["high_camp"] // Add layers
          });
  
          if (!features.length) {
              return;
          }
  
          var feature = features[0];
  
          var popup = new mapboxgl.Popup({
              offset: {
                  'top': [0, 0],
                  'top-left': [0, 0],
                  'top-right': [0, 0],
                  'bottom': [0, -40],
                  'bottom-left': [0, -40],
                  'bottom-right': [0, -40],
                  'left': [18, -22],
                  'right': [-18, -22],
              }
          })
          .setLngLat(feature.geometry.coordinates)
          .setHTML(feature.properties.NAME)
          // Change attribute, properties.'Replace' (Uppercase)
          .addTo(map);
      });
  
      // Toggle high camp layer
      var togglehighcampId = ["high_camp"]; // Add layer
  
      document.getElementById("highcampIcon").onclick = function (e) { 
          // Change button name, getElementById('Replace')
          for (var index in togglehighcampId) {
              var clickedLayer = togglehighcampId[index];
              e.preventDefault();
              e.stopPropagation();
  
              var visibility = map.getLayoutProperty(clickedLayer, 'visibility');
  
              if (visibility === 'none') {
                  map.setLayoutProperty(clickedLayer, 'visibility', 'visible');
                  this.className = '';
              } else {
                  this.className = 'on';
                  map.setLayoutProperty(clickedLayer, 'visibility', 'none');
              }
          }
  
      };
  </code></pre>