Draw Polygon how to call the mapbox-gl-draw Methods? #2053
-
How to call the mapbox-gl-draw API methods like (getAll, getMode, ...) using Following the Mapbox draw example I can use the draw variable to access all features that are drawn on a map. const draw = new MapboxDraw({
// ...
});
map.addControl(draw);
// ...
function updateArea(e) {
const data = draw.getAll(); // Accessing all features (data) drawn here
// ...
} However, in react-map-gl library useControl example I can not figure out how to pass ref to the DrawControl component so I can use it as something like draw.current in a similar way as I did draw in normal javascript above If anyone can help with the solution, I promise to update this polygon drawing example. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
I think I found a solution combine export const DrawControl = React.forwardRef((props: DrawControlProps, ref) => {
const drawRef = useControl<MapboxDraw>(
() => new MapboxDraw(props),
({ map }) => {
map.on("draw.create", props.onCreate);
map.on("draw.update", props.onUpdate);
map.on("draw.delete", props.onDelete);
map.on("draw.modechange", props.onModeChange);
},
({ map }) => {
map.off("draw.create", props.onCreate);
map.off("draw.update", props.onUpdate);
map.off("draw.delete", props.onDelete);
map.off("draw.modechange", props.onModeChange);
},
{
position: props.position,
}
);
React.useImperativeHandle(ref, () => drawRef, [drawRef]); // This way I exposed drawRef outside the component
return null;
}); in the component: const drawRef = React.useRef<MapboxDraw>();
const changeModeTo = (mode: DrawMode) => {
// If you programmatically invoke a function in the Draw API, any event that directly corresponds with that function will not be fired
drawRef.current?.changeMode(mode as string);
setDrawMode(mode);
};
<>
<DrawControl
ref={drawRef}
position="top-right”
displayControlsDefault={false}
controls={{
polygon: true,
trash: true,
}}
defaultMode={DEFAULT_INITIAL_MODE}
onCreate={onUpdate}
onUpdate={onUpdate}
onDelete={onDelete}
onModeChange={onModeChange}
/>
<button
style={{
position: ‘absolute’,
left: ‘20px’,
top: ‘20px’,
backgroundColor: '#ff0000’,
}}
onClick={() => changeModeTo('simple_select’)}
>
Change to Simple Select
</button>
<> @Pessimistress If this approach is correct, please, let me know and I will send a PR to update the Draw Polygon example as this is very important feature that isn’t documented anywhere. |
Beta Was this translation helpful? Give feedback.
I think I found a solution combine
forwardRef
anduseImperativeHandle
to solve: