Py.Cafe

lopezv.oliver/

solara-ipyleaflet-add-remove-layers-demo

Solara Interactive Map Visualizer

DocsPricing
  • app.py
  • components.py
  • requirements.txt
  • utils.py
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Try adding layers (and then removing them):

e.g., 

https://tile.openstreetmap.org/{z}/{x}/{y}.png
https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png
"""
import solara
import ipyleaflet
from components import LayersControlMockup
import ipyleaflet
center = solara.reactive((0,0))
zoom = solara.reactive(5)

meta_layer_names = solara.reactive([])
meta_layer_defs = solara.reactive({})

@solara.component
def Page():
    layers_to_add = {key: meta_layer_defs.value[key] 
                     for key in meta_layer_names.value if key in meta_layer_defs.value}
    
    layers = [
        ipyleaflet.TileLayer.element(
            url = layer['url'].value if hasattr(layer['url'],'value') else layer['url'],
            opacity = layer['opacity'].value,
            visible = layer['visible'].value,
        )
        for _,layer in layers_to_add.items()
    ]

    with solara.Columns([1,2]):
        LayersControlMockup(
            layers_to_add,
            layer_names = meta_layer_names,
            meta_layers=meta_layer_defs,
        )

        # 👀 We need to wrap the Map in a Column with 
        # isolation:isolate
        # see: https://developer.mozilla.org/en-US/docs/Web/CSS/isolation
        # to prevent the TileLayers from interfering with the global
        # z-index stacking of the modal. 
        with solara.Column(style={"isolation": "isolate"}):
            ipyleaflet.Map.element(
                scroll_wheel_zoom = True,
                zoom = zoom.value,
                on_zoom = zoom.set,
                center = center.value,
                on_center = center.set,
                layers = layers,
            )