-
-
Notifications
You must be signed in to change notification settings - Fork 937
Expand file tree
/
Copy pathMapView.tsx
More file actions
66 lines (55 loc) · 1.57 KB
/
MapView.tsx
File metadata and controls
66 lines (55 loc) · 1.57 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
import mapboxgl from 'mapbox-gl';
import React, { useEffect, useRef, useState } from 'react';
import { point } from '@turf/helpers';
import { MapViewProps } from '../../components/MapView';
import MapContext from '../MapContext';
/**
* MapView backed by Mapbox GL KS
*/
export default function MapView(
props: Pick<MapViewProps, 'styleURL' | 'children' | 'onPress'>,
) {
const mapContainerRef = useRef<HTMLDivElement>(null);
const [map, setMap] = useState<mapboxgl.Map | undefined>(undefined);
const _propsRef = useRef(props);
useEffect(() => {
_propsRef.current = props;
}, [props]);
useEffect(() => {
if (mapContainerRef.current === null) {
console.error('MapView - mapContainerRef should not be null');
return;
}
// Initialize map
const { styleURL } = props;
const _map = new mapboxgl.Map({
container: mapContainerRef.current,
style: styleURL || 'mapbox://styles/mapbox/streets-v11',
});
// Set map event listeners
_map.on('click', (e) => {
if (_propsRef.current.onPress === undefined) {
return;
}
_propsRef.current.onPress(point(e.lngLat.toArray()));
});
setMap(_map);
return () => {
_map.remove();
if (_map === map) {
setMap(undefined);
}
};
}, []);
return (
<div style={{ width: '100%', height: '100%' }} ref={mapContainerRef}>
{map && (
<div style={{ position: 'absolute' }}>
<MapContext.Provider value={{ map }}>
{props.children}
</MapContext.Provider>
</div>
)}
</div>
);
}