-
Notifications
You must be signed in to change notification settings - Fork 3k
/
MapView.tsx
275 lines (254 loc) · 12.3 KB
/
MapView.tsx
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import {useFocusEffect, useNavigation} from '@react-navigation/native';
import type {MapState} from '@rnmapbox/maps';
import Mapbox, {MarkerView, setAccessToken} from '@rnmapbox/maps';
import {forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
import {View} from 'react-native';
import {withOnyx} from 'react-native-onyx';
import Icon from '@components/Icon';
import * as Expensicons from '@components/Icon/Expensicons';
import {PressableWithoutFeedback} from '@components/Pressable';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
import * as UserLocation from '@libs/actions/UserLocation';
import compose from '@libs/compose';
import getCurrentPosition from '@libs/getCurrentPosition';
import type {GeolocationErrorCallback} from '@libs/getCurrentPosition/getCurrentPosition.types';
import {GeolocationErrorCode} from '@libs/getCurrentPosition/getCurrentPosition.types';
import colors from '@styles/theme/colors';
import variables from '@styles/variables';
import CONST from '@src/CONST';
import useLocalize from '@src/hooks/useLocalize';
import useNetwork from '@src/hooks/useNetwork';
import ONYXKEYS from '@src/ONYXKEYS';
import Direction from './Direction';
import type {MapViewHandle} from './MapViewTypes';
import PendingMapView from './PendingMapView';
import responder from './responder';
import type {ComponentProps, MapViewOnyxProps} from './types';
import utils from './utils';
const MapView = forwardRef<MapViewHandle, ComponentProps>(
({accessToken, style, mapPadding, userLocation: cachedUserLocation, styleURL, pitchEnabled, initialState, waypoints, directionCoordinates, onMapReady, interactive = true}, ref) => {
const navigation = useNavigation();
const {isOffline} = useNetwork();
const {translate} = useLocalize();
const styles = useThemeStyles();
const theme = useTheme();
const cameraRef = useRef<Mapbox.Camera>(null);
const [isIdle, setIsIdle] = useState(false);
const initialLocation = useMemo(() => initialState && {longitude: initialState.location[0], latitude: initialState.location[1]}, [initialState]);
const [currentPosition, setCurrentPosition] = useState(cachedUserLocation ?? initialLocation);
const [userInteractedWithMap, setUserInteractedWithMap] = useState(false);
const shouldInitializeCurrentPosition = useRef(true);
// Determines if map can be panned to user's detected
// location without bothering the user. It will return
// false if user has already started dragging the map or
// if there are one or more waypoints present.
const shouldPanMapToCurrentPosition = useCallback(() => !userInteractedWithMap && (!waypoints || waypoints.length === 0), [userInteractedWithMap, waypoints]);
const setCurrentPositionToInitialState: GeolocationErrorCallback = useCallback(
(error) => {
if (error?.code !== GeolocationErrorCode.PERMISSION_DENIED || !initialLocation) {
return;
}
UserLocation.clearUserLocation();
setCurrentPosition(initialLocation);
},
[initialLocation],
);
useFocusEffect(
useCallback(() => {
if (isOffline) {
return;
}
if (!shouldInitializeCurrentPosition.current) {
return;
}
shouldInitializeCurrentPosition.current = false;
if (!shouldPanMapToCurrentPosition()) {
setCurrentPositionToInitialState();
return;
}
getCurrentPosition((params) => {
const currentCoords = {longitude: params.coords.longitude, latitude: params.coords.latitude};
setCurrentPosition(currentCoords);
UserLocation.setUserLocation(currentCoords);
}, setCurrentPositionToInitialState);
}, [isOffline, shouldPanMapToCurrentPosition, setCurrentPositionToInitialState]),
);
useEffect(() => {
if (!currentPosition || !cameraRef.current) {
return;
}
if (!shouldPanMapToCurrentPosition()) {
return;
}
cameraRef.current.setCamera({
zoomLevel: CONST.MAPBOX.DEFAULT_ZOOM,
animationDuration: 1500,
centerCoordinate: [currentPosition.longitude, currentPosition.latitude],
});
}, [currentPosition, shouldPanMapToCurrentPosition]);
useImperativeHandle(
ref,
() => ({
flyTo: (location: [number, number], zoomLevel: number = CONST.MAPBOX.DEFAULT_ZOOM, animationDuration?: number) =>
cameraRef.current?.setCamera({zoomLevel, centerCoordinate: location, animationDuration}),
fitBounds: (northEast: [number, number], southWest: [number, number], paddingConfig?: number | number[] | undefined, animationDuration?: number | undefined) =>
cameraRef.current?.fitBounds(northEast, southWest, paddingConfig, animationDuration),
}),
[],
);
// When the page loses focus, we temporarily set the "idled" state to false.
// When the page regains focus, the onIdled method of the map will set the actual "idled" state,
// which in turn triggers the callback.
useFocusEffect(
useCallback(() => {
if (!waypoints || waypoints.length === 0 || !isIdle) {
return;
}
if (waypoints.length === 1) {
cameraRef.current?.setCamera({
zoomLevel: CONST.MAPBOX.SINGLE_MARKER_ZOOM,
animationDuration: 1500,
centerCoordinate: waypoints[0].coordinate,
});
} else {
const {southWest, northEast} = utils.getBounds(
waypoints.map((waypoint) => waypoint.coordinate),
directionCoordinates,
);
cameraRef.current?.fitBounds(northEast, southWest, mapPadding, 1000);
}
}, [mapPadding, waypoints, isIdle, directionCoordinates]),
);
useEffect(() => {
const unsubscribe = navigation.addListener('blur', () => {
setIsIdle(false);
});
return unsubscribe;
}, [navigation]);
useEffect(() => {
setAccessToken(accessToken);
}, [accessToken]);
const setMapIdle = (e: MapState) => {
if (e.gestures.isGestureActive) {
return;
}
setIsIdle(true);
if (onMapReady) {
onMapReady();
}
};
const centerMap = useCallback(() => {
if (directionCoordinates && directionCoordinates.length > 1) {
const {southWest, northEast} = utils.getBounds(waypoints?.map((waypoint) => waypoint.coordinate) ?? [], directionCoordinates);
cameraRef.current?.fitBounds(southWest, northEast, mapPadding, CONST.MAPBOX.ANIMATION_DURATION_ON_CENTER_ME);
return;
}
cameraRef?.current?.setCamera({
heading: 0,
centerCoordinate: [currentPosition?.longitude ?? 0, currentPosition?.latitude ?? 0],
animationDuration: CONST.MAPBOX.ANIMATION_DURATION_ON_CENTER_ME,
zoomLevel: CONST.MAPBOX.SINGLE_MARKER_ZOOM,
});
}, [directionCoordinates, currentPosition, mapPadding, waypoints]);
const centerCoordinate = currentPosition ? [currentPosition.longitude, currentPosition.latitude] : initialState?.location;
return !isOffline && Boolean(accessToken) && Boolean(currentPosition) ? (
<View style={[style, !interactive ? styles.pointerEventsNone : {}]}>
<Mapbox.MapView
style={{flex: 1}}
styleURL={styleURL}
onMapIdle={setMapIdle}
onTouchStart={() => setUserInteractedWithMap(true)}
pitchEnabled={pitchEnabled}
attributionPosition={{...styles.r2, ...styles.b2}}
scaleBarEnabled={false}
logoPosition={{...styles.l2, ...styles.b2}}
// eslint-disable-next-line react/jsx-props-no-spreading
{...responder.panHandlers}
>
<Mapbox.Camera
ref={cameraRef}
defaultSettings={{
centerCoordinate,
zoomLevel: initialState?.zoom,
}}
// Include centerCoordinate here as well to address the issue of incorrect coordinates
// displayed after the first render when the app's storage is cleared.
centerCoordinate={centerCoordinate}
/>
<Mapbox.ShapeSource
id="user-location"
shape={{
type: 'FeatureCollection',
features: [
{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [currentPosition?.longitude ?? 0, currentPosition?.latitude ?? 0],
},
properties: {},
},
],
}}
>
<Mapbox.CircleLayer
id="user-location-layer"
sourceID="user-location"
style={{
circleColor: colors.blue400,
circleRadius: 8,
}}
/>
</Mapbox.ShapeSource>
{waypoints?.map(({coordinate, markerComponent, id}) => {
const MarkerComponent = markerComponent;
if (utils.areSameCoordinate([coordinate[0], coordinate[1]], [currentPosition?.longitude ?? 0, currentPosition?.latitude ?? 0])) {
return null;
}
return (
<MarkerView
id={id}
key={id}
coordinate={coordinate}
>
<MarkerComponent />
</MarkerView>
);
})}
{directionCoordinates && <Direction coordinates={directionCoordinates} />}
</Mapbox.MapView>
<View style={[styles.pAbsolute, styles.p5, styles.t0, styles.r0, {zIndex: 1}]}>
<PressableWithoutFeedback
accessibilityRole={CONST.ROLE.BUTTON}
onPress={centerMap}
accessibilityLabel={translate('common.center')}
>
<View style={styles.primaryMediumIcon}>
<Icon
width={variables.iconSizeNormal}
height={variables.iconSizeNormal}
src={Expensicons.Crosshair}
fill={theme.icon}
/>
</View>
</PressableWithoutFeedback>
</View>
</View>
) : (
<PendingMapView
title={translate('distance.mapPending.title')}
subtitle={isOffline ? translate('distance.mapPending.subtitle') : translate('distance.mapPending.onlineSubtitle')}
style={styles.mapEditView}
/>
);
},
);
export default compose(
withOnyx<ComponentProps, MapViewOnyxProps>({
userLocation: {
key: ONYXKEYS.USER_LOCATION,
},
}),
memo,
)(MapView);