-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
108 lines (94 loc) · 2.62 KB
/
index.js
File metadata and controls
108 lines (94 loc) · 2.62 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
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
import React, { useRef, useState, useEffect } from "react"
import PropTypes from "prop-types"
import mapbox from "mapbox-gl"
import * as envelope from "@turf/envelope"
export default function Map({ height, basemap, children, showControls }) {
const containerRef = useRef()
const [map, setMap] = useState(null)
useEffect(() => {
mapbox.accessToken = process.env.GATSBY_MAPBOX_TOKEN
const m = new mapbox.Map({
container: containerRef.current,
style: basemap || "mapbox://styles/covid-nasa/cm7etyf7t003s01qpfq8kec7y",
zoom: 1,
center: [0, 0],
cooperativeGestures: showControls ? true : false,
})
if (showControls) {
m.addControl(new mapbox.FullscreenControl(), "bottom-right")
m.addControl(new mapbox.NavigationControl(), "bottom-right")
}
// check if children exist
if (children.length > 0) {
// extract geojson from all objects in children
const geojsons = children.map(child => child.props.geojson)
// create a featureCollection from the geojsons
const fc = {
type: "FeatureCollection",
features: geojsons,
}
// get width
const { width } = m.getContainer().getBoundingClientRect()
// use turf envelope to calculate a bounding box that fits all boxes
if (fc.features[0]) {
const envelopBox = envelope.default(fc)
// map should show bounding boxes in the right area of the map
m.flyTo(
m.cameraForBounds(envelopBox.bbox, {
padding: { top: 200, right: 25, bottom: 25, left: width / 1.5 },
})
)
}
}
m.on("load", () => {
setMap(m)
if (process.env.NODE_ENV === "development") {
// makes map accessible in console for debugging
window.map = m
}
})
return () => {
if (map) {
map.remove()
}
}
}, [])
useEffect(() => {
if (map) {
map.resize()
}
return () => {
if (map) {
map.remove()
}
}
}, [height])
return (
<div
css={`
grid-area: 1 / 1 / 1 / 4;
height: ${height}px;
position: relative;
`}
ref={containerRef}
data-cy="mapboxgl-map"
>
{map &&
children &&
React.Children.map(children, child =>
React.cloneElement(child, {
map,
})
)}
</div>
)
}
Map.propTypes = {
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired,
basemap: PropTypes.string,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.arrayOf(PropTypes.element),
]),
showControls: PropTypes.bool,
}