Projekt

Obecné

Profil

Stáhnout (1.67 KB) Statistiky
| Větev: | Tag: | Revize:
1
import React, { useEffect, useRef, useState } from 'react'
2
import mapboxgl, { LngLatLike, Popup } from 'mapbox-gl'
3

    
4

    
5
const coords = {
6
    lng: 7.3700,
7
    lat: 60.0400
8
}
9

    
10
// Adapted from
11
// https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/
12

    
13
// Potential wrapper could be: https://github.com/alex3165/react-mapbox-gl
14
// https://docs.mapbox.com/mapbox-gl-js/example/geojson-line/
15

    
16
// But has only 50k uses PER MONTH lol
17
const MapBoxExample = () => {
18

    
19
    const [lng, setLng] = useState(coords.lng)
20
    const [lat, setLat] = useState(coords.lat)
21
    const [zoom, setZoom] = useState(1)
22

    
23
    // TODO type
24
    const map = useRef<any>(null)
25
    const mapContainer = useRef<any>(null)
26

    
27
    // Function to add markers to the map
28
    const addMarkers = () => {
29
        for (let i = 1; i <= 10; i += 1) { //
30
            new mapboxgl.Marker()
31
                .setLngLat([i * .5 + coords.lng, i * .5 + coords.lat])
32
                .setPopup(new Popup().setHTML(`<h3>HELLO POPUP ${ i } ☀️🍕😂😅</h3>`))
33
                .addTo(map.current as mapboxgl.Map)
34
        }
35
    }
36

    
37
    useEffect(() => {
38
        if (map.current) {
39
            return
40
        }
41

    
42
        map.current = new mapboxgl.Map({
43
            container: mapContainer.current,
44
            center: [lng, lat],
45
            accessToken: process.env.REACT_APP_MAPS_API_KEY,
46
            style: 'mapbox://styles/mapbox/streets-v11',
47
            zoom: zoom
48
        })
49

    
50
        map.current.addControl(new mapboxgl.NavigationControl())
51

    
52
        addMarkers()
53
    })
54

    
55
    return (
56
        <>
57
            <h1>MapBox Example</h1>
58
            <div ref={ mapContainer } style={ { height: '400px' } }/>
59
        </>
60
    )
61
}
62

    
63
export default MapBoxExample
(2-2/3)