style-switcher
style-switcher copied to clipboard
Question.. Switch styles and maintain state?
Hi, I've recently implemented a very similar component myself, before discovering this one!
The main difference being that I needed to maintain sources/layers/feature state in-between style switches. This is semi-baked into my version but I feel like this could be a useful feature for others too...
My question is whether or not you'd accept a PR for this feature?
Hi. I didnt understand what you meant. But feel free to create a PR. 👍
@el Let me explain... When you call setStyle()
it does not copy/keey any sources/layers etc. that you may have added manually. For example I might set the initial style as streets, then add 5 custom layers, but if I then change the style to satellite, all of those 5 layers/sources will be lost. What I'm proposing is that there's a way to say "copy these sources/layers and their features state" so that when you switch styles any custom sources/layers etc. added are not lost. Does that make sense?
This makes sense, currently, the user of the library is required to handle that themselves.
Please feel free to create a PR.
I managed to fix this by passing a onChange
function to the plugin that sets a variable called forceReload
to true
. Then in the map.on('styledata', ()=>{});
re-add the previously added layers/styles when the 'forceReload' is set to true
. Note: the styledata
event is called multiple times, so i directly reset the forceReload
variable again after the reload function is called!
Probably not the best solution, but hey: 'if it works it ain't stupid' ;)
I've created a fork with a new option for "preserveLayers":
https://github.com/chriszrc/style-switcher
It automatically retains all user-added layers/sources while switching between road/satellite/etc styles. I think I've covered all the edge cases, but if you try it out and find any problems let me know and then maybe I will create a pull request-
@chriszrc Thanks for initiative, it's great, however, I'm experiencing a strange behaviour. When I switch styles, it flashes to the new one and goes back to the original. Any ideas?
@vcardins hard to say, can you recreate the problem in a codesandbox?
@chriszrc Thanks for the quick response, I'm going to try and get back to you. I assume it worked well for you, right?
@chriszrc Never mind, it's something related to my custom code. 👍🏽
@chriszrc You solution works perfectly, many thanks. @el Maybe you could incorporate it into the repo and publish a new npm version, it's very useful.
PS: @chriszrc Maybe you could remove the existing console.log.
@vcardins I removed it-
I dont see a PR for that. I can take a look if @vcardins creates a PR.
@el I wanted people to actually try it before I made the pr, but now I've created it- https://github.com/el/style-switcher/pull/27