|
| 1 | +import { useCallback, useEffect, useState } from "react" |
| 2 | +import { Source, Layer, useMap } from "react-map-gl/maplibre" |
| 3 | +import turfBboxPolygon from "@turf/bbox-polygon" |
| 4 | +import turfBooleanWithin from "@turf/boolean-within" |
| 5 | + |
| 6 | +import { mapStyles } from "../../js/map" |
| 7 | + |
| 8 | +export default function Tileset({ storeStyle }) { |
| 9 | + const { map } = useMap() |
| 10 | + const [styleName, setStyleName] = useState(storeStyle) |
| 11 | + |
| 12 | + const autoset = useCallback(() => { |
| 13 | + let newStyleName = storeStyle |
| 14 | + const currentStyle = mapStyles[storeStyle] |
| 15 | + |
| 16 | + if (map && currentStyle.zoomFallbackTileset) { |
| 17 | + if (currentStyle.minZoom && currentStyle.minZoom >= map.getZoom()) |
| 18 | + newStyleName = currentStyle.zoomFallbackTileset |
| 19 | + |
| 20 | + if (currentStyle.maxZoom && currentStyle.maxZoom <= map.getZoom()) |
| 21 | + newStyleName = currentStyle.zoomFallbackTileset |
| 22 | + |
| 23 | + if (newStyleName == storeStyle && currentStyle.bounds) { |
| 24 | + const mapBounds = map.getBounds() |
| 25 | + const mapBoundsPolygon = turfBboxPolygon([ |
| 26 | + mapBounds._ne.lng, |
| 27 | + mapBounds._ne.lat, |
| 28 | + mapBounds._sw.lng, |
| 29 | + mapBounds._sw.lat, |
| 30 | + ]) |
| 31 | + |
| 32 | + const styleBoundsPolygon = turfBboxPolygon(currentStyle.bounds.flat()) |
| 33 | + if (!turfBooleanWithin(mapBoundsPolygon, styleBoundsPolygon)) |
| 34 | + newStyleName = currentStyle.zoomFallbackTileset |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + setStyleName(newStyleName) |
| 39 | + }, [map, storeStyle]) |
| 40 | + |
| 41 | + useEffect(() => { |
| 42 | + autoset() |
| 43 | + }, [autoset, storeStyle]) |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + map.on(`move`, autoset) |
| 47 | + |
| 48 | + return () => { |
| 49 | + map.off(`move`, autoset) |
| 50 | + } |
| 51 | + }, [autoset, map]) |
| 52 | + |
| 53 | + const style = mapStyles[styleName] |
| 54 | + |
| 55 | + return ( |
| 56 | + <> |
| 57 | + <Source |
| 58 | + id="tileset" |
| 59 | + type={style.type} |
| 60 | + tiles={style.tiles} |
| 61 | + tileSize={style.tileSize} |
| 62 | + /> |
| 63 | + |
| 64 | + <Layer beforeId="base" source="tileset" type={style.type} /> |
| 65 | + </> |
| 66 | + ) |
| 67 | +} |
0 commit comments