简体   繁体   中英

How to add class to HTML element on marker click with Leaflet JS

So, I'm trying to show a modal when a marker is clicked as a part of my Leaflet app. I already have some of the click functionality set on my marker layer, but I seem to be failing in triggering the necessary class being added to the modal element.

Currently I have a modal div with the following HTML outside of my map div.:

<div class="modal" id="infoBox">
<div class="modal-dialog">
<header class="modal-header"><button class="close-modal" aria-label="close modal" data-close> X</button></header>
<p>
<section class="modal-content">
Address: <span id="street"></span><br/>
Neighborhood: <span id="suburb"></span><br/>   
City: <span id="city"></span><br/>
Piece Type: <span id="type"></span><br/>
Description: <span id="desc"></span><br/>
</p>
</section>
<footer class="modal-footer"></footer>
</div>    
</div>

I am trying to add the class with the following function:

function zoomToFeature(e) {
  var latLngs = [e.target.getLatLng()];
  var markerBounds = L.latLngBounds(latLngs);
  var street = e.target.feature.properties.str_addr;
  var city = e.target.feature.properties.city;
  var desc = e.target.feature.properties.desc;
  document.getElementById('street').textContent = street;
  document.getElementById('city').textContent = city;
  document.getElementById('desc').textContent = desc;
  mymap.fitBounds(markerBounds);
  mymap.fitBounds(e.target.getBounds());
  document.getElementById('infoBox').classList.add('is-visible');
}

Which I add the click listener on the layer with the onEachFeature function like so:

function onEachFeature(feature, layer){
    layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight,
        click: zoomToFeature,
    });
}

When I manually add the .is-visible class the element I get the expected behaviour, but clicking the marker layer doesn't add the class. I'm basically trying to implement this Tutsplus Tutorial with some of the functionality in the Leaflet Chrolopleth tutorial . The click functionality works as far as pulling the feature info and zooming to the marker, but as above the modal stays hidden.

Running the classListAdd in a stand alone function in the dev console adds the class like so class="modal is-visible" but it doesn't trigger the functionality. As above manually changing the class to modal.is-visible does work, but I assume that's because it's an exact match for the css and it's not being re-interpreted.

Stripped down demo version can be seen here

The culprit is the line: e.target.getBounds()<\/code>

But Point features do not have such getBounds()<\/code> method (since they represent a single point, not an area).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM