7 - Interaction¶
These builders wire the map to the viewer. Most need a live kernel/server to round-trip a gesture back to Python - in a saved page they build the streams but fire nothing - so the cells construct the wiring and show the map; run the notebook to interact.
hover- tooltips on the glyphs.on_tap/on_select/on_reset/on_resize- call back on a click, a box/lasso/index selection, a reset, or a canvas resize.draw- sketch a box/polygon/point/freehand area, or edit existing geometry; read it back withdrawn_geometries.annotate- an editable attribute table over a drawn layer.cross_filter- brush one layer and filter the others.
Setup and data - the Heidelberg bird observations and the population raster.
import warnings
warnings.filterwarnings("ignore") # deliberately silence all warnings to keep the rendered docs clean
import io
from pathlib import Path
import holoviews as hv
import matplotlib.pyplot as plt
from IPython.display import Image
hv.extension("bokeh", "matplotlib") # Bokeh = interactive (the default); matplotlib only for barbs / projection
# This notebook lives in docs/examples/interactive/guide/, so the bundled sample data at the repo-root
# examples/data/ is four levels up. The kernel's working directory is always the notebook's own folder
# (true for nbval, nbconvert and JupyterLab alike), so one clean relative path is all that is needed.
DATA = Path("../../../../examples/data")
from digitalearth.interactive import InteractiveMap
from pyramids.dataset import Dataset
def show(m, static=False):
"""Return the **live, interactive Bokeh map** - pan, zoom, hover, and the toolbar are all real.
Run the notebook (Run All / Shift-Enter), or open it in a trusted viewer, to see the maps draw; a saved
.ipynb only shows them once a kernel executes their JavaScript. A few layers have no Bokeh glyph
(``projection``, ``streamlines``, wind ``barbs``) and are drawn by matplotlib; for those pass
``static=True`` (projected maps switch automatically) to embed a PNG instead.
"""
if static or getattr(m, "_projection", None) is not None:
fig = hv.render(m.render(), backend="matplotlib")
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=110, bbox_inches="tight")
plt.close(fig)
return Image(data=buf.getvalue())
return m.render()
import geopandas as gpd
import holoviews as hv
import numpy as np
birds = gpd.read_file(str(DATA / "heidelberg_birds_2023.geojson"))
birds["log_uncertainty"] = np.log10(birds["uncertainty_m"].clip(lower=1.0))
pop = Dataset.read_file(str(DATA / "germany_pop_2020_1km.tif"))
print("birds:", len(birds))
birds: 3000
hover - tooltips¶
hover attaches a tooltip reading named columns off the glyph.
m = InteractiveMap(crs=4326, title="hover the observations")
m.points(birds, column="log_uncertainty", size=6, cmap="viridis").colorbar()
m.hover(tooltips=[("uncertainty (m)", "@uncertainty_m")])
show(m)
on_select - box / lasso / index selection¶
on_select wires a selection stream to a callback and returns the driven DynamicMap.
m = InteractiveMap(crs=4326)
m.points(birds, column="log_uncertainty", size=6, cmap="viridis")
dmap = m.on_select(lambda bounds: hv.Points([]), kind="box")
print("selection streams:", [type(s).__name__ for s in dmap.streams])
show(m)
selection streams: ['BoundsXY']
on_tap, on_reset, on_resize¶
A click (on_tap), the Bokeh reset tool (on_reset) and a browser resize (on_resize, a PlotSize stream).
m = InteractiveMap(crs=4326)
m.points(birds, size=4, color="black")
for name, d in [
("on_tap", m.on_tap(lambda x, y: hv.Points([]))),
("on_reset", m.on_reset(lambda resetting: hv.Points([]))),
("on_resize", m.on_resize(lambda width, height, scale: hv.Points([]))),
]:
print(f"{name:10s} ->", [type(s).__name__ for s in d.streams])
on_tap -> ['Tap'] on_reset -> ['PlotReset'] on_resize -> ['PlotSize']
draw - sketch or edit geometry¶
draw adds a draw tool: "box", "poly", "point", "freehand" to sketch, or "poly-edit" / "curve-edit" to move vertices. Read it back with drawn_geometries.
m = InteractiveMap(crs=pop.epsg, title="draw a box, then edit a polygon")
m.field(pop, cmap="inferno").draw("box").draw("poly-edit")
print("drawn geometries so far:", m.drawn_geometries) # empty without a live viewer
show(m)
WARNING:param.project_geom: While projecting a Rectangles element from a PlateCarree coordinate reference system (crs) to a Mercator projection none of the projected paths were contained within the bounds specified by the projection. Ensure you have specified the correct coordinate system for your data.
drawn geometries so far: []
annotate - an editable attribute table¶
annotate returns a HoloViews annotator over a drawn layer - a table whose rows you edit alongside the geometry (live only).
m = InteractiveMap(crs=4326)
m.points(birds, size=5, color="navy")
annotator = m.annotate()
print("annotator:", type(annotator).__name__)
show(m)
annotator: annotate
cross_filter - brush-to-filter across layers¶
cross_filter returns a HoloViews link_selections shared across the map's layers, so brushing one filters the others (live only).
m = InteractiveMap(crs=4326)
m.points(birds, column="log_uncertainty", size=6, cmap="viridis")
linker = m.cross_filter()
print("cross-filter linker:", type(linker).__name__)
show(m)
cross-filter linker: link_selections