0

Hello I'm trying to open popup in Leaflet by clicking on elements:

let markersS = L.markerClusterGroup();
const markers = places.map(function (place) {
  return markersS.addLayer(
    L.marker([place.lat, place.lon], { icon: iconO })
  .bindPopup(`Popup`)
    .on('popupopen', (e) => {
      e.target.setIcon(iconD);
    })
    .on('popupclose', (e) => {
      e.target.setIcon(iconO);
    })
  );
});

const selectPlace = function () {
  listItems.forEach((element) => {
    element.addEventListener('click', function () {

      //remove class from all elements
      listItems.forEach((el) => {
        el.parentNode.classList.remove('list__active');
      });
      
      //add class to current element
      element.parentNode.classList.add('list__active');
      
      const listID = element.getAttribute('data-list-id');
      const listItem = places[listID];
      map.setView([listItem.lat, listItem.lon], 13);

      //markersS - markerClusterGroup
      markersS.getLayers()[listID].openPopup();
    });
  });
};
selectPlace();

It works only on first clicked element. When I'm trying to click second one, the view goes to next location but the popup doesn't show up.

4
  • That's incomplete code (do read stackoverflow.com/help/minimal-reproducible-example). What's the value of markersS? Commented Aug 9, 2022 at 9:36
  • ...and how are you populating the data-list-id attribute? Commented Aug 9, 2022 at 11:48
  • @IvanSanchez it's just added in html
    – Matredok
    Commented Aug 9, 2022 at 11:54
  • That means that there's no guarantee that the ID added in HTML and the ID assigned by the L.Util.Stamp() logic will match. You should take a step back, and think on how to get the IDs to match. One of the typical ways to achieve this is to depend on an attribute present in the data. Just keep in mind that the IDs auto-assigned by Leaflet (the keys in the array resulting of the markersS.getLayers() call) are arbitrary, and they're not magically read from elsewhere. Commented Aug 9, 2022 at 12:00

0