refresh layers after style change

This commit is contained in:
vcoppe
2024-04-17 12:21:56 +02:00
parent ab0b425243
commit 0c97410c87
2 changed files with 54 additions and 31 deletions

View File

@@ -5,25 +5,31 @@
export let file: GPXFile;
$: if ($map) {
$map.on('load', () => {
function addGPXLayer() {
if (!$map.getSource('gpx')) {
$map.addSource('gpx', {
type: 'geojson',
data: file.toGeoJSON()
});
$map.addLayer({
id: 'gpx',
type: 'line',
source: 'gpx',
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#888',
'line-width': 8
}
});
}
$map.addLayer({
id: 'gpx',
type: 'line',
source: 'gpx',
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color': '#888',
'line-width': 8
}
});
}
$: if ($map) {
$map.on('style.load', () => {
addGPXLayer();
});
}
</script>

View File

@@ -24,6 +24,30 @@
$map.setStyle(basemaps[defaultBasemap]);
});
}
let addOverlayLayer: { [key: string]: () => void } = {};
function addOverlayLayerForId(id: string) {
return () => {
if ($map) {
if (!$map.getSource(id)) {
$map.addSource(id, overlays[id]);
}
$map.addLayer({
id,
type: overlays[id].type === 'raster' ? 'raster' : 'line',
source: id,
paint: {
...(id in opacities
? overlays[id].type === 'raster'
? { 'raster-opacity': opacities[id] }
: { 'line-opacity': opacities[id] }
: {})
}
});
}
};
}
</script>
<CustomControl class="group min-w-[29px] min-h-[29px] overflow-hidden">
@@ -43,7 +67,9 @@
name="basemaps"
onValueChange={(id) => {
if ($map) {
$map.setStyle(basemaps[id]);
$map.setStyle(basemaps[id], {
diff: false
});
}
}}
/>
@@ -55,25 +81,16 @@
name="overlays"
multiple={true}
onValueChange={(id, checked) => {
if (!addOverlayLayer.hasOwnProperty(id)) {
addOverlayLayer[id] = addOverlayLayerForId(id);
}
if ($map) {
if (checked) {
if (!$map.getSource(id)) {
$map.addSource(id, overlays[id]);
}
$map.addLayer({
id,
type: overlays[id].type === 'raster' ? 'raster' : 'line',
source: id,
paint: {
...(id in opacities
? overlays[id].type === 'raster'
? { 'raster-opacity': opacities[id] }
: { 'line-opacity': opacities[id] }
: {})
}
});
addOverlayLayer[id]();
$map.on('style.load', addOverlayLayer[id]);
} else {
$map.removeLayer(id);
$map.off('style.load', addOverlayLayer[id]);
}
}
}}