Skip to content

Commit

Permalink
Support click event on marker instance (#167)
Browse files Browse the repository at this point in the history
* support click handlers on markers

* log map click

* force popup on click
  • Loading branch information
kochis authored Jun 3, 2024
1 parent d26931f commit 97867c5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
12 changes: 12 additions & 0 deletions demo/views/add-a-marker.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@
.setLngLat([lng, lat])
.addTo(map);
marker.on('click', (e) => {
console.log('MARKER CLICK', e);
});
// use custom marker from URL
$('#imageUrl').on('change', (e) => {
const url = e.target.value;
Expand All @@ -60,9 +64,17 @@
})
.setLngLat([lng, lat])
.addTo(map);
marker.on('click', (e) => {
console.log('MARKER CLICK', e);
});
});
});
map.on('click', (e) => {
console.log('MAP CLICK', e);
});
map.on('error', (err) => {
console.error(err);
$('#error-alert').show();
Expand Down
15 changes: 14 additions & 1 deletion src/ui/RadarMarker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ const createImageElement = (options: RadarMarkerImage) => {
}
return element;
}

class RadarMarker extends maplibregl.Marker {
_map!: RadarMap;
_image?: RadarMarkerImage;
Expand Down Expand Up @@ -105,7 +106,7 @@ class RadarMarker extends maplibregl.Marker {

// set popup text or HTML
if (markerOptions.popup) {
const popup = new maplibregl.Popup(markerOptions.popup)
const popup = new maplibregl.Popup(markerOptions.popup);

if (markerOptions.popup.text) {
popup.setText(markerOptions.popup.text);
Expand All @@ -116,6 +117,18 @@ class RadarMarker extends maplibregl.Marker {

this.setPopup(popup);
}

// pass-through click event from element to marker
const element = this.getElement();
if (element) {
element.addEventListener('click', (e) => {
e.stopPropagation(); // stop propagation to map
if (this._popup) {
this.togglePopup();
}
this.fire('click', e);
});
}
}

addTo(map: RadarMap) {
Expand Down

0 comments on commit 97867c5

Please sign in to comment.