Reputation: 780
I like getting a popup when I click on the map. The popup includes a plot that I get based on the coordinates of the click. In the code below I used Folium to manually do this:
import folium
import pandas as pd
import altair as alt
center = [46.3014, -123.7390]
# Some random data that I like to plot in the popup.
data = pd.DataFrame({'x': ['A', 'B', 'C', 'D', 'E'],
'y': [5, 3, 6, 7, 2]})
chart = alt.Chart(data).mark_bar().encode(
x='x',
y='y')
m = folium.Map(location=center, zoom_start=13, tiles="Stamen Terrain")
folium.Marker(
location=center,
popup=folium.Popup(max_width=450).add_child(
folium.VegaLite(chart, width=450, height=250)
),
).add_to(m)
m
Note that the barplot is just an example. All I need is to get the center coordinate when I click the map so that I can use them for generating the actual plot that goes into the popup.
I know Folium has a ClickForMarker
which returns the coordinate but to my understanding, there is no way to output coordinates to a variable. On the other hand, I cannot show any plot in the ClickForMarker
as in folium.Marker
, so this option doesn't help.
I decided to get the coordinates using ipyleaflet. The best I could find is as follow (from here):
from ipyleaflet import Map, basemaps, basemap_to_tiles, Marker
from ipywidgets import Label
import ipywidgets as widgets
from ipyleaflet import WidgetControl
m1 = Map(
layers=(basemap_to_tiles(basemaps.Esri.WorldGrayCanvas), ),
center=(center),
zoom=13
)
output_widget = widgets.Output(layout={'border': '1px solid black'})
output_control = WidgetControl(widget=output_widget, position='bottomright')
m1.add_control(output_control)
def handle_interaction(**kwargs):
latlon = kwargs.get('coordinates')
if kwargs.get('type') == 'click':
Map.default_style = {'cursor': 'wait'}
with output_widget:
output_widget.clear_output()
print(latlon)
Map.default_style = {'cursor': 'pointer'}
m1.on_interaction(handle_interaction)
m1
This one returns the coordinates (lower right) but it has two issues: firstly, I don't know how to save the coordinates in a variable that I can use later, and secondly, I cannot move the map since when I click and hold the mouse to move the map, it only returns the coordinates.
So I just wonder how can I combine ipyleaflet and Folium to get click driven pop up which includes plot? Or is there a better way to do all these? Thanks
Upvotes: 0
Views: 1452