-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapScreen.tsx
More file actions
230 lines (215 loc) · 6.74 KB
/
MapScreen.tsx
File metadata and controls
230 lines (215 loc) · 6.74 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import {
Camera,
type CameraRef,
LocationManager,
Map as MapLibreMap,
Marker,
UserLocation,
useCurrentPosition,
type ViewStateChangeEvent,
} from '@maplibre/maplibre-react-native';
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import type {NativeSyntheticEvent} from 'react-native';
import {
ActivityIndicator,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {
type ElementsQuery,
type ElementsQueryVariables,
useElementsQuery,
} from '../graphql/__generated__/types';
type ElementWithLocation = ElementsQuery['elements'][number];
const MAP_STYLE = 'https://tiles.openfreemap.org/styles/liberty';
const USER_ZOOM = 14;
// Show the recenter button once the viewport center drifts more than this
// fraction of the visible span away from the user in either axis.
const OFF_CENTER_THRESHOLD = 0.2;
// Vertical clearance above the device safe area so the recenter button sits
// above the app's bottom "signed in as…" bar in App.tsx. Keep in sync if that
// bar's height changes.
const BOTTOM_BAR_CLEARANCE = 64;
export function MapScreen() {
const cameraRef = useRef<CameraRef>(null);
const hasCenteredRef = useRef(false);
const [permissionGranted, setPermissionGranted] = useState(false);
const safeAreaInsets = useSafeAreaInsets();
useEffect(() => {
let cancelled = false;
(async () => {
const granted = await LocationManager.requestPermissions();
if (!cancelled && granted) {
setPermissionGranted(true);
}
})();
return () => {
cancelled = true;
};
}, []);
const position = useCurrentPosition({enabled: permissionGranted});
const positionRef = useRef(position);
positionRef.current = position;
const flyToUser = useCallback(() => {
const pos = positionRef.current;
if (!pos) return;
cameraRef.current?.flyTo({
center: [pos.coords.longitude, pos.coords.latitude],
zoom: USER_ZOOM,
duration: 1500,
});
}, []);
useEffect(() => {
if (hasCenteredRef.current || !position) return;
hasCenteredRef.current = true;
flyToUser();
}, [position, flyToUser]);
const [bounds, setBounds] = useState<ElementsQueryVariables['bounds']>();
const [isCenteredOnUser, setIsCenteredOnUser] = useState(true);
const onRegionDidChange = useCallback(
(event: NativeSyntheticEvent<ViewStateChangeEvent>) => {
// Skip viewport events until we've flown to the user's location, so
// we don't fetch the entire world at the initial zoom-1 framing.
if (!hasCenteredRef.current) return;
const [west, south, east, north] = event.nativeEvent.bounds;
setBounds({left: west, bottom: south, right: east, top: north});
const pos = positionRef.current;
if (!pos) return;
const [centerLng, centerLat] = event.nativeEvent.center;
const spanLng = east - west;
const spanLat = north - south;
const offLng = Math.abs(centerLng - pos.coords.longitude) / spanLng;
const offLat = Math.abs(centerLat - pos.coords.latitude) / spanLat;
setIsCenteredOnUser(
offLng <= OFF_CENTER_THRESHOLD && offLat <= OFF_CENTER_THRESHOLD,
);
},
[],
);
const {data} = useElementsQuery({
skip: !bounds,
variables: bounds ? {bounds} : undefined,
});
// Accumulate elements across viewport fetches so pins persist while a new
// search is in flight. Fine for our small per-user dataset; revisit if we
// ever need eviction or to reflect server-side deletes.
const [elementsById, setElementsById] = useState<
ReadonlyMap<string, ElementWithLocation>
>(new Map());
useEffect(() => {
if (!data?.elements) return;
setElementsById(prev => {
const next = new Map(prev);
for (const el of data.elements) next.set(el.id, el);
return next;
});
}, [data?.elements]);
// Only render markers whose location falls inside the last-known viewport.
// <Marker> is a native View — rendering offscreen ones still costs layout
// and reprojection on every camera frame, so we cull client-side.
const visibleElements = useMemo(() => {
if (!bounds) return [];
const {left, right, bottom, top} = bounds;
return Array.from(elementsById.values()).filter(el => {
if (!el.location) return false;
const {longitude: lng, latitude: lat} = el.location;
return lng >= left && lng <= right && lat >= bottom && lat <= top;
});
}, [elementsById, bounds]);
return (
<View style={styles.container}>
<MapLibreMap
mapStyle={MAP_STYLE}
style={styles.map}
onRegionDidChange={onRegionDidChange}>
<Camera ref={cameraRef} initialViewState={{center: [0, 20], zoom: 1}} />
<UserLocation animated accuracy />
{visibleElements.map(el =>
el.location ? (
<Marker
key={el.id}
id={el.id}
lngLat={[el.location.longitude, el.location.latitude]}>
<View style={styles.pin}>
{el.icon ? <Text style={styles.pinIcon}>{el.icon}</Text> : null}
</View>
</Marker>
) : null,
)}
</MapLibreMap>
{!position ? (
<View pointerEvents="none" style={styles.loadingOverlay}>
<ActivityIndicator size="large" color="#1d6fe0" />
</View>
) : null}
{position && !isCenteredOnUser ? (
<TouchableOpacity
accessibilityLabel="Recenter map on your location"
accessibilityRole="button"
onPress={flyToUser}
style={[
styles.recenterButton,
{bottom: safeAreaInsets.bottom + BOTTOM_BAR_CLEARANCE},
]}>
<Text style={styles.recenterIcon}>◎</Text>
</TouchableOpacity>
) : null}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
map: {
flex: 1,
},
pin: {
width: 36,
height: 36,
borderRadius: 18,
backgroundColor: '#1d6fe0',
borderWidth: 2,
borderColor: '#ffffff',
alignItems: 'center',
justifyContent: 'center',
},
pinIcon: {
fontSize: 18,
lineHeight: 22,
textAlign: 'center',
},
loadingOverlay: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(255,255,255,0.6)',
},
recenterButton: {
position: 'absolute',
right: 16,
width: 48,
height: 48,
borderRadius: 24,
backgroundColor: '#ffffff',
alignItems: 'center',
justifyContent: 'center',
shadowColor: '#000',
shadowOpacity: 0.2,
shadowRadius: 4,
shadowOffset: {width: 0, height: 2},
elevation: 4,
},
recenterIcon: {
fontSize: 24,
lineHeight: 28,
color: '#1d6fe0',
},
});