-
Notifications
You must be signed in to change notification settings - Fork 5
/
MapView.web.tsx
86 lines (76 loc) · 2.75 KB
/
MapView.web.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
import Map, {MapRef, Marker} from 'react-map-gl';
import {forwardRef, useCallback, useEffect, useImperativeHandle, useState} from 'react';
import {View} from 'react-native';
import {MapViewHandle, MapViewProps} from './MapViewTypes';
import Utils from './utils';
import 'mapbox-gl/dist/mapbox-gl.css';
import Direction from './Direction';
import {DEFAULT_INITIAL_STATE} from './CONST';
const MapView = forwardRef<MapViewHandle, MapViewProps>(function MapView(
{accessToken, waypoints, style, mapPadding, directionCoordinates, initialState = DEFAULT_INITIAL_STATE, styleURL, directionStyle},
ref,
) {
const [mapRef, setMapRef] = useState<MapRef | null>(null);
const setRef = useCallback((newRef: MapRef | null) => setMapRef(newRef), []);
useEffect(() => {
if (!waypoints || waypoints.length === 0) {
return;
}
if (!mapRef) {
return;
}
if (waypoints.length === 1) {
mapRef.flyTo({
center: waypoints[0].coordinate,
zoom: 15,
});
return;
}
const map = mapRef.getMap();
const {northEast, southWest} = Utils.getBounds(waypoints.map((waypoint) => waypoint.coordinate));
map.fitBounds([northEast, southWest], {padding: mapPadding});
}, [waypoints, mapRef]);
useImperativeHandle(
ref,
() => ({
flyTo: (location: [number, number], animationDuration?: number) =>
mapRef?.flyTo({
center: location,
duration: animationDuration,
}),
}),
[],
);
return (
<View style={style}>
<Map
ref={setRef}
mapboxAccessToken={accessToken}
initialViewState={{
longitude: initialState?.location[0],
latitude: initialState?.location[1],
zoom: initialState?.zoom,
}}
mapStyle={styleURL}
>
{waypoints &&
waypoints.map(({coordinate, markerComponent: MarkerComponent}) => (
<Marker
key={`${coordinate[0]},${coordinate[1]}`}
longitude={coordinate[0]}
latitude={coordinate[1]}
>
<MarkerComponent />
</Marker>
))}
{directionCoordinates && (
<Direction
coordinates={directionCoordinates}
directionStyle={directionStyle}
/>
)}
</Map>
</View>
);
});
export default MapView;