-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
75 lines (59 loc) · 2.06 KB
/
index.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
import React, { useRef, useEffect } from 'react'
import ReactDOM from 'react-dom'
import mapboxgl from 'mapbox-gl'
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'
import { mapboxConfig } from 'config'
import MapMarker from '../MapMarker'
import './index.css'
interface MapSelectLocationProps {
onGeolocationChange(latlog: { longitude: number; latitude: number }): void
initialGeoLocation?: { longitude: number; latitude: number }
initialZoom?: number
props?: Record<string, unknown>
}
function MapSelectLocation({
onGeolocationChange,
initialGeoLocation = mapboxConfig.initialValues.geoLocation,
initialZoom = mapboxConfig.initialValues.zoom,
...props
}: MapSelectLocationProps): JSX.Element {
const mapContainerRef = useRef<HTMLDivElement | null>(null)
const currentMarker = useRef<mapboxgl.Marker | null>(null)
useEffect(() => {
mapboxgl.accessToken = mapboxConfig.accessToken
const map = new mapboxgl.Map({
container: mapContainerRef.current || '',
style: 'mapbox://styles/mapbox/streets-v11',
center: [initialGeoLocation.longitude, initialGeoLocation.latitude],
zoom: initialZoom
})
map.addControl(
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
})
)
map.addControl(
new mapboxgl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: true
})
)
map.on('click', ({ lngLat }) => {
const { lng, lat } = lngLat
currentMarker?.current?.remove()
const markerNode = document.createElement('div')
ReactDOM.render(<MapMarker />, markerNode)
const market = new mapboxgl.Marker(markerNode)
market.setLngLat([lng, lat]).addTo(map)
currentMarker.current = market
onGeolocationChange({ longitude: lng, latitude: lat })
})
return () => map.remove()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return <div ref={mapContainerRef} className='select-location' {...props} />
}
export default MapSelectLocation