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

View File

@@ -24,6 +24,30 @@
$map.setStyle(basemaps[defaultBasemap]); $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> </script>
<CustomControl class="group min-w-[29px] min-h-[29px] overflow-hidden"> <CustomControl class="group min-w-[29px] min-h-[29px] overflow-hidden">
@@ -43,7 +67,9 @@
name="basemaps" name="basemaps"
onValueChange={(id) => { onValueChange={(id) => {
if ($map) { if ($map) {
$map.setStyle(basemaps[id]); $map.setStyle(basemaps[id], {
diff: false
});
} }
}} }}
/> />
@@ -55,25 +81,16 @@
name="overlays" name="overlays"
multiple={true} multiple={true}
onValueChange={(id, checked) => { onValueChange={(id, checked) => {
if (!addOverlayLayer.hasOwnProperty(id)) {
addOverlayLayer[id] = addOverlayLayerForId(id);
}
if ($map) { if ($map) {
if (checked) { if (checked) {
if (!$map.getSource(id)) { addOverlayLayer[id]();
$map.addSource(id, overlays[id]); $map.on('style.load', addOverlayLayer[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] }
: {})
}
});
} else { } else {
$map.removeLayer(id); $map.removeLayer(id);
$map.off('style.load', addOverlayLayer[id]);
} }
} }
}} }}