-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathuseFeatureDraw.tsx
More file actions
97 lines (85 loc) · 2.16 KB
/
useFeatureDraw.tsx
File metadata and controls
97 lines (85 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import useMap from './useMap';
import { useEffect, useRef, useState } from 'react';
import { TerraDraw } from 'terra-draw';
import { TerraDrawMapLibreGLAdapter } from 'terra-draw-maplibre-gl-adapter';
import { TerraDrawBaseDrawMode } from 'terra-draw/dist/modes/base.mode';
export interface useFeatureDrawProps {
/**
* Id of the target MapLibre instance in mapContext
*/
mapId?: string;
/**
* Id of an existing layer in the mapLibre instance to help specify the layer order
* This layer will be visually beneath the layer with the "insertBeforeLayer" id.
*/
insertBeforeLayer?: string;
/**
* drawing mode
*/
mode: TerraDrawBaseDrawMode<any>[];
}
const useFeatureDraw = (props: useFeatureDrawProps) => {
const draw = useRef<TerraDraw | null>(null);
const [isDrawing, setIsDrawing] = useState<boolean>(false);
const mapHook = useMap({
mapId: props.mapId,
waitForLayer: props.insertBeforeLayer,
});
const cleanup = () => {
if (draw.current) {
draw.current.stop();
draw.current = null;
}
setIsDrawing(false);
};
const initializeDraw = () => {
if (!mapHook.map) return;
cleanup();
draw.current = new TerraDraw({
adapter: new TerraDrawMapLibreGLAdapter(mapHook.map),
modes: props.mode,
});
};
useEffect(() => {
initializeDraw();
return () => {
cleanup();
};
}, [mapHook.map, props.mode]);
const setMode = (mode: string): void => {
if (!draw.current) return;
try {
draw.current.setMode(mode);
setIsDrawing(mode !== 'select');
} catch (error) {
console.error('Error setting mode:', error);
setIsDrawing(false);
}
};
const startDrawing = (mode: string) => {
if (!draw.current) initializeDraw();
if (!draw.current) return;
try {
if (!draw.current.enabled) {
draw.current.start();
}
setMode(mode);
} catch (error) {
console.error('Error starting drawing:', error);
cleanup();
}
};
const stopDrawing = (): void => {
if (draw.current) {
console.log('select mode');
setMode('select');
}
};
const clearDrawing = (): void => {
if (draw.current) {
draw.current.clear();
}
};
return { startDrawing, stopDrawing, clearDrawing, isDrawing };
};
export default useFeatureDraw;