How to add “click” listener on marker in mapbox-gl-js
I have been digging to try to find the solution for this little feature but can be a waster time, even because it's not in the MapboxGL documentation.
Solution below shows how to add a click event listener to a Mapbox Marker.
Stations.features.forEach((station) => {
// image
const elImg = document.createElement("img");
elImg.setAttribute("src", StationMarker);
const el = document.createElement('div');
// tooltip
const elTooltip = document.createElement("div");
elTooltip.className = "tooltip";
elTooltip.innerHTML = station.properties.Station;
// element
el.appendChild(elImg);
el.appendChild(elTooltip);
el.className = 'marker-station';
const marker = new mapboxgl.Marker(el)
.setLngLat([station.properties.xcoord, station.properties.ycoord])
//.setPopup(new mapboxgl.Popup({ closeButton: false }).setHTML(station.properties.Station))
.addTo(map);
marker.getElement().addEventListener('click', (event) => {
console.log("Clicked", event);
});
});