Reputation: 4173
I have an html marker, and I want to have a button inside, to delete this marker
const PoiHtml = (poi: PointOfInterest) =>
`<h3>${poi.name}</h3>
<button>delete</button>`
const source = map.getSource(`marker-${poi.id}`) as any;
source.setData({
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'properties': {
'description': PoiHtml(poi),
'icon': 'theatre'
}
}
]
});
How can I get the event of clicked delete button ?
Upvotes: 0
Views: 172
Reputation: 3780
There are different ways to make this, but one probably the simplest is to use HTML onclick
event. you only need to modify your string for PoiHtml
adding an onclick
attibute with the value of the event handler.
I have created a quick fiddle on how to add an event to a marker popup. Every time you click the button, the console will log "deleted"
through the event
Here is the relevant code:
mapboxgl.accessToken = 'PUT HERE YOUR TOKEN';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-73.99594, 40.680975],
zoom: 17
});
map.on('style.load', function() {
map.on('click', function(e) {
let l = map.getStyle().layers;
var features = map.queryRenderedFeatures(e.point, {
layers: ['poi-label', 'transit-label', 'landuse', 'national-park']
});
let marker = new mapboxgl.Marker({
draggable: true
})
.setLngLat(e.lngLat)
.setPopup(new mapboxgl.Popup({
offset: 25
}) // add popups
.setHTML('<h3>Actions</h3><i class="fas fa-plus-circle"></i> <button type="button" class="btnDelete" onclick="clicked()" >delete</button>'));
marker.addTo(map);
marker.togglePopup();
});
});
function clicked() {
console.log("deleted");
}
Upvotes: 1