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.
markersS
?data-list-id
attribute?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 themarkersS.getLayers()
call) are arbitrary, and they're not magically read from elsewhere.