I am using mapbox draw to draw a polygon. I would like it so that there can only be one drawn polygon on the screen at once. For example, the user draws a polygon and then clicks the polygon draw button again, the first polygon would be deleted. I have tried to do this using the draw.modechange but there is an error somewhere in way it is coded. When I clicked the polygon draw button, the existing polygon is deleted but when I try and draw the new polygon nothing is there.
this.map.on('draw.modechange', (e) => {
const data = draw.getAll();
console.log(draw.getMode());
if (draw.getMode() == 'draw_polygon') {
if (data.features.length > 1) {
draw.deleteAll();
}
}
});
The problem is that when the mode changes, an template empty feature of the corresponding type is added. And you delete it with all the features. So it's necessary to pass through all features and check for a template empty feature:
map.on('draw.modechange', (e) => {
const data = Draw.getAll();
if (Draw.getMode() == 'draw_polygon') {
var pids = []
// ID of the added template empty feature
const lid = data.features[data.features.length - 1].id
data.features.forEach((f) => {
if (f.geometry.type === 'Polygon' && f.id !== lid) {
pids.push(f.id)
}
})
Draw.delete(pids)
}
});