forked from valhalla/web-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalhalla-layers-toggle.tsx
More file actions
82 lines (70 loc) · 2.03 KB
/
valhalla-layers-toggle.tsx
File metadata and controls
82 lines (70 loc) · 2.03 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
import { useState, useEffect } from 'react';
import { useMap } from 'react-map-gl/maplibre';
import { useCommonStore } from '@/stores/common-store';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import {
VALHALLA_SOURCE_ID,
VALHALLA_LAYERS,
getValhallaSourceSpec,
} from './valhalla-layers';
export const ValhallaLayersToggle = () => {
const { mainMap } = useMap();
const mapReady = useCommonStore((state) => state.mapReady);
const [enabled, setEnabled] = useState(false);
useEffect(() => {
if (!mainMap) return;
const map = mainMap.getMap();
const handleStyleData = () => {
const hasSource = !!map.getSource(VALHALLA_SOURCE_ID);
setEnabled(hasSource);
};
map.on('styledata', handleStyleData);
return () => {
map.off('styledata', handleStyleData);
};
}, [mainMap]);
const handleToggle = (checked: boolean) => {
if (!mainMap || !mapReady) return;
const map = mainMap.getMap();
setEnabled(checked);
if (checked) {
if (!map.getSource(VALHALLA_SOURCE_ID)) {
map.addSource(VALHALLA_SOURCE_ID, getValhallaSourceSpec());
}
for (const layer of VALHALLA_LAYERS) {
if (!map.getLayer(layer.id)) {
map.addLayer(layer);
}
}
} else {
for (const layer of VALHALLA_LAYERS) {
if (map.getLayer(layer.id)) {
map.removeLayer(layer.id);
}
}
if (map.getSource(VALHALLA_SOURCE_ID)) {
map.removeSource(VALHALLA_SOURCE_ID);
}
}
};
if (!mapReady) {
return null;
}
return (
<div className="flex items-center justify-between gap-3 p-3 bg-muted/50 rounded-md">
<Label
htmlFor="valhalla-layers-toggle"
className="text-sm font-medium cursor-pointer"
>
Append Valhalla layers
</Label>
<Switch
id="valhalla-layers-toggle"
checked={enabled}
onCheckedChange={handleToggle}
className="data-[state=checked]:bg-green-600"
/>
</div>
);
};