protomaps-leaflet icon indicating copy to clipboard operation
protomaps-leaflet copied to clipboard

Change theme after map init

Open jonnitto opened this issue 1 year ago • 3 comments

I've build a map where the theme changes based on the interface settings (dark and light mode). Before, I had the function setDefaultStyle. But after v1 the function was removed. I've found nothing in the change log on how to achieve this functionality, on how to update the layer options afterwards. How can I do this?

jonnitto avatar Nov 07 '24 10:11 jonnitto

I tried some thing like this (style is one of light, dark, white, black, grayscale

layer.options.theme = style;
layer.clearLayout();
layer.rerenderTiles();

But this doesn't work

jonnitto avatar Nov 07 '24 11:11 jonnitto

My current workaround is following: (leafletLayer is used somewhere else to generate the layer variable)

import { leafletLayer } from "../../../node_modules/protomaps-leaflet/src/frontends/leaflet";
import { paintRules, labelRules } from "./node_modules/protomaps-leaflet/src/default_style/style";
import { themes } from ./node_modules/protomaps-leaflet/src/default_style/themes";

function setLayerStyle(layer, style) {
    const theme = themes[style];
    if (!theme) {
        return;
    }
    layer.options.theme = style;
    layer.paintRules = paintRules(theme);
    layer.labelRules = labelRules(theme);
    layer.backgroundColor = theme.background;
    layer.clearLayout();
    layer.rerenderTiles();
}

jonnitto avatar Nov 07 '24 11:11 jonnitto

I think that is a good workaround for now. We should provide a convenience method later for setting a style from a custom object or one of the preset theme names.

bdon avatar Nov 09 '24 01:11 bdon