-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathUseBackgroundLayer.tsx
More file actions
59 lines (55 loc) · 2.16 KB
/
UseBackgroundLayer.tsx
File metadata and controls
59 lines (55 loc) · 2.16 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
import { Feature, Map } from 'ol'
import { useEffect } from 'react'
import { RasterStyle, StyleOption } from '@/stores/MapOptionsStore'
import TileLayer from 'ol/layer/Tile'
import { XYZ } from 'ol/source'
import { applyBackground, applyStyle } from 'ol-mapbox-style'
import VectorTileLayer from 'ol/layer/VectorTile'
export default function useBackgroundLayer(map: Map, styleOption: StyleOption) {
useEffect(() => {
removeCurrentBackgroundLayers(map)
addNewBackgroundLayers(map, styleOption)
setupMouseInteraction(map)
return () => {
removeCurrentBackgroundLayers(map)
}
}, [map, styleOption])
}
function removeCurrentBackgroundLayers(map: Map) {
const backgroundLayers = map
.getLayers()
.getArray()
.filter(l => {
// vector layers added via olms#addLayers have the mapbox-source key
return l.get('mapbox-source') || l.get('background-raster-layer')
})
backgroundLayers.forEach(l => map.removeLayer(l))
}
function addNewBackgroundLayers(map: Map, styleOption: StyleOption) {
if (styleOption.type === 'vector') {
const layer = new VectorTileLayer({ declutter: true })
applyBackground(layer, styleOption.url)
applyStyle(layer, styleOption.url)
map.addLayer(layer)
} else {
const rasterStyle = styleOption as RasterStyle
const tileLayer = new TileLayer({
source: new XYZ({
urls: rasterStyle.url,
maxZoom: rasterStyle.maxZoom,
attributions: [rasterStyle.attribution],
tilePixelRatio: rasterStyle.tilePixelRatio,
}),
})
tileLayer.set('background-raster-layer', true)
map.addLayer(tileLayer)
}
}
function setupMouseInteraction(map: Map) {
map.on('pointermove', function (evt) {
const features = map.getFeaturesAtPixel(evt.pixel)
// features can also contain 'RenderFeatures' for vector tiles, but in this case the cursor should not change
const atFeature = features.some(f => f instanceof Feature)
map.getTargetElement().style.cursor = atFeature ? 'pointer' : 'default'
})
}