dimfeld / svelte-maplibre

Svelte bindings for the MapLibre mapping library
https://svelte-maplibre.vercel.app
MIT License
283 stars 34 forks source link

Updating sourceLayer after Layer creation doesn't take effect #140

Closed dimfeld closed 3 months ago

dimfeld commented 3 months ago

First of all, thanks for this great library. It enables me as a relatively inexperience (hobbyist) developer to get a lot done with maplibre. Currently I have an issue with drawing FillLayer when i change the layer in a VectorTileSource. I have already tried many things that did not work out and I would really like to know whether I do something wrong, or the thing I want to achieve with svelte-maplibre is not possible.

I have set up a minimal example of my problem here: https://codesandbox.io/p/devbox/musing-hill-rdcwnw

  • The Map.svelte file in $lib/Map.svelte contains a maptiler Vector source. This tile database contains 3 layers of the states California, Nevada and Utah.
  • /src/routes/+page.svelte contains a basic page with 3 radio buttons. On the change of these buttons i want to grab a different layer in the tile set. Hence, when California is selected I want that layer to appear on the map, and similar for Nevada and Utah.

Among others, I have tried to fiddle with the mapInstance binding in the component and tried to use a writable store to pass the choice value, but without success. I could not find a solution in the other discussion topics either (#86 was closest related). What I did notice is that the layer does re-draw when i select a different radio button and subsequently change something in the Map.svelte file (e.g. the line-width of the lineLayerId). This is why I believe it should be possible, but I'm missing how. The sourceLayer={layer} in line 30 and 37 of Map.svelte is clearly too naive.

Thanks in advance for any help!

Originally posted by @bootje in https://github.com/dimfeld/svelte-maplibre/discussions/139

dimfeld commented 3 months ago

Looks like Layer.svelte only handles the sourceLayer prop on instantiation, and it needs to change to update the layer reactively when that prop changes.

Might work to just edit the style? https://stackoverflow.com/questions/70109527/mapbox-change-source-property

Worst case we can tear down the layer and recreate it but I'm hoping that won't be necessary.

dimfeld commented 3 months ago

Unfortunately this just doesn't seem to be supported. I recommend putting a {#key} template construct (https://svelte.dev/docs/logic-blocks#key) around any layer components that may need to change their sourceLayer at runtime.