Is there a draw event for a single click of a feature in mapbox-gl-draw?

671 views Asked by At

I'm playing around with react-map-gl and mapbox-gl-draw to draw polygons on to my map

I'm wondering if there is a better way to get the details of a selected feature on click, rather than using the draw.selectionchange event? This event handles clicks of multiple features, and also fires when you click OFF a feature, which I don't want. I just want to handle the click of a single feature.

The documentation I'm following: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md#drawselectionchange

The example on github that I am building from: https://github.com/visgl/react-map-gl/tree/7.0-release/examples/draw-polygon

1

There are 1 answers

0
tan On

You can use the click event of the map (not the draw plugin)

Listen the event:

map.current.on("click", handleClick);

This will return an object with point property, you can use the point to get the feature if any at that point by using method from draw plugin getFeatureIdsAt(point):

Then handle it

const handleClick = (event: MapMouseEvent) => {
  const featureIds = draw.getFeatureIdsAt(event.point);
  const feature = draw.get(featureIds[0]);
};

Docs: https://github.com/mapbox/mapbox-gl-draw/blob/main/docs/API.md#getfeatureidsatpoint--x-number-y-number--arraystring