I want to add geometry dynamically into folium. However, I have difficulty understanding the behaviour.
The following code snippet generates two folium map. The left one will update dynamically while I select a different LineString or press the generate random line button. While the right one doesn’t update at all.
Moreover, the button click doesn’t refresh on the left but will refresh on the right hand side. I am quite confused.
import random
import folium
import param
from shapely.geometry import LineString
pn.extension()
class PanelFoliumMap(param.Parameterized):
# action = param.Action(lambda x:self._update_map)
lines = param.Selector([
LineString([[random.uniform(0, 180), random.uniform(-90, 90)] for _ in range(3)]),
LineString([[random.uniform(0, 180), random.uniform(-90, 90)] for _ in range(3)]),
LineString([[random.uniform(0, 180), random.uniform(-90, 90)] for _ in range(3)])
])
def __init__(self, **params):
super().__init__(**params)
self.map = folium.Map()
self.folium_pane = pn.pane.plot.Folium(self.map, sizing_mode="stretch_both", min_height=500, margin=0)
self.button = pn.widgets.Button(name='Generate random line')
self.button.on_click(self._update_map)
self.view = pn.Column(
self.param,
self.folium_pane,
self.button,
self.button.clicks,
sizing_mode="stretch_both", height=500
)
def get_polyline(self):
# lon = random.uniform(0, 180)
# lat = random.uniform(-90, 90)
# lon2 = random.uniform(0, 180)
# lat2 = random.uniform(-90, 90)
return LineString([[random.uniform(0, 180), random.uniform(-90, 90)] for _ in range(3)])
def _update_map(self, event):
folium.GeoJson(self.get_polyline()).add_to(self.map)
# folium.LayerControl().add_to(self.map)
self.folium_pane.object = self.map
@param.depends('lines')
def _udpate_map2(self):
print('_update_map2')
folium.GeoJson(self.lines).add_to(self.map)
self.folium_pane.object = self.map
return self.folium_pane
@param.depends('lines', watch=True)
def view2(self):
return self._udpate_map2()
def view3(self):
return self.button.clicks
app = PanelFoliumMap()
pn.Row(app.view, app._udpate_map2, app.view3).show()