问题描述
我有一个html标记,并且我想在其中有一个按钮来删除该标记
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'
}
}
]
});
如何获取单击删除按钮的事件?
解决方法
有多种方法可以做到这一点,但最简单的方法之一就是使用HTML onclick
事件。您只需为PoiHtml
修改字符串即可添加带有事件处理程序值的onclick
装饰。
我在how to add an event to a marker popup上创建了一个小提琴。每次您单击按钮,控制台都会在事件中记录"deleted"
以下是相关代码:
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");
}