Skip to content

Interactive maps (HoloViz)#

InteractiveMap is the pan/zoom/hover backend: a Bokeh canvas with a display CRS and a list of layers it can re-order, hide, restyle and remove after they are drawn. It is the interactive sibling of the matplotlib Map — the same method names wherever the two can draw the same thing — and needs the interactive extra (pip install 'digitalearth[interactive]') only when a builder or render method is actually called; importing the module works without it.

from digitalearth.interactive import InteractiveMap

m = InteractiveMap(crs=3857, tiles="CartoLight")
m.field(dataset, cmap="terrain")
m.points(stations, name="obs")
m.coastlines()
m.save("map.html")

Every input is reprojected to the display CRS through pyramids before an element is built, so the Bokeh layers are already in the display CRS (EPSG:3857 by default — the only CRS Bokeh tile basemaps render). The rendering itself is HoloViews/GeoViews/Datashader; styling keywords (cmap, clim, alpha, …) are handed straight to the engine, which is why they are documented there rather than here.

What this tier is for#

Exploration: a dataset you pan into, a cell you click to pull a time series, an area you draw to crop, a million points shaded server-side so they cost the same as a thousand. Anything that must come back as a file — a vector export, a print-quality figure — belongs to the matplotlib tier; this one saves interactive HTML and headless PNG.

The layer list#

A builder records a layer addressed by the name= you gave it (or a generated id), and returns the map so the calls chain. layer_ids lists them in draw order, and move_layer, remove_layer, replace_layer and set_visible work on that list afterwards, so a figure can be rearranged without being rebuilt. Layers sit in bands — underlay, reference, data, overlay — so a basemap stays under the data and a graticule stays over it however the calls were ordered. figure_spec is the whole map as a value, the description the other tiers read back.

The layer control#

layer_control() builds a Panel widget — one visibility toggle per layer, an opacity slider and a basemap switch — and returns the map; the widget itself is read back through layer_control_panel. The control is keyed by layer id, not by the position a layer held when it was built, so toggling and removal keep working after the overlay is re-stacked. reorder=True adds a ▲/▼ button per layer that moves it within its band live. The basemap switch is Web-Mercator-only (Bokeh renders tiles in EPSG:3857); named outright on a non-Mercator map it is refused, left at the default it is quietly dropped.

m = InteractiveMap().field(dataset).points(stations)
m.layer_control(controls=("visibility", "opacity"), reorder=True)
m.layer_control_panel        # the Panel object to display

Every widget event — the dashboard's and the layer control's alike — goes through one reconcile that re-styles only the layers a value reaches and reuses every other element untouched, so a slider tick does not rebuild the map.

Big data#

rasterize and datashade aggregate millions of rows into a server-rendered density image that re-aggregates on every pan/zoom. rasterize keeps a Bokeh colorbar and client-side colour-mapping, so it can pin a frozen colour scale with clim/cnorm — a rasterized layer then shares one range with a neighbouring field, and cnorm="eq_hist" reaches Bokeh's EqHistColorMapper (which takes explicit limits, where Datashader refuses a span under eq-hist).

m.rasterize(gps_fixes, aggregator="mean", column="speed", clim=(0, 120), cnorm="eq_hist")

Clicking, drawing and brushing#

A live kernel or server is what makes these round-trip to Python; in a saved HTML they degrade to plain hover. on_tap/tap_profile pull a value (or a DatasetCollection time series) at the clicked cell. draw() adds a box/polygon/point/freehand tool and drawn_geometry/aoi_crop read the sketch back in pyramids' CRS to drive a crop. cross_filter links a selection across panels and hands the selected rows back.

Live data#

live() adds a streaming layer backed by a HoloViews Pipe (each push replaces the data) or a Buffer (each push appends, keeping the last length rows). Only the changed glyphs redraw — the IN-2 reconcile applied to a feed — so a moving vehicle or a sensor stream does not rebuild the map. Reach the stream with live_stream(id) and feed it with push(id, data); the data is in the display CRS, and the repaint reaches the browser under a live kernel/server.

m = InteractiveMap().live(kind="points", name="cars")
m.push("cars", positions_df)        # positions_df: x/y in the display CRS

Themes#

theme() sets one Bokeh theme for every render of the map — a built-in name ("dark_minimal", "night_sky", …) or a bokeh.themes.Theme — instead of threading bgcolor through **opts at every call.

m = InteractiveMap().field(dataset).theme("dark_minimal")

Dashboards#

dashboard() wraps the map and reactive widgets into a Panel app; serve() marks it servable and save_app() bakes the widget states into a standalone HTML file. A pyramids-backed app must be served, not converted to WASM — GDAL does not run in the browser. share() syncs the view into the URL under a running server.

digitalearth.interactive.map.InteractiveMap #

Bases: RasterMixin, VectorMixin, BigDataMixin, TemporalMixin, DecorationMixin, LegendMixin, InteractionMixin, LiveMixin, ProjectionMixin, AnimationMixin, DashboardMixin, InteractiveMapBase

Interactive 2-D web map: pan/zoom/hover Bokeh layers built from pyramids data.

The interactive sibling of the static :class:~digitalearth.static.map.Map: raster/vector builders turn pyramids objects into GeoViews elements (reprojected to the display CRS through pyramids first), register them as layers, and render()/save() compose them into one overlay. Needs the optional interactive extra (pip install 'digitalearth[interactive]') only when a builder/render method is actually called — importing this module works without it.

Examples:

  • Importing and constructing needs no HoloViz engine:
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap(crs=3857, width=800, height=600)
    >>> m.layers
    []
    
  • Layers register in overlay order and the builders chain:
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap()
    >>> m.add_layer("dem").add_layer("basemap") is m
    True
    >>> m.layers
    ['dem', 'basemap']
    
  • With the interactive extra installed, a raster becomes a pan/zoom web map:
    >>> from pyramids.dataset import Dataset                      # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")      # doctest: +SKIP
    >>> InteractiveMap().field(dem).basemap().save("map.html").name  # doctest: +SKIP
    'map.html'
    
See Also

digitalearth.static.map.Map: the static matplotlib sibling of this scene. digitalearth.three_d.scene3d.Scene3D: the true-3D (PyVista) sibling.

Source code in src/digitalearth/interactive/map.py
class InteractiveMap(
    RasterMixin,
    VectorMixin,
    BigDataMixin,
    TemporalMixin,
    DecorationMixin,
    LegendMixin,
    InteractionMixin,
    LiveMixin,
    ProjectionMixin,
    AnimationMixin,
    DashboardMixin,
    InteractiveMapBase,
):
    """Interactive 2-D web map: pan/zoom/hover Bokeh layers built from pyramids data.

    The interactive sibling of the static :class:`~digitalearth.static.map.Map`: raster/vector builders
    turn pyramids objects into GeoViews elements (reprojected to the display CRS through pyramids first),
    register them as layers, and ``render()``/``save()`` compose them into one overlay. Needs the optional
    ``interactive`` extra (``pip install 'digitalearth[interactive]'``) only when a builder/render method
    is actually called — importing this module works without it.

    Examples:
        - Importing and constructing needs no HoloViz engine:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap(crs=3857, width=800, height=600)
            >>> m.layers
            []

            ```
        - Layers register in overlay order and the builders chain:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap()
            >>> m.add_layer("dem").add_layer("basemap") is m
            True
            >>> m.layers
            ['dem', 'basemap']

            ```
        - With the ``interactive`` extra installed, a raster becomes a pan/zoom web map:
            ```python
            >>> from pyramids.dataset import Dataset                      # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")      # doctest: +SKIP
            >>> InteractiveMap().field(dem).basemap().save("map.html").name  # doctest: +SKIP
            'map.html'

            ```

    See Also:
        digitalearth.static.map.Map: the static matplotlib sibling of this scene.
        digitalearth.three_d.scene3d.Scene3D: the true-3D (PyVista) sibling.
    """

drawn_geometry property #

The geometry drawn via :meth:draw, as a display-CRS bbox/dict (or None).

For a box this is (xmin, ymin, xmax, ymax) in the display CRS — ready to feed Dataset.crop (pyramids). Returns None before anything is drawn. Needs a live kernel for the stream to have captured anything.

Returns:

Type Description
Any

The drawn geometry, or None.

layer_control_panel property #

The Panel layer manager :meth:layer_control built, or None when none has been built.

:meth:layer_control returns the map, the way every other builder on both 2-D tiers does (#264), so the object a caller displays is held on the map and read back here — the same place the static tier keeps its fig/ax and this tier keeps its layers. Read-only on purpose: a panel this map did not build is not this map's control.

Returns:

Type Description
Any

A panel.viewable.Viewable whose widgets reactively rebuild the map overlay — toggling a

Any

layer hides/shows it, the opacity slider sets its alpha, and the basemap Select swaps the

Any

tiles underneath. None until :meth:layer_control has been called; a second call replaces

Any

it rather than stacking a second control.

Examples:

  • The control is reached through the map the builder returned:
    >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
    >>> m = InteractiveMap().field(dem).layer_control()            # doctest: +SKIP
    >>> m.layer_control_panel is None                              # doctest: +SKIP
    False
    

layer_ids property #

The ids of the layers this map draws, in draw order, bottom first.

Returns:

Type Description
list[str]

One id per described layer. A layer the caller named carries that name, with surrounding

list[str]

whitespace removed; an unnamed one gets a generated id counting the layers of its kind —

list[str]

points, text, points, text is points-1, points-2, text-1, text-2, listed in draw order.

list[str]

It counted the map until review R2-M10, while this sentence already said otherwise

list[str]

(review R2-L2).

Examples:

  • A named layer keeps its name; an unnamed one is numbered after what it is:
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().add_layer("dem", name="elevation").add_layer("obs").layer_ids
    ['elevation', 'holoviews-1']
    
  • Draw order, not call order: a layer in the reference band added second is listed first, because that is where it is drawn:
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap().add_layer("obs", name="obs")
    >>> m.add_layer("grid", name="grid", band="reference").layer_ids
    ['grid', 'obs']
    
  • A map that has drawn nothing has no ids:
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().layer_ids
    []
    

figure_spec property #

What the map draws, as data: its layers, their sources and the view.

Returns:

Name Type Description
A FigureSpec

class:~digitalearth.base.spec.FigureSpec with one panel, "main", whose layers are the

FigureSpec

tree in draw order and whose sources are what each builder was given.

FigureSpec

It carries only the half of the styling that travels

FigureSpec

(:func:~digitalearth.base.spec._serial.travels_in_a_figure). A colormap object, a Datashader

FigureSpec

reduction, a tile provider, a timestamp, a tuple such as a dash pattern and an array are held

FigureSpec

beside the layer instead (:func:describe), so a figure read back elsewhere draws each layer

FigureSpec

with what the description alone can say. A list or dict of plain values is not one of

FigureSpec

those — it comes back from JSON as itself, so it is described (#330).

FigureSpec

A map built from a GeoDataFrame or a dataset already in memory can be handed straight to a

FigureSpec

renderer, but not written: to_dict() refuses an object: source, since a reference into this

FigureSpec

process's memory would be unreadable everywhere else. Give a builder a path or a URL to get a

FigureSpec

figure that can be stored.

Examples:

  • The panel names the layers it draws, and each layer says what it is:
    >>> from digitalearth.interactive import InteractiveMap
    >>> figure = InteractiveMap().add_layer("dem", name="elevation").figure_spec
    >>> figure.panels[0].id, figure.panels[0].layers
    ('main', ('elevation',))
    >>> figure.layers.get("elevation").kind
    'custom:holoviews'
    
  • A builder describes its layer by the engine-neutral kind and the recipe it drew by, and files what it drew as the layer's source:
    >>> import geopandas as gpd                                       # doctest: +SKIP
    >>> from shapely.geometry import Point                            # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> gdf = gpd.GeoDataFrame(geometry=[Point(4.9, 52.4)], crs=4326) # doctest: +SKIP
    >>> figure = InteractiveMap().points(gdf).figure_spec             # doctest: +SKIP
    >>> layer = figure.layers.get("points-1")                         # doctest: +SKIP
    >>> layer.kind, layer.symbology.props["via"], layer.source_id     # doctest: +SKIP
    ('points', 'geometry', 'points-1')
    

viewport property #

Where the map is looking, as a value — including the region it has been framed on.

Returns:

Type Description
Viewport

The view :class:~digitalearth.interactive.core.base.InteractiveMapBase builds from the display CRS,

Viewport

carrying the region :meth:set_bounds asked for when there has been one. It still carries no

Viewport

centre or zoom: this tier is framed by an extent, not by a camera position.

field(data, *, band=DEFAULT_BAND, cmap=None, limits=None, scheme=None, k=None, opacity=UNSET, colorbar=True, clabel=None, name=None, visible=True, **opts) #

Add a colour-mapped raster layer with hover readout.

Parameters:

Name Type Description Default
data Any

A pyramids Dataset / NetCDF / Source; reprojected to the display CRS through pyramids when needed.

required
band int

1-based band to render.

DEFAULT_BAND
cmap str | None

Colormap name; None (default) resolves it from the variable via autostyle.auto_style (DI.12) — the same lookup the static Map uses.

None
limits tuple[float, float] | None

Optional (vmin, vmax) colour limits; None auto-scales. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use, so the same channel is written the same way on every tier (#332); it reaches HoloViews as its own clim. A list is taken too, and is the spelling the figure records — a tuple is what the travel rule refuses, so the documented pair used to be dropped from every saved figure (review R2-M13). The drawer hands HoloViews the tuple its own option is declared with either way. Under a graduated scheme it pins the classes to this window (#378): they span it exactly and an outlier lands in an end class; "categorical" and explicit edges ignore it, having no range to pin.

None
scheme Any | None

Colour the band class by class rather than along a ramp. A named graduated scheme ("quantiles", "equal_interval", "fisher_jenks", …) or an explicit list of edges cuts classes coloured from cmap; "categorical" gives each integer code a class of its own, coloured from the shared categorical palette (cmap picks another). The classes are cut by :mod:digitalearth.base.raster_classes, the classifier the static and web tiers use, so one band is classed — and coloured — alike on all three, and they are recorded in the layer's colour encoding, so the colorbar steps at them and a figure drawn on another tier keeps them. None (default) draws the continuous ramp.

None
k int | None

How many classes a named graduated scheme cuts; None takes 5. Ignored without scheme.

None
opacity Maybe[float]

Layer opacity in [0, 1]; not passed leaves :data:FIELD_ALPHA. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use, so the same channel is written the same way on every tier (#332); HoloViews reads it as alpha. The keyword is recorded when it is passed, so a caller asking for exactly that value publishes it like any other (#334).

UNSET
colorbar bool

Whether to draw a colorbar.

True
clabel str | None

Colorbar label; None (default) takes the variable's units from autostyle.auto_style (#230) and leaves the colorbar unlabelled when it knows none.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Examples:

  • Render a DEM as a pan/zoom raster with explicit colour limits:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().field(dem, cmap="terrain", limits=(0, 60))  # doctest: +SKIP
    >>> len(m.layers)                                               # doctest: +SKIP
    1
    
  • Classify a band into three equal-interval classes, and read the edges its colour encoding records — the ones a figure drawn on another tier keeps:
    >>> import numpy as np                                            # doctest: +SKIP
    >>> from digitalearth.base.sources import get_source              # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> src = get_source(                                             # doctest: +SKIP
    ...     np.arange(10.0).reshape(2, 5), x=np.arange(5.0), y=np.array([1.0, 0.0])
    ... )
    >>> m = InteractiveMap().field(src, scheme="equal_interval", k=3, name="dem")  # doctest: +SKIP
    >>> m.figure_spec.layers.get("dem").symbology.encoding("color").scale.breaks  # doctest: +SKIP
    (0.0, 3.0, 6.0, 9.0)
    
  • Draw a band of class codes as categories, one colour per code:
    >>> import numpy as np                                            # doctest: +SKIP
    >>> from digitalearth.base.sources import get_source              # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> src = get_source(                                             # doctest: +SKIP
    ...     np.array([[1.0, 1.0, 2.0], [3.0, 3.0, 2.0]]),
    ...     x=np.array([0.0, 1.0, 2.0]),
    ...     y=np.array([1.0, 0.0]),
    ... )
    >>> m = InteractiveMap().field(src, scheme="categorical", name="landcover")  # doctest: +SKIP
    >>> scale = m.figure_spec.layers.get("landcover").symbology.encoding("color").scale  # doctest: +SKIP
    >>> scale.categories, [scale.color_for(code) for code in scale.categories]  # doctest: +SKIP
    ((1, 2, 3), ['#1f77b4', '#ff7f0e', '#2ca02c'])
    

Returns:

Type Description
Self

This map (chainable).

Raises:

Type Description
ValueError

for a scheme that cannot classify the band — an unknown name, k below one, or, under "categorical", a band holding non-integer values, more than :data:~digitalearth.base.raster_classes.MAX_RASTER_CATEGORIES codes, or no valid cell.

Source code in src/digitalearth/interactive/builders/raster.py
@_skips_off_limb
def field(
    self,
    data: Any,
    *,
    band: int = DEFAULT_BAND,
    cmap: str | None = None,
    limits: tuple[float, float] | None = None,
    scheme: Any | None = None,
    k: int | None = None,
    opacity: Maybe[float] = UNSET,
    colorbar: bool = True,
    clabel: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a colour-mapped raster layer with hover readout.

    Args:
        data: A pyramids ``Dataset`` / ``NetCDF`` / ``Source``; reprojected to the display CRS
            through pyramids when needed.
        band: 1-based band to render.
        cmap: Colormap name; ``None`` (default) resolves it from the variable via
            ``autostyle.auto_style`` (DI.12) — the same lookup the static ``Map`` uses.
        limits: Optional ``(vmin, vmax)`` colour limits; ``None`` auto-scales. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use, so the same
            channel is written the same way on every tier (#332); it reaches HoloViews as its own
            ``clim``. A list is taken too, and is the spelling the figure records — a tuple is what the
            travel rule refuses, so the documented pair used to be dropped from every saved figure
            (review R2-M13). The drawer hands HoloViews the tuple its own option is declared with either
            way. Under a graduated ``scheme`` it pins the classes to this window (#378): they span it
            exactly and an outlier lands in an end class; ``"categorical"`` and explicit edges ignore it,
            having no range to pin.
        scheme: Colour the band class by class rather than along a ramp. A named graduated scheme
            (``"quantiles"``, ``"equal_interval"``, ``"fisher_jenks"``, …) or an explicit list of edges cuts
            classes coloured from ``cmap``; ``"categorical"`` gives each integer code a class of its own,
            coloured from the shared categorical palette (``cmap`` picks another). The classes are cut by
            :mod:`digitalearth.base.raster_classes`, the classifier the static and web tiers use, so one
            band is classed — and coloured — alike on all three, and they are recorded in the layer's
            colour encoding, so the colorbar steps at them and a figure drawn on another tier keeps them.
            ``None`` (default) draws the continuous ramp.
        k: How many classes a named graduated scheme cuts; ``None`` takes 5. Ignored without ``scheme``.
        opacity: Layer opacity in ``[0, 1]``; not passed leaves :data:`FIELD_ALPHA`. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use, so the same
            channel is written the same way on every tier (#332); HoloViews reads it as ``alpha``. The
            keyword is recorded when it is passed, so a caller asking for exactly that value publishes it
            like any other (#334).
        colorbar: Whether to draw a colorbar.
        clabel: Colorbar label; ``None`` (default) takes the variable's ``units`` from
            ``autostyle.auto_style`` (#230) and leaves the colorbar unlabelled when it knows none.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Examples:
        - Render a DEM as a pan/zoom raster with explicit colour limits:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().field(dem, cmap="terrain", limits=(0, 60))  # doctest: +SKIP
            >>> len(m.layers)                                               # doctest: +SKIP
            1

            ```
        - Classify a band into three equal-interval classes, and read the edges its colour encoding
          records — the ones a figure drawn on another tier keeps:
            ```python
            >>> import numpy as np                                            # doctest: +SKIP
            >>> from digitalearth.base.sources import get_source              # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> src = get_source(                                             # doctest: +SKIP
            ...     np.arange(10.0).reshape(2, 5), x=np.arange(5.0), y=np.array([1.0, 0.0])
            ... )
            >>> m = InteractiveMap().field(src, scheme="equal_interval", k=3, name="dem")  # doctest: +SKIP
            >>> m.figure_spec.layers.get("dem").symbology.encoding("color").scale.breaks  # doctest: +SKIP
            (0.0, 3.0, 6.0, 9.0)

            ```
        - Draw a band of class codes as categories, one colour per code:
            ```python
            >>> import numpy as np                                            # doctest: +SKIP
            >>> from digitalearth.base.sources import get_source              # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> src = get_source(                                             # doctest: +SKIP
            ...     np.array([[1.0, 1.0, 2.0], [3.0, 3.0, 2.0]]),
            ...     x=np.array([0.0, 1.0, 2.0]),
            ...     y=np.array([1.0, 0.0]),
            ... )
            >>> m = InteractiveMap().field(src, scheme="categorical", name="landcover")  # doctest: +SKIP
            >>> scale = m.figure_spec.layers.get("landcover").symbology.encoding("color").scale  # doctest: +SKIP
            >>> scale.categories, [scale.color_for(code) for code in scale.categories]  # doctest: +SKIP
            ((1, 2, 3), ['#1f77b4', '#ff7f0e', '#2ca02c'])

            ```

    Returns:
        This map (chainable).

    Raises:
        ValueError: for a ``scheme`` that cannot classify the band — an unknown name, ``k`` below one, or,
            under ``"categorical"``, a band holding non-integer values, more than
            :data:`~digitalearth.base.raster_classes.MAX_RASTER_CATEGORIES` codes, or no valid cell.
    """
    scale = limits_scale(limits)
    if scheme is not None:
        # Pin the classes to `limits` only when it is a real `(lo, hi)` pair; a malformed `limits` is left
        # to `limits_scale`'s tolerant handling above (it draws rather than raising), so the classify path
        # must not turn the same bad value into a cryptic unpack error (review L3).
        window = (
            limits
            if isinstance(limits, (tuple, list)) and len(limits) == 2
            else None
        )
        scale = _band_classes(self, data, band, scheme, k, cmap, clip=window).scale
    # The caller's raw HoloViews keywords are split per value (review M3): the JSON-safe half goes
    # into the description, and what has no JSON form — a colormap object, a callable — is held beside
    # the layer, because a figure is saved as JSON.
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    ask = Ask()
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="raster",
        source=data,
        held=held,
        symbology=Symbology(
            # The layer's colour varies with the band it draws, so that is published as a binding rather
            # than left for a reader to infer from `cmap`. It is what a colorbar hangs on (order 24): a
            # `Guide` explains an encoding, so a layer with no colour encoding has no key, and a layer
            # with this one has a key that moves, hides and disappears with it.
            encodings={
                "color": Encoding.by_field(
                    "color", coloured_by(data, band), scale=scale
                )
            },
            props={
                "via": "image",
                "band": band,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "clim": describe(held, "clim", _travelling_pair(limits)),
                "scheme": scheme
                if scheme is None or isinstance(scheme, str)
                else list(scheme),
                "k": k,
                "alpha": ask("alpha", opacity, FIELD_ALPHA),
                "colorbar": colorbar,
                "clabel": clabel,
                "opts": described_opts,
                **ask.record,
            },
        ),
    )

quadmesh(data, *, band=DEFAULT_BAND, cmap=None, clabel=None, name=None, visible=True, **opts) #

Add a quadrilateral-mesh raster layer (handles non-uniform / curvilinear coordinates).

Unlike :meth:field (regular grid), a QuadMesh draws each cell from its coordinate arrays, so irregularly spaced or 2-D (curvilinear) coordinates render without resampling.

Parameters:

Name Type Description Default
data Any

A pyramids Dataset / NetCDF / Source; reprojected through pyramids.

required
band int

1-based band to render.

DEFAULT_BAND
cmap str | None

Colormap name; None (default) resolves it from the variable via autostyle.auto_style (DI.12) — consistent with :meth:field.

None
clabel str | None

Colorbar label; None (default) takes the variable's units from autostyle.auto_style (#230), as :meth:field does.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Examples:

  • Draw an irregular grid without resampling to axis-aligned:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> grid = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
    >>> InteractiveMap().quadmesh(grid).save("mesh.html").name      # doctest: +SKIP
    'mesh.html'
    

Returns:

Type Description
Self

This map (chainable).

Source code in src/digitalearth/interactive/builders/raster.py
@_skips_off_limb
def quadmesh(
    self,
    data: Any,
    *,
    band: int = DEFAULT_BAND,
    cmap: str | None = None,
    clabel: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a quadrilateral-mesh raster layer (handles non-uniform / curvilinear coordinates).

    Unlike :meth:`field` (regular grid), a ``QuadMesh`` draws each cell from its coordinate
    arrays, so irregularly spaced or 2-D (curvilinear) coordinates render without resampling.

    Args:
        data: A pyramids ``Dataset`` / ``NetCDF`` / ``Source``; reprojected through pyramids.
        band: 1-based band to render.
        cmap: Colormap name; ``None`` (default) resolves it from the variable via
            ``autostyle.auto_style`` (DI.12) — consistent with :meth:`field`.
        clabel: Colorbar label; ``None`` (default) takes the variable's ``units`` from
            ``autostyle.auto_style`` (#230), as :meth:`field` does.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Examples:
        - Draw an irregular grid without resampling to axis-aligned:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> grid = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
            >>> InteractiveMap().quadmesh(grid).save("mesh.html").name      # doctest: +SKIP
            'mesh.html'

            ```

    Returns:
        This map (chainable).
    """
    _require_holoviz()
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="mesh",
        source=data,
        held=held,
        symbology=Symbology(
            # Coloured by its band, exactly as `field` is; it takes no `clim=`, so the domain is the
            # engine's to measure and the encoding carries no scale rather than a guessed one.
            encodings={
                "color": Encoding.by_field("color", coloured_by(data, band))
            },
            props={
                "via": "quadmesh",
                "band": band,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "clabel": clabel,
                "opts": described_opts,
            },
        ),
    )

rgb(data, *, bands=DEFAULT_COMPOSITE_BANDS, limits=None, name=None, visible=True, **opts) #

Add a true-colour composite from three raster bands (2–98 % percentile stretch).

Parameters:

Name Type Description Default
data Any

A pyramids multiband Dataset; reprojected to the display CRS first.

required
bands Sequence[int]

The three 1-based band indices composing (R, G, B).

DEFAULT_COMPOSITE_BANDS
limits ChannelLimits | None

Optional frozen (lo, hi) stretch bounds, one pair per channel — skips the per-call percentile scan, so a sequence of frames can share one black and white point.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

This map (chainable).

Examples:

  • Compose three bands of a satellite stack into true colour:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> stack = Dataset.read_file("sentinel.tif")                   # doctest: +SKIP
    >>> m = InteractiveMap().rgb(stack, bands=(4, 3, 2))            # doctest: +SKIP
    >>> [d.name for d in m.layers[0].vdims]                         # doctest: +SKIP
    ['R', 'G', 'B']
    

Raises:

Type Description
ValueError

when bands does not name exactly three bands, or limits is given without one (lo, hi) pair per channel.

Source code in src/digitalearth/interactive/builders/raster.py
@_skips_off_limb
def rgb(
    self,
    data: Any,
    *,
    bands: Sequence[int] = DEFAULT_COMPOSITE_BANDS,
    limits: ChannelLimits | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a true-colour composite from three raster bands (2–98 % percentile stretch).

    Args:
        data: A pyramids multiband ``Dataset``; reprojected to the display CRS first.
        bands: The three 1-based band indices composing ``(R, G, B)``.
        limits: Optional frozen ``(lo, hi)`` stretch bounds, one pair per channel — skips the per-call
            percentile scan, so a sequence of frames can share one black and white point.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        This map (chainable).

    Examples:
        - Compose three bands of a satellite stack into true colour:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> stack = Dataset.read_file("sentinel.tif")                   # doctest: +SKIP
            >>> m = InteractiveMap().rgb(stack, bands=(4, 3, 2))            # doctest: +SKIP
            >>> [d.name for d in m.layers[0].vdims]                         # doctest: +SKIP
            ['R', 'G', 'B']

            ```

    Raises:
        ValueError: when ``bands`` does not name exactly three bands, or ``limits`` is given without
            one ``(lo, hi)`` pair per channel.
    """
    _require_holoviz()
    # Refused here rather than in the drawer, because the message names the argument the caller wrote.
    require_three_bands("rgb", bands)
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="rgb",
        source=data,
        held=held,
        symbology=Symbology(
            props={
                "via": "rgb",
                "bands": tuple(bands),
                # A frozen stretch whose channel had no finite cell holds `(nan, nan)`, which JSON has
                # no spelling for. Such limits are held beside the layer and described as not given,
                # which is what a reader without them derives per frame.
                "limits": describe(held, "limits", limits),
                "opts": described_opts,
            }
        ),
    )

contours(dataset, *, band=DEFAULT_BAND, levels=None, interval=None, filled=False, name=None, visible=True, **opts) #

Trace iso-value lines of a raster band, or fill the bands between them.

The three keywords the Tier-2 contract declares — levels, interval and filled — on the one method that answers to the name, so a call written against the web or static tier runs here unchanged (#262). This tier also had a second method, filled_contours, for what filled=True says here; it was deleted in review M3, and interval= used to fall through **opts to HoloViews, which refused it as an unknown style option.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset / NetCDF / Source; reprojected through pyramids.

required
band int

1-based band to contour.

DEFAULT_BAND
levels Any

Contour levels — an int (count) or explicit sequence; None takes the variable's canonical levels from autostyle.auto_style (#230), falling back to 10. Give at most one of this or interval.

None
interval float | None

Spacing between levels — one level every N, in the band's own units. Resolved against the band when the layer is drawn, because it is the band that decides which multiples of the spacing lie inside it, and only the ones strictly inside are traced: a level on an extreme draws the frame's edge or nothing. The arithmetic is :func:~digitalearth.base.levels.levels_every, shared with the static tier so the two cannot disagree about which multiples are inside.

None
filled bool

Fill the bands between the levels instead of drawing the levels as lines. It is also what the layer's kind records — "filled_contours" against "contours" — so a figure says which of the two renders it holds.

False
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Raises:

Type Description
ValueError

when both levels and interval are given — two ways of asking for one thing, so neither can be silently preferred; when interval is not a positive finite number; or when no multiple of it lies inside the band's range. The last two are refused as the layer is drawn, which is where the band is read.

Examples:

  • Contour a raster at five levels:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().contours(dem, levels=5)                # doctest: +SKIP
    >>> len(m.layers)                                               # doctest: +SKIP
    1
    
  • One level every 100 m, filled, from the same method:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().contours(dem, interval=100, filled=True)  # doctest: +SKIP
    >>> type(m.layers[0]).__name__                                  # doctest: +SKIP
    'Polygons'
    

Returns:

Type Description
Self

This map (chainable).

See Also

digitalearth.base.levels.levels_every: the shared interval-to-levels arithmetic.

Source code in src/digitalearth/interactive/builders/raster.py
@_skips_off_limb
def contours(
    self,
    dataset: Any,
    *,
    band: int = DEFAULT_BAND,
    levels: Any = None,
    interval: float | None = None,
    filled: bool = False,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Trace iso-value lines of a raster band, or fill the bands between them.

    The three keywords the Tier-2 contract declares — ``levels``, ``interval`` and ``filled`` — on the
    one method that answers to the name, so a call written against the web or static tier runs here
    unchanged (#262). This tier also had a second method, ``filled_contours``, for what ``filled=True``
    says here; it was deleted in review M3, and ``interval=`` used to fall through ``**opts`` to
    HoloViews, which refused it as an unknown *style* option.

    Args:
        dataset: A pyramids ``Dataset`` / ``NetCDF`` / ``Source``; reprojected through pyramids.
        band: 1-based band to contour.
        levels: Contour levels — an int (count) or explicit sequence; ``None`` takes the
            variable's canonical levels from ``autostyle.auto_style`` (#230), falling back to 10.
            Give at most one of this or ``interval``.
        interval: Spacing between levels — one level every N, in the band's own units. Resolved
            against the band when the layer is drawn, because it is the band that decides which
            multiples of the spacing lie inside it, and only the ones *strictly* inside are traced: a
            level on an extreme draws the frame's edge or nothing. The arithmetic is
            :func:`~digitalearth.base.levels.levels_every`, shared with the static tier so the two
            cannot disagree about which multiples are inside.
        filled: Fill the bands between the levels instead of drawing the levels as lines. It is also
            what the layer's kind records — ``"filled_contours"`` against ``"contours"`` — so a figure
            says which of the two renders it holds.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **opts: Extra HoloViews style options applied to the element.

    Raises:
        ValueError: when both ``levels`` and ``interval`` are given — two ways of asking for one thing,
            so neither can be silently preferred; when ``interval`` is not a positive finite number; or
            when no multiple of it lies inside the band's range. The last two are refused as the layer
            is drawn, which is where the band is read.

    Examples:
        - Contour a raster at five levels:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().contours(dem, levels=5)                # doctest: +SKIP
            >>> len(m.layers)                                               # doctest: +SKIP
            1

            ```
        - One level every 100 m, filled, from the same method:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().contours(dem, interval=100, filled=True)  # doctest: +SKIP
            >>> type(m.layers[0]).__name__                                  # doctest: +SKIP
            'Polygons'

            ```

    Returns:
        This map (chainable).

    See Also:
        digitalearth.base.levels.levels_every: the shared interval-to-levels arithmetic.
    """
    _one_spacing_only("contours", levels, interval)
    return self._contour_layer(
        dataset,
        band=band,
        levels=levels,
        interval=interval,
        filled=filled,
        name=name,
        visible=visible,
        opts=opts,
    )

spaghetti(collection, *, band=DEFAULT_BAND, name=None, visible=True, **opts) #

Overlay each member of a DatasetCollection as line contours (ensemble spaghetti).

Each member gets a distinct colour from a cycling palette so the strands are distinguishable, unless the caller passes an explicit color/cmap in opts.

Parameters:

Name Type Description Default
collection Any

A pyramids DatasetCollection whose members share a grid.

required
band int

1-based band contoured in every member.

DEFAULT_BAND
name str | None

The caller's own name for the layers, used as their ids and labels; None (default) generates one per member. One call draws one layer per member, so a single name is shared and the second and later take -2, -3, … (#321).

None
visible bool

Whether the members are drawn. False builds them hidden and describes them hidden (#327).

True
**opts Any

Extra HoloViews style options applied to each member's contour element. An explicit color or cmap here disables the per-member colour cycle.

{}

Examples:

  • Overlay a three-member ensemble as spaghetti contours:
    >>> from pyramids.dataset.collection import DatasetCollection   # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dc = DatasetCollection.from_files(["examples/data/acc4000.tif"] * 3)  # doctest: +SKIP
    >>> m = InteractiveMap().spaghetti(dc, levels=4)                # doctest: +SKIP
    >>> len(m.layers)                                               # doctest: +SKIP
    3
    

Returns:

Type Description
Self

This map (chainable) — one contour layer registered per member.

Source code in src/digitalearth/interactive/builders/raster.py
def spaghetti(
    self,
    collection: Any,
    *,
    band: int = DEFAULT_BAND,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Overlay each member of a ``DatasetCollection`` as line contours (ensemble spaghetti).

    Each member gets a distinct colour from a cycling palette so the strands are
    distinguishable, unless the caller passes an explicit ``color``/``cmap`` in ``opts``.

    Args:
        collection: A pyramids ``DatasetCollection`` whose members share a grid.
        band: 1-based band contoured in every member.
        name: The caller's own name for the layers, used as their ids and labels; ``None``
            (default) generates one per member. One call draws **one layer per member**, so a
            single name is shared and the second and later take ``-2``, ``-3``, … (#321).
        visible: Whether the members are drawn. ``False`` builds them hidden **and** describes
            them hidden (#327).
        **opts: Extra HoloViews style options applied to each member's contour element. An
            explicit ``color`` or ``cmap`` here disables the per-member colour cycle.

    Examples:
        - Overlay a three-member ensemble as spaghetti contours:
            ```python
            >>> from pyramids.dataset.collection import DatasetCollection   # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dc = DatasetCollection.from_files(["examples/data/acc4000.tif"] * 3)  # doctest: +SKIP
            >>> m = InteractiveMap().spaghetti(dc, levels=4)                # doctest: +SKIP
            >>> len(m.layers)                                               # doctest: +SKIP
            3

            ```

    Returns:
        This map (chainable) — one contour layer registered per member.
    """
    cycle_colour = "color" not in opts and "cmap" not in opts
    # `levels` is a parameter of the shared funnel rather than a style option, so it is taken out of
    # the caller's keywords here instead of being handed to it twice.
    levels = opts.pop("levels", None)
    for index, member in enumerate(collection.datasets):
        # The cycle goes in the *derived* bucket, not in the caller's. Passing it through `**opts`
        # filed a colour nobody asked for under the one bucket `portable_encodings` lifts unfiltered,
        # so three unstyled members published three different colours as three caller intents — and a
        # figure carried to another tier repainted itself in this tier's cycle (review R2-H3).
        derived = (
            {"color": self._SPAGHETTI_COLORS[index % len(self._SPAGHETTI_COLORS)]}
            if cycle_colour
            else {}
        )
        self._contour_layer(
            member,
            band=band,
            levels=levels,
            filled=False,
            name=name,
            visible=visible,
            derived=derived,
            # A member's strands are one flat colour — the cycle's, or the caller's own `color=` — so the
            # layer publishes no colour encoding and takes no colour key. A `cmap=` is the one keyword
            # that makes the strands vary with the value they trace, and only then is there a key to draw.
            coloured_by_value="cmap" in opts,
            opts=opts,
        )
    return self

large_image(dataset, *, band=DEFAULT_BAND, max_pixels=4000000, dynamic=True, cmap=None, name=None, visible=True, **opts) #

Add a large raster / COG by loading only the viewport at a decimated overview (DI.14).

The raster analogue of the vector Datashader path: instead of materialising a multi-GB raster, it reads only the visible window at a suitable overview via pyramids and re-reads on pan/ zoom. Cloud-native partial reads for remote COGs over /vsicurl/ come for free.

Every frame is a read through the data tier (#297): the window, the canvas and the budget are a :class:~digitalearth.base.spec.RenderTarget request, and :class:~digitalearth.base.sources.view.SourceView answers it — snapping the window to source pixel edges, never asking for more cells than the window holds, masking what is missing, and drawing an empty frame for a window off the data. A raster in another CRS is read through pyramids' Dataset.warped_view, so each frame warps only its own window rather than the whole raster once.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset (ideally a COG with overviews). Must expose read_part.

required
band int

1-based band to read.

DEFAULT_BAND
max_pixels int

Cell budget per rendered frame. The canvas follows the map's own width and height within it, so a wide map reads a wide window rather than a square one.

4000000
dynamic bool

Re-read the viewport on pan/zoom via a RangeXY stream and on a browser-window resize via a PlotSize stream (IN-6 #432), both needing a live server; False renders one frame of the whole raster within the budget (deterministic — what tests assert).

True
cmap str | None

Colormap; None (default) resolves from the band's variable name via autostyle.auto_style (#249), with "viridis" behind the lookup as the fallback.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

This map (chainable).

Raises:

Type Description
ValueError

when band is below 1 (the tier's band numbering is 1-based, like GDAL).

AttributeError

when dataset lacks the pyramids COG/overview read surface (read_part/preview) — file a pyramids issue rather than reaching around it.

Examples:

  • dynamic=False reads one frame of the whole raster — deterministic, and the one form that works with no live server behind it. A raster already under the budget comes back whole, so the budget only ever caps what is materialised:
    >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
    >>> (dem.rows, dem.columns)                                    # doctest: +SKIP
    (13, 14)
    >>> m = InteractiveMap().large_image(dem, dynamic=False)       # doctest: +SKIP
    >>> m.layers[0].dimension_values(2, flat=False).shape          # doctest: +SKIP
    (13, 14)
    
  • The default dynamic=True registers a viewport-driven layer instead, carrying two streams — a RangeXY that re-reads the window from the axes ranges on every pan/zoom, and a PlotSize that re-reads at the new resolution on a browser-window resize (IN-6):
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> m = InteractiveMap().large_image(dem)                      # doctest: +SKIP
    >>> len(m.layers[0].streams)                                   # doctest: +SKIP
    2
    >>> sorted(m.layers[0].streams[0].contents)                    # doctest: +SKIP
    ['x_range', 'y_range']
    
  • A raster without pyramids' windowed-read surface is refused by name, rather than being quietly read whole:
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> try:                                                       # doctest: +SKIP
    ...     InteractiveMap().large_image(object())
    ... except AttributeError as error:
    ...     print(str(error).split(" (")[0])
    large_image needs pyramids' COG/overview read surface
    
Source code in src/digitalearth/interactive/builders/raster.py
@_skips_off_limb
def large_image(
    self,
    dataset: Any,
    *,
    band: int = DEFAULT_BAND,
    max_pixels: int = 4_000_000,
    dynamic: bool = True,
    cmap: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a large raster / COG by loading only the viewport at a decimated overview (DI.14).

    The raster analogue of the vector Datashader path: instead of materialising a multi-GB raster,
    it reads only the visible window at a suitable overview via **pyramids** and re-reads on pan/
    zoom. Cloud-native partial reads for remote COGs over ``/vsicurl/`` come for free.

    **Every frame is a read through the data tier** (#297): the window, the canvas and the budget are a
    :class:`~digitalearth.base.spec.RenderTarget` request, and
    :class:`~digitalearth.base.sources.view.SourceView` answers it — snapping the window to source pixel
    edges, never asking for more cells than the window holds, masking what is missing, and drawing an
    empty frame for a window off the data. A raster in another CRS is read through pyramids'
    ``Dataset.warped_view``, so each frame warps only its own window rather than the whole raster once.

    Args:
        dataset: A pyramids ``Dataset`` (ideally a COG with overviews). Must expose ``read_part``.
        band: 1-based band to read.
        max_pixels: Cell budget per rendered frame. The canvas follows the map's own width and height
            within it, so a wide map reads a wide window rather than a square one.
        dynamic: Re-read the viewport on pan/zoom via a ``RangeXY`` stream **and on a browser-window
            resize via a ``PlotSize`` stream** (IN-6 #432), both needing a live server; ``False``
            renders one frame of the whole raster within the budget (deterministic — what tests assert).
        cmap: Colormap; ``None`` (default) resolves from the band's variable name via
            ``autostyle.auto_style`` (#249), with ``"viridis"`` behind the lookup as the fallback.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        This map (chainable).

    Raises:
        ValueError: when ``band`` is below 1 (the tier's band numbering is 1-based, like GDAL).
        AttributeError: when ``dataset`` lacks the pyramids COG/overview read surface
            (``read_part``/``preview``) — file a pyramids issue rather than reaching around it.

    Examples:
        - ``dynamic=False`` reads one frame of the whole raster — deterministic, and the one
          form that works with no live server behind it. A raster already under the budget comes back
          whole, so the budget only ever *caps* what is materialised:
            ```python
            >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
            >>> (dem.rows, dem.columns)                                    # doctest: +SKIP
            (13, 14)
            >>> m = InteractiveMap().large_image(dem, dynamic=False)       # doctest: +SKIP
            >>> m.layers[0].dimension_values(2, flat=False).shape          # doctest: +SKIP
            (13, 14)

            ```
        - The default ``dynamic=True`` registers a viewport-driven layer instead, carrying two
          streams — a ``RangeXY`` that re-reads the window from the axes ranges on every pan/zoom, and
          a ``PlotSize`` that re-reads at the new resolution on a browser-window resize (IN-6):
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> m = InteractiveMap().large_image(dem)                      # doctest: +SKIP
            >>> len(m.layers[0].streams)                                   # doctest: +SKIP
            2
            >>> sorted(m.layers[0].streams[0].contents)                    # doctest: +SKIP
            ['x_range', 'y_range']

            ```
        - A raster without pyramids' windowed-read surface is refused by name, rather than
          being quietly read whole:
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> try:                                                       # doctest: +SKIP
            ...     InteractiveMap().large_image(object())
            ... except AttributeError as error:
            ...     print(str(error).split(" (")[0])
            large_image needs pyramids' COG/overview read surface

            ```
    """
    _require_holoviz()
    # Both refusals stay with the builder, because each names an argument the caller wrote.
    if band < 1:
        raise ValueError(f"band is 1-based; got {band!r}")
    if not hasattr(dataset, "read_part") or not hasattr(dataset, "preview"):
        raise AttributeError(
            "large_image needs pyramids' COG/overview read surface (Dataset.read_part / "
            ".preview); upgrade pyramids or use field() for a small raster"
        )
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="raster",
        source=dataset,
        held=held,
        symbology=Symbology(
            # Coloured by its band like `field`, and named the same warp-free way — which matters more
            # here than anywhere else, since the whole point of this builder is never to read the raster
            # whole. No scale: each frame is stretched to the window it read.
            encodings={
                "color": Encoding.by_field("color", coloured_by(dataset, band))
            },
            props={
                "via": "large_image",
                "band": band,
                "max_pixels": max_pixels,
                "dynamic": dynamic,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "opts": described_opts,
            },
        ),
    )

points(features, *, column=None, scheme=None, k=5, size=UNSET, cmap='viridis', opacity=None, rasterize='auto', big_data_threshold=None, name=None, visible=True, **opts) #

Add a point layer, optionally coloured by an attribute column.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of point geometries; reprojected to the display CRS through pyramids when needed. A path or URL naming one is taken too, and is the only input a figure carrying this layer can be written down with.

required
column str | None

The column colouring the points (also shown on hover). The Core spelling, and the one polygons and choropleth on this tier already used; value_column was a second name for one concept (#332) and is gone.

None
opacity float | None

How opaque the layer is, in [0, 1]. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use, and the one the web and 3-D tiers take, so the same channel is written the same way on every tier (#332). HoloViews reads it as alpha, which :func:apply_opacity is the one place to know. None (default) hands the engine no opacity at all, which is not 1.0: it leaves a colormap's own alpha channel in force.

None
scheme Any | None

Optional classification scheme for column — None (the default) is a continuous ramp, a named cleopatra.styling.styles.classify scheme ("quantiles", "equal_interval", "fisher_jenks", …) cuts it into k classes, and "categorical" gives every distinct value its own colour (the same unordered-attribute colouring :meth:choropleth does, so a point layer and a polygon layer key one column the same way). Spelled and computed the same way on every tier that classifies. It styles column, so naming a scheme without one is refused rather than ignored.

None
k int

Number of classes a named scheme is cut into; ignored when scheme is None or "categorical".

5
size Maybe[float]

Marker size in screen pixels — the one thing size ever means on any tier (#251).

UNSET
cmap str

Colormap used when column is given.

'viridis'
rasterize Any

"auto" (default) routes through Datashader above big_data_threshold rows — logged, never silent; True/False force it.

'auto'
big_data_threshold int | None

Row count above which "auto" switches to Datashader; None (default) uses the map's big_data_threshold attribute (#250). Counted off features as given, so a path is measured as a string rather than as rows — see the note below.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element. Anything written here wins over the option a scheme derived — the same precedence :meth:choropleth applies — so colorbar=False drops the colorbar on a classified point layer just as it does on a classified polygon one.

{}
Note

rasterize="auto" counts the rows, whether features is a loaded collection or a path. A path used to be measured as a string — a layer named by a 25-character path was reported as 25 features when the file held 10, so a ten-row layer routed through Datashader on the strength of its filename (#316). pyramids now answers the count without reading the geometry (FeatureCollection.feature_count, serapeum-org/pyramids#1200, shipped in 0.65.0), so naming a file still costs no open and the two spellings of one input agree. The routing log line names the number the decision used, so a surprising one is visible rather than silent.

Examples:

  • Colour gauging stations by an attribute column:
    >>> from pyramids.feature import FeatureCollection              # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
    >>> m = InteractiveMap().points(fc, column="fid")         # doctest: +SKIP
    >>> [d.name for d in m.layers[0].vdims]                         # doctest: +SKIP
    ['fid']
    

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

if scheme is given without a column to classify, or when the column cannot be classified (unknown scheme, no spread, k < 1, or an explicit colour list shorter than the class count).

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def points(
    self,
    features: Any,
    *,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    size: Maybe[float] = UNSET,
    cmap: str = "viridis",
    opacity: float | None = None,
    rasterize: Any = "auto",
    big_data_threshold: int | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a point layer, optionally coloured by an attribute column.

    Args:
        features: A pyramids ``FeatureCollection`` of point geometries; reprojected to the
            display CRS through pyramids when needed. A path or URL naming one is taken too, and is
            the only input a figure carrying this layer can be written down with.
        column: The column colouring the points (also shown on hover). The Core spelling, and the one
            ``polygons`` and ``choropleth`` on this tier already used; ``value_column`` was a second
            name for one concept (#332) and is gone.
        opacity: How opaque the layer is, in ``[0, 1]``. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use, and the one the
            web and 3-D tiers take, so the same channel is written the same way on every tier (#332).
            HoloViews reads it as ``alpha``, which :func:`apply_opacity` is the one place to know.
            ``None`` (default) hands the engine no opacity at all, which is not ``1.0``: it leaves a
            colormap's own alpha channel in force.
        scheme: Optional classification scheme for ``column`` — ``None`` (the default) is a
            continuous ramp, a named ``cleopatra.styling.styles.classify`` scheme
            (``"quantiles"``, ``"equal_interval"``, ``"fisher_jenks"``, …) cuts it into ``k``
            classes, and ``"categorical"`` gives every distinct value its own colour (the same
            unordered-attribute colouring :meth:`choropleth` does, so a point layer and a polygon
            layer key one column the same way). Spelled and computed the same way on every tier that
            classifies. It styles ``column``, so naming a scheme without one is refused rather
            than ignored.
        k: Number of classes a named ``scheme`` is cut into; ignored when ``scheme`` is ``None`` or
            ``"categorical"``.
        size: Marker size in screen pixels — the one thing ``size`` ever means on any tier (#251).
        cmap: Colormap used when ``column`` is given.
        rasterize: ``"auto"`` (default) routes through Datashader above
            ``big_data_threshold`` rows — logged, never silent; ``True``/``False`` force it.
        big_data_threshold: Row count above which ``"auto"`` switches to Datashader; ``None``
            (default) uses the map's ``big_data_threshold`` attribute (#250). Counted off ``features``
            as given, so a path is measured as a string rather than as rows — see the note below.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element. Anything written here **wins**
            over the option a ``scheme`` derived — the same precedence :meth:`choropleth` applies — so
            ``colorbar=False`` drops the colorbar on a classified point layer just as it does on a
            classified polygon one.

    Note:
        ``rasterize="auto"`` counts the **rows**, whether ``features`` is a loaded collection or a path.
        A path used to be measured as a string — a layer named by a 25-character path was reported as
        *25* features when the file held 10, so a ten-row layer routed through Datashader on the strength
        of its filename (#316). pyramids now answers the count without reading the geometry
        (``FeatureCollection.feature_count``, serapeum-org/pyramids#1200, shipped in 0.65.0), so naming a
        file still costs no open and the two spellings of one input agree. The routing log line names the
        number the decision used, so a surprising one is visible rather than silent.

    Examples:
        - Colour gauging stations by an attribute column:
            ```python
            >>> from pyramids.feature import FeatureCollection              # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
            >>> m = InteractiveMap().points(fc, column="fid")         # doctest: +SKIP
            >>> [d.name for d in m.layers[0].vdims]                         # doctest: +SKIP
            ['fid']

            ```

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: if ``scheme`` is given without a ``column`` to classify, or when the
            column cannot be classified (unknown scheme, no spread, ``k < 1``, or an explicit
            colour list shorter than the class count).
    """
    from digitalearth.interactive.builders.bigdata import (
        _feature_count,
        _route_through_rasterize,
    )

    self._require_vector(features, "points")
    apply_opacity(opacity, opts)
    if scheme is not None and not column:
        # A scheme with nothing to classify used to draw plain points and say nothing — a dropped
        # styling request, which is exactly what this tier stopped doing elsewhere (review M2).
        raise ValueError(
            f"{_POINTS_CALLER}: scheme= classifies column=, which was not given; "
            "name the column to classify, or drop scheme="
        )
    threshold = self._resolve_big_data_threshold(
        big_data_threshold, caller=_POINTS_CALLER
    )
    # Nothing here is reprojected: the drawer warps what it draws, and what the description needs — the
    # row count and a column's values — is the same before a warp as after it. Warping here as well did
    # the work twice and threw one result away (review M8). A frame the display CRS cannot place is
    # still refused, by the drawer, and `_skips_off_limb` answers it as before.
    # Counted through `_feature_count`, not `len()`: `features` may be a path, and `len()` of a path is
    # its character count, so the threshold used to be compared against the filename (#316). pyramids reads
    # the count without the geometry, so naming a file still costs no open.
    # Clear any breaks a prior categorical call recorded, as `choropleth` does — above the rasterize
    # early-return as well, so a density layer (which records no class edges) does not keep reporting a
    # prior categorical call's breaks on the legacy `last_breaks` accessor (#332 L3, round-2 M2). Only the
    # categorical and graduated branches below record one; every other path leaves it cleared.
    self.last_breaks = None
    if rasterize is True or (
        rasterize == "auto"
        and _route_through_rasterize("points", _feature_count(features), threshold)
    ):
        aggregator = "mean" if column else "count"
        return self.rasterize(
            features, aggregator=aggregator, column=column, cmap=cmap, **opts
        )
    styling: dict = {}
    labels: dict | None = None
    # What the layer's colour varies with, published beside the engine's own spelling of it so a colour
    # key can hang on the layer rather than on the tier's most recent classification (order 24). `None`
    # while no `column` was given: those points are one flat colour, and a key over them would label
    # nothing.
    colour: Encoding | None = None
    if column and isinstance(scheme, str) and scheme.lower() == "categorical":
        # Categorical colouring works off the string form of the value, so it has to relabel the frame
        # before the element is built — and it is the same relabelling `_categorical_polygons` does, so
        # a point layer and a polygon layer key an unordered column identically (review M3).
        styling, categories, labels = self._categorical_style(
            features, column, cmap=cmap
        )
        self.last_breaks = categories
        colour = Encoding.by_field(
            "color", column, scale=_categorical_scale(styling, categories, labels)
        )
    elif column and scheme is not None:
        styling = self._graduated_style(
            features, column, scheme=scheme, k=k, cmap=cmap
        )
        self.last_breaks = list(styling["color_levels"])
        colour = Encoding.by_field(
            "color", column, scale=_graduated_scale(styling, scheme)
        )
    elif column:
        styling = {"color": column, "cmap": cmap, "colorbar": True}
        # A continuous ramp over the column, with no limits the builder holds: HoloViews measures them
        # from the data at render time unless the caller wrote a `clim` of their own.
        colour = Encoding.by_field(
            "color", column, scale=limits_scale(opts.get("clim"))
        )
    # The caller's `**opts` are split per value: `describe_opts` writes the JSON-safe half into the
    # description and puts the rest in `held` (review M3). Either way the drawer merges them over
    # this, which keeps the precedence: an explicit style the caller wrote outranks the one
    # classification derived, so one scheme cannot mean two things (review M4).
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    # Resolved here rather than at the top of the method, so the aggregating route above — which forwards
    # `**opts` to `rasterize` and never draws a marker — is reached with the keyword untouched.
    ask = Ask()
    common: dict = {"size": ask("size", size, POINT_SIZE), **styling}
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="points",
        source=features,
        held=held,
        symbology=_vector_symbology(
            "Points",
            [column] if column else None,
            describe_style(held, common),
            labels,
            described_opts,
            tuple(ask.named),
            colour,
        ),
    )

lines(features, *, column=None, scheme=None, k=5, cmap='viridis', width=None, opacity=None, name=None, visible=True, **opts) #

Add a line layer (LineString / MultiLineString features), optionally coloured by a column.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of line geometries; reprojected through pyramids when needed.

required
column str | None

The column colouring the lines (also shown on hover); None (default) draws one flat colour. The Core spelling, the same one :meth:points and :meth:polygons use on this tier (#332).

None
scheme Any | None

Optional classification of column — None (the default) is a continuous ramp, a named cleopatra.styling.styles.classify scheme ("quantiles", "equal_interval", "fisher_jenks", …) cuts it into k classes, and "categorical" gives every distinct value its own colour. It styles column, so naming a scheme without one is refused rather than ignored.

None
k int

Number of classes a named scheme is cut into; ignored when scheme is None or "categorical".

5
cmap str

Colormap used when column is given.

'viridis'
width float | None

Line width in screen pixels; None (default) leaves HoloViews' own. HoloViews reads it as line_width, so a bare number is the line's thickness rather than the plot's.

None
opacity float | None

How opaque the layer is, in [0, 1]. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use (#332); HoloViews reads it as alpha through :func:apply_opacity. None (default) hands the engine no opacity at all.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element. Anything written here wins over the option a scheme derived, the same precedence :meth:points applies. A continuous ramp (a column with no scheme) reads clim=(lo, hi) from here to pin its colour range — the spelling :meth:choropleth forwards it under on this tier; without one HoloViews measures the range from the data.

{}

Examples:

  • Draw river reaches as an interactive line layer:
    >>> from pyramids.feature import FeatureCollection              # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> reaches = FeatureCollection.read_file("reaches.geojson")    # doctest: +SKIP
    >>> InteractiveMap().lines(reaches).save("reaches.html").name    # doctest: +SKIP
    'reaches.html'
    

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

if scheme is given without a column to classify, or when the column cannot be classified (unknown scheme, no spread, k < 1, or an explicit colour list shorter than the class count).

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def lines(
    self,
    features: Any,
    *,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    cmap: str = "viridis",
    width: float | None = None,
    opacity: float | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a line layer (LineString / MultiLineString features), optionally coloured by a column.

    Args:
        features: A pyramids ``FeatureCollection`` of line geometries; reprojected through
            pyramids when needed.
        column: The column colouring the lines (also shown on hover); ``None`` (default) draws one
            flat colour. The Core spelling, the same one :meth:`points` and :meth:`polygons` use on
            this tier (#332).
        scheme: Optional classification of ``column`` — ``None`` (the default) is a continuous ramp, a
            named ``cleopatra.styling.styles.classify`` scheme (``"quantiles"``, ``"equal_interval"``,
            ``"fisher_jenks"``, …) cuts it into ``k`` classes, and ``"categorical"`` gives every
            distinct value its own colour. It styles ``column``, so naming a scheme without one is
            refused rather than ignored.
        k: Number of classes a named ``scheme`` is cut into; ignored when ``scheme`` is ``None`` or
            ``"categorical"``.
        cmap: Colormap used when ``column`` is given.
        width: Line width in screen pixels; ``None`` (default) leaves HoloViews' own. HoloViews reads
            it as ``line_width``, so a bare number is the line's thickness rather than the plot's.
        opacity: How opaque the layer is, in ``[0, 1]``. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use (#332);
            HoloViews reads it as ``alpha`` through :func:`apply_opacity`. ``None`` (default) hands the
            engine no opacity at all.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element. Anything written here **wins**
            over the option a ``scheme`` derived, the same precedence :meth:`points` applies. A
            continuous ramp (a ``column`` with no ``scheme``) reads ``clim=(lo, hi)`` from here to pin
            its colour range — the spelling :meth:`choropleth` forwards it under on this tier; without
            one HoloViews measures the range from the data.

    Examples:
        - Draw river reaches as an interactive line layer:
            ```python
            >>> from pyramids.feature import FeatureCollection              # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> reaches = FeatureCollection.read_file("reaches.geojson")    # doctest: +SKIP
            >>> InteractiveMap().lines(reaches).save("reaches.html").name    # doctest: +SKIP
            'reaches.html'

            ```

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: if ``scheme`` is given without a ``column`` to classify, or when the column
            cannot be classified (unknown scheme, no spread, ``k < 1``, or an explicit colour list
            shorter than the class count).
    """
    apply_opacity(opacity, opts)
    if width is not None:
        # HoloViews reads a line's thickness as `line_width`; a bare `width=` is the plot's width.
        opts["line_width"] = width
    if scheme is not None and not column:
        raise ValueError(
            f"{_LINES_CALLER}: scheme= classifies column=, which was not given; "
            "name the column to classify, or drop scheme="
        )
    styling: dict = {}
    labels: dict | None = None
    # What the layer's colour varies with, published beside the engine's own spelling of it so a colour
    # key can hang on the layer (order 24). `None` while no `column` was given: those lines are one flat
    # colour, and a key over them would label nothing.
    colour: Encoding | None = None
    # Clear any breaks a prior categorical call recorded, as `choropleth` does: only the categorical and
    # graduated branches below record class edges, so a flat or continuous layer must not keep reporting
    # stale ones on the legacy `last_breaks` accessor (#332 L3).
    self.last_breaks = None
    if column and isinstance(scheme, str) and scheme.lower() == "categorical":
        styling, categories, labels = self._categorical_style(
            features, column, cmap=cmap
        )
        self.last_breaks = categories
        colour = Encoding.by_field(
            "color", column, scale=_categorical_scale(styling, categories, labels)
        )
    elif column and scheme is not None:
        styling = self._graduated_style(
            features, column, scheme=scheme, k=k, cmap=cmap
        )
        self.last_breaks = list(styling["color_levels"])
        colour = Encoding.by_field(
            "color", column, scale=_graduated_scale(styling, scheme)
        )
    elif column:
        styling = {"color": column, "cmap": cmap, "colorbar": True}
        colour = Encoding.by_field(
            "color", column, scale=limits_scale(opts.get("clim"))
        )
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    common: dict = {**styling}
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="lines",
        source=features,
        held=held,
        symbology=_vector_symbology(
            "Path",
            [column] if column else None,
            describe_style(held, common),
            labels,
            described_opts,
            (),
            colour,
        ),
    )

polygons(features, *, column=None, scheme=None, k=5, cmap='viridis', opacity=None, rasterize='auto', big_data_threshold=None, name=None, visible=True, **opts) #

Add a polygon layer — outlines, a continuous fill, or classified by an attribute column.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of polygon geometries; reprojected through pyramids when needed. A path or URL naming one is taken too, and is the only input a figure carrying this layer can be written down with.

required
opacity float | None

How opaque the layer is, in [0, 1]. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use, and the one the web and 3-D tiers take, so the same channel is written the same way on every tier (#332). HoloViews reads it as alpha, which :func:apply_opacity is the one place to know. None (default) hands the engine no opacity at all, which is not 1.0: it leaves a colormap's own alpha channel in force.

None
column str | None

Optional column filling the polygons (also shown on hover); None draws unfilled outlines.

None
scheme Any | None

Optional classification of column, spelled and computed the way :meth:choropleth and the web tier's polygons do, so the three answer the same call the same way (#331). None (default) is a continuous ramp, a named cleopatra.styling.styles.classify scheme ("quantiles", "equal_interval", "fisher_jenks", …) cuts column into k classes, and "categorical" gives every distinct value its own colour. It styles column, so naming a scheme without one is refused rather than ignored. A classified polygon layer is described as a choropleth on this tier, the same as calling :meth:choropleth — the class edges land on last_breaks and the layer's colour scale.

None
k int

Number of classes a named scheme is cut into; ignored when scheme is None or "categorical". 5 is the shared cross-tier default (#246).

5
cmap str

Colormap used when column is given (a qualitative map is used for "categorical" when left at the default; sampled once per class for a graduated scheme).

'viridis'
rasterize Any

"auto" (default) routes through Datashader above big_data_threshold rows — logged, never silent; True/False force it. Polygon datashading needs the optional spatialpandas package. Not applied to a classified layer (scheme set), which draws raw glyphs so each class keeps its colour — so rasterize=True (force datashade) or an explicit big_data_threshold alongside scheme warns, because that request is dropped. rasterize=False asks for the same raw glyphs and "auto" names no request, so both are silent.

'auto'
big_data_threshold int | None

Row count above which "auto" switches to Datashader; None (default) uses the map's big_data_threshold attribute (#250). Counted off features as given, so a path is measured as a string rather than as rows — see the note below.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}
Note

rasterize="auto" counts the rows, whether features is a loaded collection or a path. A path used to be measured as a string — a layer named by a 25-character path was reported as 25 features when the file held 10, so a ten-row layer routed through Datashader on the strength of its filename (#316). pyramids now answers the count without reading the geometry (FeatureCollection.feature_count, serapeum-org/pyramids#1200, shipped in 0.65.0), so naming a file still costs no open and the two spellings of one input agree. The routing log line names the number the decision used, so a surprising one is visible rather than silent.

Examples:

  • Outline catchment polygons over a basemap:
    >>> from pyramids.feature import FeatureCollection                # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> basins = FeatureCollection.read_file("basins.geojson")        # doctest: +SKIP
    >>> InteractiveMap().polygons(basins).basemap().save("m.html").name  # doctest: +SKIP
    'm.html'
    

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

if scheme is given without a column to classify, or when the column cannot be classified (unknown scheme, no spread, k < 1, or an explicit colour list shorter than the class count).

KeyError

when scheme is given and column is not one of features' columns — named the way :meth:choropleth names it, rather than a bare pandas KeyError from the classifier.

ImportError

when the layer routes through Datashader (rasterize=True, or "auto" above the threshold) and spatialpandas is not installed. It is datashader's own polygon backend, not a Digital-Earth dependency, so the tier says which package to install — or to pass rasterize=False and draw raw glyphs — rather than failing deeper inside datashader.

Warns:

Type Description
UserWarning

when a classified call (scheme set) is also given rasterize=True or an explicit big_data_threshold=, which a classified layer cannot honour (it draws raw glyphs), so the request is dropped rather than silently ignored. rasterize=False is consistent with raw glyphs and does not warn.

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def polygons(
    self,
    features: Any,
    *,
    column: str | None = None,
    scheme: Any | None = None,
    k: int = 5,
    cmap: str = "viridis",
    opacity: float | None = None,
    rasterize: Any = "auto",
    big_data_threshold: int | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a polygon layer — outlines, a continuous fill, or classified by an attribute column.

    Args:
        features: A pyramids ``FeatureCollection`` of polygon geometries; reprojected through
            pyramids when needed. A path or URL naming one is taken too, and is the only input a
            figure carrying this layer can be written down with.
        opacity: How opaque the layer is, in ``[0, 1]``. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use, and the one the
            web and 3-D tiers take, so the same channel is written the same way on every tier (#332).
            HoloViews reads it as ``alpha``, which :func:`apply_opacity` is the one place to know.
            ``None`` (default) hands the engine no opacity at all, which is not ``1.0``: it leaves a
            colormap's own alpha channel in force.
        column: Optional column filling the polygons (also shown on hover); ``None`` draws unfilled
            outlines.
        scheme: Optional classification of ``column``, spelled and computed the way :meth:`choropleth`
            and the web tier's ``polygons`` do, so the three answer the same call the same way (#331).
            ``None`` (default) is a continuous ramp, a named ``cleopatra.styling.styles.classify`` scheme
            (``"quantiles"``, ``"equal_interval"``, ``"fisher_jenks"``, …) cuts ``column`` into ``k``
            classes, and ``"categorical"`` gives every distinct value its own colour. It styles
            ``column``, so naming a scheme without one is refused rather than ignored. A classified
            polygon layer is described as a ``choropleth`` on this tier, the same as calling
            :meth:`choropleth` — the class edges land on ``last_breaks`` and the layer's colour scale.
        k: Number of classes a named ``scheme`` is cut into; ignored when ``scheme`` is ``None`` or
            ``"categorical"``. ``5`` is the shared cross-tier default (#246).
        cmap: Colormap used when ``column`` is given (a qualitative map is used for ``"categorical"``
            when left at the default; sampled once per class for a graduated scheme).
        rasterize: ``"auto"`` (default) routes through Datashader above
            ``big_data_threshold`` rows — logged, never silent; ``True``/``False`` force it.
            Polygon datashading needs the optional ``spatialpandas`` package. Not applied to a classified
            layer (``scheme`` set), which draws raw glyphs so each class keeps its colour — so
            ``rasterize=True`` (force datashade) or an explicit ``big_data_threshold`` alongside
            ``scheme`` **warns**, because that request is dropped. ``rasterize=False`` asks for the same
            raw glyphs and ``"auto"`` names no request, so both are silent.
        big_data_threshold: Row count above which ``"auto"`` switches to Datashader; ``None``
            (default) uses the map's ``big_data_threshold`` attribute (#250). Counted off ``features``
            as given, so a path is measured as a string rather than as rows — see the note below.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Note:
        ``rasterize="auto"`` counts the **rows**, whether ``features`` is a loaded collection or a path.
        A path used to be measured as a string — a layer named by a 25-character path was reported as
        *25* features when the file held 10, so a ten-row layer routed through Datashader on the strength
        of its filename (#316). pyramids now answers the count without reading the geometry
        (``FeatureCollection.feature_count``, serapeum-org/pyramids#1200, shipped in 0.65.0), so naming a
        file still costs no open and the two spellings of one input agree. The routing log line names the
        number the decision used, so a surprising one is visible rather than silent.

    Examples:
        - Outline catchment polygons over a basemap:
            ```python
            >>> from pyramids.feature import FeatureCollection                # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> basins = FeatureCollection.read_file("basins.geojson")        # doctest: +SKIP
            >>> InteractiveMap().polygons(basins).basemap().save("m.html").name  # doctest: +SKIP
            'm.html'

            ```

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: if ``scheme`` is given without a ``column`` to classify, or when the column
            cannot be classified (unknown scheme, no spread, ``k < 1``, or an explicit colour list
            shorter than the class count).
        KeyError: when ``scheme`` is given and ``column`` is not one of ``features``' columns — named
            the way :meth:`choropleth` names it, rather than a bare pandas ``KeyError`` from the
            classifier.
        ImportError: when the layer routes through Datashader (``rasterize=True``, or
            ``"auto"`` above the threshold) and ``spatialpandas`` is not installed. It is
            datashader's own polygon backend, not a Digital-Earth dependency, so the tier says
            which package to install — or to pass ``rasterize=False`` and draw raw glyphs —
            rather than failing deeper inside datashader.

    Warns:
        UserWarning: when a classified call (``scheme`` set) is also given ``rasterize=True`` or an
            explicit ``big_data_threshold=``, which a classified layer cannot honour (it draws raw
            glyphs), so the request is dropped rather than silently ignored. ``rasterize=False`` is
            consistent with raw glyphs and does not warn.
    """
    self._require_vector(features, "polygons")
    apply_opacity(opacity, opts)
    # A classified polygon layer is a choropleth, cut by the very classifier `choropleth` uses (#331).
    # The whole scheme path lives in its own method so this builder stays a thin dispatch.
    if scheme is not None:
        return self._classified_polygons(
            features,
            column=column,
            scheme=scheme,
            k=k,
            cmap=cmap,
            rasterize=rasterize,
            big_data_threshold=big_data_threshold,
            name=name,
            visible=visible,
            **opts,
        )
    threshold = self._resolve_big_data_threshold(
        big_data_threshold, caller="InteractiveMap.polygons()"
    )
    return self._polygon_layer(
        features,
        "polygons",
        column=column,
        cmap=cmap,
        rasterize=rasterize,
        threshold=threshold,
        name=name,
        visible=visible,
        **opts,
    )

choropleth(features, column, *, scheme=None, k=5, cmap='viridis', opacity=None, clim=None, name=None, visible=True, **opts) #

Add a choropleth — polygons filled and coloured by column (hover shows the value).

A thin colour-by-attribute :meth:polygons, mirroring the static Map.choropleth. Pass scheme="categorical" to colour an unordered attribute by distinct value instead of a continuous ramp (DC.8), or a graduated scheme ("quantiles"/"equal_interval"/"fisher_jenks"/…) to classify a numeric column into k flat classes. Either way the categories or class edges are published on the layer's own colour encoding, as the :class:~digitalearth.base.spec.scale.Scale it was classified through — which is what :meth:colorbar and :meth:legend hang their key on (order 24) and what :meth:~digitalearth.base.spec.legend.LegendSpec.from_scale derives a swatch list from. They are recorded on last_breaks as well, which keeps the caller's own category values (the scale colours by their string form) and stays the raw-numbers accessor the web tier also publishes.

Graduated classification goes through :class:~digitalearth.base.spec.scale.Scale — the one place every tier reaches the classifier — so the same column/scheme/k yields the same breaks on every tier. Note the default scheme still differs: this interactive tier (like the static Map.choropleth) defaults to a continuous ramp, whereas the web choropleth is graduated-by-default ("quantiles"). Pass scheme explicitly for identical classification.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of polygon geometries; reprojected through pyramids when needed. A path or URL naming one is taken too, and is the only input a figure carrying this layer can be written down with.

required
column str

The column driving the fill colour (required); numeric for the continuous ramp, or any hashable value for scheme="categorical".

required
scheme str | None

"categorical" for distinct-value colouring; a graduated scheme name (or an explicit sequence of class edges) for classified colouring; None (default) for a continuous ramp.

None
k int

Number of classes for a graduated scheme (ignored by "categorical"/None); 5 is the shared cross-tier default (#246).

5
cmap str

Colormap name (a qualitative map such as "tab10" is used for the categorical scheme when left at the default); sampled once per class for a graduated scheme.

'viridis'
opacity float | None

How opaque the layer is, in [0, 1]. The spelling :data:~digitalearth.base.spec.encoding.CHANNELS and the Core contract use, and the one the web and 3-D tiers take, so the same channel is written the same way on every tier (#332). HoloViews reads it as alpha, which :func:apply_opacity is the one place to know. None (default) hands the engine no opacity at all, which is not 1.0: it leaves a colormap's own alpha channel in force.

None
clim tuple[float, float] | None

Optional (vmin, vmax) colour limits for the continuous ramp; None auto-scales.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Examples:

  • Fill polygons by a population column with fixed colour limits:
    >>> from pyramids.feature import FeatureCollection              # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> admin = FeatureCollection.read_file("admin.geojson")        # doctest: +SKIP
    >>> m = InteractiveMap().choropleth(admin, "pop", clim=(0, 1e6))  # doctest: +SKIP
    >>> [d.name for d in m.layers[0].vdims]                         # doctest: +SKIP
    ['pop']
    

Raises:

Type Description
KeyError

when column is not a column of features.

ValueError

when a graduated scheme cannot classify column (unknown scheme name, a constant column, k < 1, …).

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def choropleth(
    self,
    features: Any,
    column: str,
    *,
    scheme: str | None = None,
    k: int = 5,
    cmap: str = "viridis",
    opacity: float | None = None,
    clim: tuple[float, float] | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a choropleth — polygons filled and coloured by ``column`` (hover shows the value).

    A thin colour-by-attribute :meth:`polygons`, mirroring the static ``Map.choropleth``. Pass
    ``scheme="categorical"`` to colour an unordered attribute by distinct value instead of a continuous
    ramp (DC.8), or a **graduated** scheme (``"quantiles"``/``"equal_interval"``/``"fisher_jenks"``/…)
    to classify a numeric column into ``k`` flat classes. Either way the categories or class edges are
    published on the layer's own colour encoding, as the :class:`~digitalearth.base.spec.scale.Scale` it
    was classified through — which is what :meth:`colorbar` and :meth:`legend` hang their key on (order
    24) and what :meth:`~digitalearth.base.spec.legend.LegendSpec.from_scale` derives a swatch list from.
    They are recorded on ``last_breaks`` as well, which keeps the caller's own category values (the scale
    colours by their string form) and stays the raw-numbers accessor the web tier also publishes.

    Graduated classification goes through :class:`~digitalearth.base.spec.scale.Scale` — the one place
    every tier reaches the classifier — so the same ``column``/``scheme``/``k`` yields the same breaks on
    every tier. Note the *default* ``scheme`` still differs: this interactive tier (like the static
    ``Map.choropleth``) defaults to a **continuous** ramp, whereas the **web** ``choropleth`` is
    graduated-by-default (``"quantiles"``). Pass ``scheme`` explicitly for identical classification.

    Args:
        features: A pyramids ``FeatureCollection`` of polygon geometries; reprojected through
            pyramids when needed. A path or URL naming one is taken too, and is the only input a
            figure carrying this layer can be written down with.
        column: The column driving the fill colour (required); numeric for the continuous ramp, or any
            hashable value for ``scheme="categorical"``.
        scheme: ``"categorical"`` for distinct-value colouring; a graduated scheme name (or an explicit
            sequence of class edges) for classified colouring; ``None`` (default) for a continuous ramp.
        k: Number of classes for a graduated ``scheme`` (ignored by ``"categorical"``/``None``);
            ``5`` is the shared cross-tier default (#246).
        cmap: Colormap name (a qualitative map such as ``"tab10"`` is used for the categorical scheme when
            left at the default); sampled once per class for a graduated scheme.
        opacity: How opaque the layer is, in ``[0, 1]``. The spelling
            :data:`~digitalearth.base.spec.encoding.CHANNELS` and the Core contract use, and the one the
            web and 3-D tiers take, so the same channel is written the same way on every tier (#332).
            HoloViews reads it as ``alpha``, which :func:`apply_opacity` is the one place to know.
            ``None`` (default) hands the engine no opacity at all, which is not ``1.0``: it leaves a
            colormap's own alpha channel in force.
        clim: Optional ``(vmin, vmax)`` colour limits for the continuous ramp; ``None`` auto-scales.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.

    Examples:
        - Fill polygons by a population column with fixed colour limits:
            ```python
            >>> from pyramids.feature import FeatureCollection              # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> admin = FeatureCollection.read_file("admin.geojson")        # doctest: +SKIP
            >>> m = InteractiveMap().choropleth(admin, "pop", clim=(0, 1e6))  # doctest: +SKIP
            >>> [d.name for d in m.layers[0].vdims]                         # doctest: +SKIP
            ['pop']

            ```

    Raises:
        KeyError: when ``column`` is not a column of ``features``.
        ValueError: when a graduated ``scheme`` cannot classify ``column`` (unknown scheme name, a
            constant column, ``k < 1``, …).
    """
    self._require_vector(features, "choropleth")
    if column not in getattr(features, "columns", [column]):
        raise KeyError(
            f"choropleth column {column!r} not found in the feature attributes"
        )
    apply_opacity(opacity, opts)
    if isinstance(scheme, str) and scheme.lower() == "categorical":
        return self._categorical_polygons(
            features, column, cmap=cmap, name=name, visible=visible, **opts
        )
    if scheme is not None:
        if clim is not None:
            opts = {"clim": clim, **opts}
        return self._graduated_polygons(
            features,
            column,
            scheme=scheme,
            k=k,
            cmap=cmap,
            name=name,
            visible=visible,
            **opts,
        )
    # Continuous ramp: no discrete breaks — clear any recorded from a prior categorical call.
    self.last_breaks = None
    if clim is not None:
        opts = {"clim": clim, **opts}
    # Resolved here rather than by `polygons()`, which never sees the keyword: `choropleth` takes it
    # through `**opts`.
    threshold = self._resolve_big_data_threshold(
        opts.pop("big_data_threshold", None),
        caller="InteractiveMap.choropleth()",
    )
    return self._polygon_layer(
        features,
        "choropleth",
        column=column,
        cmap=cmap,
        rasterize=opts.pop("rasterize", "auto"),
        threshold=threshold,
        name=name,
        visible=visible,
        **opts,
    )

hexbin(features, *, gridsize=30, aggregator='mean', column=None, cmap='viridis', name=None, visible=True, **opts) #

Add an equal-area hex-bin density layer (honest no-overplot density, recipe I7).

Parameters:

Name Type Description Default
features Any

A point FeatureCollection; reprojected through pyramids.

required
gridsize int

Number of hexagons across — higher is finer.

30
aggregator str

Per-bin reducer ("count"/"mean"/"sum"/…); "count" ignores column.

'mean'
column str | None

Value column aggregated per bin (required for non-count aggregators).

None
cmap str

Colormap name.

'viridis'
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def hexbin(
    self,
    features: Any,
    *,
    gridsize: int = 30,
    aggregator: str = "mean",
    column: str | None = None,
    cmap: str = "viridis",
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add an equal-area hex-bin density layer (honest no-overplot density, recipe I7).

    Args:
        features: A point ``FeatureCollection``; reprojected through pyramids.
        gridsize: Number of hexagons across — higher is finer.
        aggregator: Per-bin reducer (``"count"``/``"mean"``/``"sum"``/…); ``"count"`` ignores
            ``column``.
        column: Value column aggregated per bin (required for non-``count`` aggregators).
        cmap: Colormap name.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.
    """
    _require_holoviz()
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="heatmap",
        source=features,
        held=held,
        symbology=Symbology(
            props={
                "via": "hexbin",
                "gridsize": gridsize,
                "aggregator": aggregator,
                "column": column,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "opts": described_opts,
            }
        ),
    )

kde(features, *, filled=True, cmap='viridis', name=None, visible=True, **opts) #

Add a 2-D kernel-density layer of point positions (parity with Map.kde, recipe I7).

Parameters:

Name Type Description Default
features Any

A point FeatureCollection; reprojected through pyramids.

required
filled bool

Fill the density bands (True) or draw contour lines (False).

True
cmap str

Colormap name.

'viridis'
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def kde(
    self,
    features: Any,
    *,
    filled: bool = True,
    cmap: str = "viridis",
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a 2-D kernel-density layer of point positions (parity with ``Map.kde``, recipe I7).

    Args:
        features: A point ``FeatureCollection``; reprojected through pyramids.
        filled: Fill the density bands (``True``) or draw contour lines (``False``).
        cmap: Colormap name.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.
    """
    _require_holoviz()
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="heatmap",
        source=features,
        held=held,
        symbology=Symbology(
            props={
                "via": "kde",
                "filled": filled,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "opts": described_opts,
            }
        ),
    )

flow(nodes, edges, *, weight=None, name=None, visible=True, **opts) #

Spatial-flow alias of :meth:graph mirroring Map.sankey's framing (DI.15).

Parameters:

Name Type Description Default
nodes Any

A point FeatureCollection of flow endpoints.

required
edges Any

(src_id, dst_id[, weight]) tuples.

required
weight str | None

Optional flow-magnitude column.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the figure is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden, so a switcher reading the figure agrees with the drawing (#327).

True
**opts Any

Forwarded to :meth:graph.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/builders/vector.py
def flow(
    self,
    nodes: Any,
    edges: Any,
    *,
    weight: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Spatial-flow alias of :meth:`graph` mirroring ``Map.sankey``'s framing (DI.15).

    Args:
        nodes: A point ``FeatureCollection`` of flow endpoints.
        edges: ``(src_id, dst_id[, weight])`` tuples.
        weight: Optional flow-magnitude column.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the figure is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden, so a switcher reading the figure agrees with the drawing (#327).
        **opts: Forwarded to :meth:`graph`.

    Returns:
        The same map instance, so builder calls chain.
    """
    return self.graph(
        nodes, edges, weight=weight, name=name, visible=visible, **opts
    )

vectorfield(u, v, *, band=DEFAULT_BAND, density=1.0, color_by='magnitude', cmap='viridis', name=None, visible=True, **opts) #

Add a u/v vector field as interactive arrows (parity with Map.quiver, recipe I6).

Parameters:

Name Type Description Default
u Any

Eastward-component Dataset / Source; reprojected through pyramids.

required
v Any

Northward-component Dataset / Source on the same grid.

required
band int

1-based band read from each component.

DEFAULT_BAND
density float

Keep-fraction in (0, 1] controlling arrow density (1.0 = every cell).

1.0
color_by str | None

"magnitude" colours arrows by speed; None draws uniform arrows.

'magnitude'
cmap str

Colormap used when color_by="magnitude".

'viridis'
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when density is not in (0, 1].

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def vectorfield(
    self,
    u: Any,
    v: Any,
    *,
    band: int = DEFAULT_BAND,
    density: float = 1.0,
    color_by: str | None = "magnitude",
    cmap: str = "viridis",
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a u/v vector field as interactive arrows (parity with ``Map.quiver``, recipe I6).

    Args:
        u: Eastward-component ``Dataset`` / ``Source``; reprojected through pyramids.
        v: Northward-component ``Dataset`` / ``Source`` on the same grid.
        band: 1-based band read from each component.
        density: Keep-fraction in ``(0, 1]`` controlling arrow density (``1.0`` = every cell).
        color_by: ``"magnitude"`` colours arrows by speed; ``None`` draws uniform arrows.
        cmap: Colormap used when ``color_by="magnitude"``.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: when ``density`` is not in ``(0, 1]``.
    """
    _require_holoviz()
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="vectors",
        # The pair is the source: a field is not drawable from either component alone.
        source=(u, v),
        held=held,
        symbology=Symbology(
            props={
                "via": "vectorfield",
                "band": band,
                "density": density,
                "color_by": color_by,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "opts": described_opts,
            }
        ),
    )

barbs(u, v, *, band=DEFAULT_BAND, density=1.0, name=None, visible=True, **opts) #

Add wind barbs of a u/v field — matplotlib backend only (parity with Map.barbs).

gv.WindBarbs has no Bokeh renderer, so barbs are a static matplotlib layer; this logs that they are non-interactive rather than silently producing an empty Bokeh layer.

Parameters:

Name Type Description Default
u Any

Eastward-component Dataset / Source; reprojected through pyramids.

required
v Any

Northward-component Dataset / Source on the same grid.

required
band int

1-based band read from each component.

DEFAULT_BAND
density float

Keep-fraction in (0, 1] subsampling the field before drawing barbs (same meaning as :meth:vectorfield's density; 1.0 keeps every cell).

1.0
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ImportError

when the installed GeoViews has no WindBarbs element.

ValueError

when density is not in (0, 1].

Source code in src/digitalearth/interactive/builders/vector.py
def barbs(
    self,
    u: Any,
    v: Any,
    *,
    band: int = DEFAULT_BAND,
    density: float = 1.0,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add wind barbs of a u/v field — **matplotlib backend only** (parity with ``Map.barbs``).

    ``gv.WindBarbs`` has no Bokeh renderer, so barbs are a static matplotlib layer; this logs
    that they are non-interactive rather than silently producing an empty Bokeh layer.

    Args:
        u: Eastward-component ``Dataset`` / ``Source``; reprojected through pyramids.
        v: Northward-component ``Dataset`` / ``Source`` on the same grid.
        band: 1-based band read from each component.
        density: Keep-fraction in ``(0, 1]`` subsampling the field before drawing barbs (same
            meaning as :meth:`vectorfield`'s ``density``; ``1.0`` keeps every cell).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ImportError: when the installed GeoViews has no ``WindBarbs`` element.
        ValueError: when ``density`` is not in ``(0, 1]``.
    """
    from loguru import logger

    gv, _ = _require_holoviz()
    # Refused here, because the message answers the builder the caller called.
    if not hasattr(gv, "WindBarbs"):
        raise ImportError(
            "barbs need gv.WindBarbs (GeoViews ≥1.11 with the matplotlib backend); it is "
            "absent in this GeoViews build"
        )
    logger.info(
        "barbs render through the matplotlib backend only (Bokeh has no wind-barb glyph); "
        "save to a .png, not interactive .html — a vector file is the static tier's (Map)"
    )
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="vectors",
        source=(u, v),
        held=held,
        symbology=Symbology(
            props={
                "via": "barbs",
                "band": band,
                "density": density,
                "opts": described_opts,
            }
        ),
    )

streamlines(u, v, *, band=DEFAULT_BAND, density=1.0, name=None, visible=True, **opts) #

Add streamlines of a u/v field via the matplotlib backend (parity with Map.streamplot).

Bokeh has no streamline integrator, so streamlines render through HoloViews' matplotlib backend (a static layer in the saved PNG). The element is built so save("x.png") works; it is logged as non-interactive rather than emitting an empty Bokeh layer.

Parameters:

Name Type Description Default
u Any

Eastward-component Dataset / Source; reprojected through pyramids.

required
v Any

Northward-component Dataset / Source on the same grid.

required
band int

1-based band read from each component.

DEFAULT_BAND
density float

Keep-fraction in (0, 1] subsampling the field before streamline integration (same meaning as :meth:vectorfield's density).

1.0
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when density is not in (0, 1].

Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def streamlines(
    self,
    u: Any,
    v: Any,
    *,
    band: int = DEFAULT_BAND,
    density: float = 1.0,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add streamlines of a u/v field via the matplotlib backend (parity with ``Map.streamplot``).

    Bokeh has no streamline integrator, so streamlines render through HoloViews' matplotlib
    backend (a static layer in the saved PNG). The element is built so ``save("x.png")`` works;
    it is logged as non-interactive rather than emitting an empty Bokeh layer.

    Args:
        u: Eastward-component ``Dataset`` / ``Source``; reprojected through pyramids.
        v: Northward-component ``Dataset`` / ``Source`` on the same grid.
        band: 1-based band read from each component.
        density: Keep-fraction in ``(0, 1]`` subsampling the field before streamline
            integration (same meaning as :meth:`vectorfield`'s ``density``).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: when ``density`` is not in ``(0, 1]``.
    """
    from loguru import logger

    _require_holoviz()
    logger.info(
        "streamlines render through the matplotlib backend (Bokeh has no streamline glyph); "
        "save to a .png, not interactive .html — a vector file is the static tier's (Map)"
    )
    held: dict[str, Any] = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="streamlines",
        source=(u, v),
        held=held,
        symbology=Symbology(
            props={
                "via": "streamlines",
                "band": band,
                "density": density,
                "opts": described_opts,
            }
        ),
    )

trimesh(data, *, value_column=None, rasterize='auto', big_data_threshold=None, cmap='viridis', name=None, visible=True, **opts) #

Add an unstructured triangular mesh (parity with Map.tricontour/tripcolor, recipe I7).

Connectivity comes from one of two sources, both pyramids-fed:

  • a true UGRID mesh (pyramids.netcdf.ugrid.Mesh2d — anything exposing node_x / node_y / fan_triangles): nodes + triangles are taken straight off it, no triangulation needed;
  • a point FeatureCollection: Delaunay-triangulated locally with matplotlib.tri (matplotlib is not a forbidden GIS engine), mirroring the static tri* path.

Above big_data_threshold faces the mesh auto-rasterizes to a density image (logged).

Parameters:

Name Type Description Default
data Any

A UGRID-mesh object or a point FeatureCollection (reprojected via pyramids).

required
value_column str | None

Node-value column (for the FeatureCollection path) driving the colour.

None
rasterize Any

"auto" (default) rasterizes above the threshold; True/False force it.

'auto'
big_data_threshold int | None

Face count above which "auto" rasterizes; None (default) uses the map's big_data_threshold attribute (#250).

None
cmap str

Colormap name.

'viridis'
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
TypeError

when data is a pyramids raster. trimesh takes a UGRID mesh or a point collection, so it uses the raster-only guard (:meth:_reject_raster) — a mesh exposing node_x/node_y rather than geometry passes, a raster is turned away naming the builder and the raster entry points (#175).

Examples:

  • Delaunay-triangulate scattered points; the nodes carry the value column:
    >>> from pyramids.feature import FeatureCollection                # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
    >>> m = InteractiveMap().trimesh(fc, value_column="fid")          # doctest: +SKIP
    >>> len(m.layers[0].nodes) == len(fc)                             # doctest: +SKIP
    True
    >>> [d.name for d in m.layers[0].nodes.vdims]                     # doctest: +SKIP
    ['fid']
    
  • A UGRID mesh brings its own connectivity, so nothing is triangulated locally — its four nodes and two faces come through as they are:
    >>> import numpy as np                                            # doctest: +SKIP
    >>> from pyramids.netcdf.ugrid import Connectivity, Mesh2d        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> mesh = Mesh2d(                                                # doctest: +SKIP
    ...     node_x=np.array([0.0, 1.0, 0.5, 1.5]),
    ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
    ...     face_node_connectivity=Connectivity(
    ...         data=np.array([[0, 1, 2], [1, 3, 2]]),
    ...         fill_value=-1,
    ...         cf_role="face_node_connectivity",
    ...         original_start_index=0,
    ...     ),
    ... )
    >>> len(InteractiveMap().trimesh(mesh).layers[0].nodes)           # doctest: +SKIP
    4
    
  • Lowering the cutoff routes the same mesh through Datashader instead, and the density image is styled (and recorded) with the cmap that was asked for:
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> m = InteractiveMap()                                          # doctest: +SKIP
    >>> m = m.trimesh(fc, big_data_threshold=1, cmap="magma")         # doctest: +SKIP
    >>> m.layer_styles[0]["common"]["cmap"]                           # doctest: +SKIP
    'magma'
    >>> m.layer_styles[0]["common"]["colorbar"]                       # doctest: +SKIP
    True
    
Source code in src/digitalearth/interactive/builders/vector.py
@_skips_off_limb
def trimesh(
    self,
    data: Any,
    *,
    value_column: str | None = None,
    rasterize: Any = "auto",
    big_data_threshold: int | None = None,
    cmap: str = "viridis",
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add an unstructured triangular mesh (parity with ``Map.tricontour``/``tripcolor``, recipe I7).

    Connectivity comes from one of two sources, both pyramids-fed:

    - a **true UGRID mesh** (``pyramids.netcdf.ugrid.Mesh2d`` — anything exposing ``node_x`` /
      ``node_y`` / ``fan_triangles``): nodes + triangles are taken straight off it, no
      triangulation needed;
    - a **point** ``FeatureCollection``: Delaunay-triangulated locally with ``matplotlib.tri``
      (matplotlib is not a forbidden GIS engine), mirroring the static ``tri*`` path.

    Above ``big_data_threshold`` faces the mesh auto-``rasterize``s to a density image (logged).

    Args:
        data: A UGRID-mesh object or a point ``FeatureCollection`` (reprojected via pyramids).
        value_column: Node-value column (for the FeatureCollection path) driving the colour.
        rasterize: ``"auto"`` (default) rasterizes above the threshold; ``True``/``False`` force it.
        big_data_threshold: Face count above which ``"auto"`` rasterizes; ``None`` (default) uses
            the map's ``big_data_threshold`` attribute (#250).
        cmap: Colormap name.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        TypeError: when ``data`` is a pyramids raster. ``trimesh`` takes a UGRID mesh or a point
            collection, so it uses the raster-only guard (:meth:`_reject_raster`) — a mesh exposing
            ``node_x``/``node_y`` rather than ``geometry`` passes, a raster is turned away naming the
            builder and the raster entry points (#175).

    Examples:
        - Delaunay-triangulate scattered points; the nodes carry the value column:
            ```python
            >>> from pyramids.feature import FeatureCollection                # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
            >>> m = InteractiveMap().trimesh(fc, value_column="fid")          # doctest: +SKIP
            >>> len(m.layers[0].nodes) == len(fc)                             # doctest: +SKIP
            True
            >>> [d.name for d in m.layers[0].nodes.vdims]                     # doctest: +SKIP
            ['fid']

            ```
        - A UGRID mesh brings its own connectivity, so nothing is triangulated locally — its
          four nodes and two faces come through as they are:
            ```python
            >>> import numpy as np                                            # doctest: +SKIP
            >>> from pyramids.netcdf.ugrid import Connectivity, Mesh2d        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> mesh = Mesh2d(                                                # doctest: +SKIP
            ...     node_x=np.array([0.0, 1.0, 0.5, 1.5]),
            ...     node_y=np.array([0.0, 0.0, 1.0, 1.0]),
            ...     face_node_connectivity=Connectivity(
            ...         data=np.array([[0, 1, 2], [1, 3, 2]]),
            ...         fill_value=-1,
            ...         cf_role="face_node_connectivity",
            ...         original_start_index=0,
            ...     ),
            ... )
            >>> len(InteractiveMap().trimesh(mesh).layers[0].nodes)           # doctest: +SKIP
            4

            ```
        - Lowering the cutoff routes the same mesh through Datashader instead, and the
          density image is styled (and recorded) with the ``cmap`` that was asked for:
            ```python
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> m = InteractiveMap()                                          # doctest: +SKIP
            >>> m = m.trimesh(fc, big_data_threshold=1, cmap="magma")         # doctest: +SKIP
            >>> m.layer_styles[0]["common"]["cmap"]                           # doctest: +SKIP
            'magma'
            >>> m.layer_styles[0]["common"]["colorbar"]                       # doctest: +SKIP
            True

            ```
    """
    self._reject_raster(data, "trimesh")
    gv, _ = _require_holoviz()
    threshold = self._resolve_big_data_threshold(
        big_data_threshold, caller="InteractiveMap.trimesh()"
    )
    # The mesh is built here because the routing decision below is made on the face count, which only the
    # built connectivity knows. The drawer would build the same one again from the same data, so the one
    # built here is handed to it for the length of this call (review M8).
    built = self._mesh_inputs(data, value_column)
    nodes, simplices, _ = built
    n_faces = len(simplices)
    if rasterize is True or (rasterize == "auto" and n_faces > threshold):
        from loguru import logger

        if rasterize == "auto":
            logger.info(
                f"trimesh: {n_faces:,} faces exceed big_data_threshold={threshold:,}"
                " — rasterizing the mesh to a density image"
            )
        trimesh = gv.TriMesh((simplices, nodes), crs=gv.util.process_crs(self.crs))
        return self.rasterize(
            trimesh, dynamic=True, cmap=cmap, name=name, visible=visible, **opts
        )
    self._built_mesh = (data, value_column, built)
    try:
        held: dict[str, Any] = {}
        described_opts = describe_opts(held, opts)
        return self.add_layer(
            None,
            name=name,
            visible=visible,
            kind="unstructured",
            source=data,
            held=held,
            symbology=Symbology(
                props={
                    "via": "trimesh",
                    "value_column": value_column,
                    "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                    "opts": described_opts,
                }
            ),
        )
    finally:
        # Released as soon as the layer is drawn: holding it would keep the mesh alive for as long as the
        # map, and a later draw from the description must build its own.
        self._built_mesh = None

labels(features, column, *, crs=4326, name=None, visible=True, **opts) #

Add per-feature text labels from a point FeatureCollection column.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection of point geometries; reprojected to the display CRS through pyramids when needed.

required
column str

The attribute column whose values are drawn as labels.

required
crs Any

Unused when features carries its own CRS (kept for signature symmetry with :meth:text); reprojection goes through FeatureCollection.to_crs.

4326
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
KeyError

when column is not a column of features.

Source code in src/digitalearth/interactive/decoration/decoration.py
@_skips_off_limb
def labels(
    self,
    features: Any,
    column: str,
    *,
    crs: Any = 4326,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add per-feature text labels from a point ``FeatureCollection`` column.

    Args:
        features: A pyramids ``FeatureCollection`` of point geometries; reprojected to the
            display CRS through pyramids when needed.
        column: The attribute column whose values are drawn as labels.
        crs: Unused when ``features`` carries its own CRS (kept for signature symmetry with
            :meth:`text`); reprojection goes through ``FeatureCollection.to_crs``.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        KeyError: when ``column`` is not a column of ``features``.
    """
    _require_holoviz()
    # Refused here, because the message names the column the caller asked for.
    if column not in getattr(features, "columns", [column]):
        raise KeyError(
            f"labels column {column!r} not found in the feature attributes"
        )
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="labels",
        source=features,
        held=held,
        symbology=Symbology(
            props={"via": "labels", "column": column, "opts": described_opts}
        ),
    )

text(lon, lat, s, *, crs=4326, name=None, visible=True, **opts) #

Add a single text annotation at (lon, lat) (reprojected to the display CRS).

Parameters:

Name Type Description Default
lon Any

X / longitude of the label anchor, in crs.

required
lat Any

Y / latitude of the label anchor, in crs.

required
s str

The text to draw.

required
crs Any

CRS of lon/lat (default EPSG:4326); reprojected to the display CRS via pyramids.

4326
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/decoration/decoration.py
def text(
    self,
    lon: Any,
    lat: Any,
    s: str,
    *,
    crs: Any = 4326,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a single text annotation at ``(lon, lat)`` (reprojected to the display CRS).

    Args:
        lon: X / longitude of the label anchor, in ``crs``.
        lat: Y / latitude of the label anchor, in ``crs``.
        s: The text to draw.
        crs: CRS of ``lon``/``lat`` (default EPSG:4326); reprojected to the display CRS via
            pyramids.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the element.

    Returns:
        The same map instance, so builder calls chain.
    """
    _require_holoviz()
    # Reprojected here, because `crs=` is the caller's own argument and this is where it is answered;
    # the element itself is built by `draw_text` from the display coordinates this records.
    (x,), (y,) = self._to_display_xy(lon, lat, crs)
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="text",
        held=held,
        symbology=Symbology(
            props={
                "via": "text",
                "x": float(x),
                "y": float(y),
                "s": s,
                "opts": described_opts,
            }
        ),
    )

timecube(collection, *, kdim='time', labels=None, band=DEFAULT_BAND, cmap=None, clim=None, colorbar=True, name=None, visible=True, **opts) #

Render a DatasetCollection as an interactive time-slider map.

Builds an hv.DynamicMap whose frame(t) constructs an I1 hv.Image from the t-th member; redim.values drives a Bokeh slider. The colour range is frozen across frames so the colorbar is identical on the first and last frame.

Parameters:

Name Type Description Default
collection Any

A pyramids DatasetCollection whose members are ordered time steps.

required
kdim str

Slider dimension name.

'time'
labels Sequence | None

Optional per-member labels (e.g. datetimes) shown on the slider instead of the integer index; must match the member count.

None
band int

1-based band rendered in every frame.

DEFAULT_BAND
cmap str | None

Colormap name; None (default) resolves it from the variable through autostyle.auto_style (#249), exactly as field does.

None
clim tuple[float, float] | None

Frozen (vmin, vmax) colour limits; None computes one range for the whole series once, from at most :data:~digitalearth.base.clim.DEFAULT_CLIM_SCAN_CAP members sampled evenly across it.

None
colorbar bool

Whether to draw a colorbar.

True
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to every frame.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain — one DynamicMap layer is registered.

Raises:

Type Description
ValueError

when labels is given but its length differs from the member count, or two of its entries are equal — duplicate keys collapse the slider and make the matching frames unreachable.

Examples:

  • Scrub a 3-step collection with a frozen colour range:
    >>> from pyramids.dataset.collection import DatasetCollection  # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dc = DatasetCollection.from_files(["a.tif", "b.tif"])      # doctest: +SKIP
    >>> m = InteractiveMap().timecube(dc, cmap="inferno")          # doctest: +SKIP
    >>> [d.name for d in m.layers[0].kdims]                        # doctest: +SKIP
    ['time']
    
  • Label the slider with real datetimes:
    >>> import datetime as dt                                     # doctest: +SKIP
    >>> from pyramids.dataset.collection import DatasetCollection  # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dc = DatasetCollection.from_files(["a.tif", "b.tif"])      # doctest: +SKIP
    >>> stamps = [dt.datetime(2020, 1, 1), dt.datetime(2020, 1, 2)]  # doctest: +SKIP
    >>> m = InteractiveMap().timecube(dc, labels=stamps)          # doctest: +SKIP
    >>> m.save("t.html").name                                     # doctest: +SKIP
    't.html'
    
Source code in src/digitalearth/interactive/temporal/temporal.py
@_skips_off_limb
def timecube(
    self,
    collection: Any,
    *,
    kdim: str = "time",
    labels: Sequence | None = None,
    band: int = DEFAULT_BAND,
    cmap: str | None = None,
    clim: tuple[float, float] | None = None,
    colorbar: bool = True,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Render a ``DatasetCollection`` as an interactive time-slider map.

    Builds an ``hv.DynamicMap`` whose ``frame(t)`` constructs an I1 ``hv.Image`` from the *t*-th
    member; ``redim.values`` drives a Bokeh slider. The colour range is frozen across frames so
    the colorbar is identical on the first and last frame.

    Args:
        collection: A pyramids ``DatasetCollection`` whose members are ordered time steps.
        kdim: Slider dimension name.
        labels: Optional per-member labels (e.g. datetimes) shown on the slider instead of the
            integer index; must match the member count.
        band: 1-based band rendered in every frame.
        cmap: Colormap name; ``None`` (default) resolves it from the variable through
            ``autostyle.auto_style`` (#249), exactly as ``field`` does.
        clim: Frozen ``(vmin, vmax)`` colour limits; ``None`` computes one range for the whole series
            once, from at most :data:`~digitalearth.base.clim.DEFAULT_CLIM_SCAN_CAP` members sampled
            evenly across it.
        colorbar: Whether to draw a colorbar.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to every frame.

    Returns:
        The same map instance, so builder calls chain — one ``DynamicMap`` layer is registered.

    Raises:
        ValueError: when ``labels`` is given but its length differs from the member count, or two of
            its entries are equal — duplicate keys collapse the slider and make the matching frames
            unreachable.

    Examples:
        - Scrub a 3-step collection with a frozen colour range:
            ```python
            >>> from pyramids.dataset.collection import DatasetCollection  # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> dc = DatasetCollection.from_files(["a.tif", "b.tif"])      # doctest: +SKIP
            >>> m = InteractiveMap().timecube(dc, cmap="inferno")          # doctest: +SKIP
            >>> [d.name for d in m.layers[0].kdims]                        # doctest: +SKIP
            ['time']

            ```
        - Label the slider with real datetimes:
            ```python
            >>> import datetime as dt                                     # doctest: +SKIP
            >>> from pyramids.dataset.collection import DatasetCollection  # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> dc = DatasetCollection.from_files(["a.tif", "b.tif"])      # doctest: +SKIP
            >>> stamps = [dt.datetime(2020, 1, 1), dt.datetime(2020, 1, 2)]  # doctest: +SKIP
            >>> m = InteractiveMap().timecube(dc, labels=stamps)          # doctest: +SKIP
            >>> m.save("t.html").name                                     # doctest: +SKIP
            't.html'

            ```
    """
    _require_holoviz()
    # Both refusals stay with the builder: each names the `labels` the caller wrote.
    n = len(collection.datasets)
    if labels is not None:
        if len(labels) != n:
            raise ValueError(
                f"labels has {len(labels)} entries but the collection has {n} members"
            )
        if len(set(labels)) != n:
            raise ValueError(
                "timecube labels must be unique — duplicate labels collapse the slider and "
                "make the matching frames unreachable"
            )
    kept = None if labels is None else list(labels)
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="raster",
        source=collection,
        held=held,
        symbology=Symbology(
            props={
                "via": "timecube",
                "kdim": kdim,
                # A slider's labels are usually timestamps, which JSON has no spelling for: the
                # originals are held beside the layer and the description keeps them as ISO strings,
                # which is what a reader without the objects slides through (review M9).
                "labels": describe(held, "labels", kept, _iso_labels(kept)),
                "band": band,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                # Normalised to the spelling a figure can be written with, as `field` records it:
                # the documented `(low, high)` is a tuple, and a tuple is exactly what
                # `travels_in_a_figure` refuses — so the documented form was held beside the layer and
                # dropped from every saved figure while the undocumented list form travelled
                # (review R2-M13). The cost here is worse than a restyle: a reloaded cube with no
                # `clim` sends `draw_timecube` back to `_global_clim`, which rescans the members to
                # invent one, so the figure both looks different and pays for the scan this keyword
                # was passed to avoid.
                "clim": describe(held, "clim", _travelling_pair(clim)),
                "colorbar": colorbar,
                "opts": described_opts,
            }
        ),
    )

rasterize(layer, *, aggregator='count', column=None, dynamic=True, cmap='viridis', clim=None, cnorm=None, name=None, visible=True, **opts) #

Add a server-rasterized density layer that re-aggregates on zoom.

Produces a numeric image (Bokeh keeps colorbar + hover + live recolor), aggregating all rows per screen pixel — a million points cost the same as a thousand.

Parameters:

Name Type Description Default
layer Any

A HoloViews element or a (Feature)GeoDataFrame (becomes a point layer).

required
aggregator Any

Reduction name ("count"/"mean"/"sum"/…/"count_cat") or a Datashader reduction object.

'count'
column str | None

The value column aggregated by column-requiring reductions.

None
dynamic bool

Re-rasterize on every viewport change (needs a live kernel/server); False bakes a single static image (deterministic — what the tests assert on).

True
cmap str

Colormap for the rasterized image.

'viridis'
clim tuple[float, float] | None

Frozen (vmin, vmax) colour limits (IN-4). None (default) lets Bokeh auto-range the rasterized image, which re-ranges per viewport; a pair pins the colour scale so a rasterized layer can share one range with a neighbouring field. The limits reach Bokeh's colour mapper rather than Datashader, so a frozen scale works even under cnorm="eq_hist", which Datashader itself refuses to combine with a span (the X-4 workaround).

None
cnorm str | None

Colour normalisation Bokeh applies — "linear" (the default when limits are pinned), "log" or "eq_hist". None leaves Bokeh's default. With clim and cnorm="eq_hist" the equalisation is Bokeh's EqHistColorMapper, which takes explicit limits.

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

width/height pin the canvas; everything else styles the result.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/builders/bigdata.py
def rasterize(
    self,
    layer: Any,
    *,
    aggregator: Any = "count",
    column: str | None = None,
    dynamic: bool = True,
    cmap: str = "viridis",
    clim: tuple[float, float] | None = None,
    cnorm: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a server-rasterized density layer that re-aggregates on zoom.

    Produces a numeric image (Bokeh keeps colorbar + hover + live recolor), aggregating all
    rows per screen pixel — a million points cost the same as a thousand.

    Args:
        layer: A HoloViews element or a (Feature)GeoDataFrame (becomes a point layer).
        aggregator: Reduction name (``"count"``/``"mean"``/``"sum"``/…/``"count_cat"``) or a
            Datashader reduction object.
        column: The value column aggregated by column-requiring reductions.
        dynamic: Re-rasterize on every viewport change (needs a live kernel/server); ``False``
            bakes a single static image (deterministic — what the tests assert on).
        cmap: Colormap for the rasterized image.
        clim: Frozen ``(vmin, vmax)`` colour limits (IN-4). ``None`` (default) lets Bokeh auto-range
            the rasterized image, which re-ranges per viewport; a pair pins the colour scale so a
            rasterized layer can share one range with a neighbouring ``field``. The limits reach Bokeh's
            colour mapper rather than Datashader, so a frozen scale works even under ``cnorm="eq_hist"``,
            which Datashader itself refuses to combine with a span (the X-4 workaround).
        cnorm: Colour normalisation Bokeh applies — ``"linear"`` (the default when limits are pinned),
            ``"log"`` or ``"eq_hist"``. ``None`` leaves Bokeh's default. With ``clim`` and
            ``cnorm="eq_hist"`` the equalisation is Bokeh's ``EqHistColorMapper``, which takes explicit
            limits.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: ``width``/``height`` pin the canvas; everything else styles the result.

    Returns:
        The same map instance, so builder calls chain.
    """
    _require_holoviz()
    canvas = {key: opts.pop(key) for key in ("width", "height") if key in opts}
    held: dict = {}
    described_opts = describe_opts(held, opts)
    common: dict[str, Any] = {
        "cmap": style_value(held, "cmap", cmap, cmap_name(cmap)),
        "colorbar": True,
    }
    # A frozen colour scale rides in `common` so the drawer hands it to Bokeh's colour mapper (IN-4). The
    # pair is recorded in the travelling (list) spelling, as `field`/`timecube` record theirs.
    if clim is not None:
        common["clim"] = style_value(held, "clim", _travelling_pair(clim))
    if cnorm is not None:
        common["cnorm"] = cnorm
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="raster",
        source=layer,
        held=held,
        symbology=Symbology(
            props={
                "via": "rasterize",
                # A Datashader reduction is a live object; held beside the layer, and described as
                # nothing, which is the `"count"` every reader without it aggregates by.
                "aggregator": describe(held, "aggregator", aggregator),
                "column": column,
                "dynamic": dynamic,
                "canvas": canvas,
                "common": common,
                "opts": described_opts,
            }
        ),
    )

datashade(layer, *, cmap='viridis', color_key=None, aggregator='count', column=None, dynamic=True, clim=None, cnorm=None, name=None, visible=True, **opts) #

Add a fully shaded (RGB) density layer — categorical blends via color_key (DI.2a).

Unlike :meth:rasterize the colour-mapping happens server-side too (no Bokeh colorbar / live recolor) — use it when categories must blend per pixel, e.g. landcover classes.

Parameters:

Name Type Description Default
layer Any

A HoloViews element or a (Feature)GeoDataFrame (becomes a point layer).

required
cmap str

Colormap for continuous shading (ignored when color_key is given).

'viridis'
color_key Any | None

{category: colour} mapping for categorical shading, or a list of colours in category order — the two forms HoloViews takes; requires a count_cat/by aggregation over column. Non-categorical columns are converted (and the conversion logged — no silent dtype switch).

None
aggregator Any

Reduction name or Datashader reduction; color_key implies count_cat when the aggregator is left at "count".

'count'
column str | None

The value/category column.

None
dynamic bool

Re-shade on every viewport change; False bakes a static RGB.

True
clim tuple[float, float] | None

Frozen (vmin, vmax) colour span (IN-4). None (default) re-autoranges per frame; a pair pins the shade's domain (passed to the shade operation as clims).

None
cnorm str | None

Shade normalisation — "linear" / "log" / "eq_hist". None leaves HoloViews' default, but defaults to "linear" when clim is set, because Datashader refuses a span under eq_hist (the X-4 trap).

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

width/height pin the canvas; everything else styles the result.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/builders/bigdata.py
def datashade(
    self,
    layer: Any,
    *,
    cmap: str = "viridis",
    color_key: Any | None = None,
    aggregator: Any = "count",
    column: str | None = None,
    dynamic: bool = True,
    clim: tuple[float, float] | None = None,
    cnorm: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a fully shaded (RGB) density layer — categorical blends via ``color_key`` (DI.2a).

    Unlike :meth:`rasterize` the colour-mapping happens server-side too (no Bokeh colorbar /
    live recolor) — use it when categories must blend per pixel, e.g. landcover classes.

    Args:
        layer: A HoloViews element or a (Feature)GeoDataFrame (becomes a point layer).
        cmap: Colormap for continuous shading (ignored when ``color_key`` is given).
        color_key: ``{category: colour}`` mapping for categorical shading, or a list of colours in
            category order — the two forms HoloViews takes; requires a
            ``count_cat``/``by`` aggregation over ``column``. Non-categorical columns are
            converted (and the conversion logged — no silent dtype switch).
        aggregator: Reduction name or Datashader reduction; ``color_key`` implies
            ``count_cat`` when the aggregator is left at ``"count"``.
        column: The value/category column.
        dynamic: Re-shade on every viewport change; ``False`` bakes a static RGB.
        clim: Frozen ``(vmin, vmax)`` colour span (IN-4). ``None`` (default) re-autoranges per frame;
            a pair pins the shade's domain (passed to the shade operation as ``clims``).
        cnorm: Shade normalisation — ``"linear"`` / ``"log"`` / ``"eq_hist"``. ``None`` leaves
            HoloViews' default, but **defaults to ``"linear"`` when ``clim`` is set**, because
            Datashader refuses a span under ``eq_hist`` (the X-4 trap).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: ``width``/``height`` pin the canvas; everything else styles the result.

    Returns:
        The same map instance, so builder calls chain.
    """
    _require_holoviz()
    _reject_invalid_span(clim, cnorm, color_key, "datashade")
    if color_key is not None and aggregator == "count":
        aggregator = "count_cat"
    if aggregator == "count_cat" and column is not None:
        # Cast before the source is recorded, so the frame the layer draws is the categorical one the
        # reduction needs — the drawer opens what was recorded, not what the caller passed.
        layer = self._ensure_categorical(layer, column)
    canvas: dict = {
        key: opts.pop(key) for key in ("width", "height") if key in opts
    }
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="points",
        source=layer,
        held=held,
        symbology=Symbology(
            props={
                "via": "datashade",
                "aggregator": describe(held, "aggregator", aggregator),
                "column": column,
                "dynamic": dynamic,
                "canvas": canvas,
                "color_key": describe(held, "color_key", color_key),
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "clim": describe(held, "clim", _travelling_pair(clim)),
                "cnorm": cnorm,
                "common": {},
                "opts": described_opts,
            }
        ),
    )

trajectory(features, *, track_column=None, by=None, dynspread=True, cmap='viridis', color_key=None, dynamic=True, clim=None, cnorm=None, name=None, visible=True, **opts) #

Datashade millions of ordered track points as line density (GPS/AIS, DI.2b).

Point rows are connected into per-track paths (NaN-separated, the Canvas.line recipe) and aggregated server-side; with by the tracks blend per class via count_cat.

Parameters:

Name Type Description Default
features Any

A point (Feature)GeoDataFrame whose row order walks each track; reprojected through pyramids first.

required
track_column str | None

Column identifying the track each point belongs to; None treats the whole table as one track.

None
by str | None

Optional categorical column colouring tracks per class (count_cat blend).

None
dynspread bool

Grow isolated pixels so sparse tracks stay visible.

True
clim tuple[float, float] | None

Frozen (vmin, vmax) colour span (IN-4). None (default) re-autoranges per frame; a pair pins the shade's domain (passed to the shade operation as clims).

None
cnorm str | None

Shade normalisation — "linear" / "log" / "eq_hist". None leaves HoloViews' default, but defaults to "linear" when clim is set, because Datashader refuses a span under eq_hist (the X-4 trap).

None
cmap str

Colormap for continuous shading (ignored when color_key is given).

'viridis'
color_key Any | None

{category: colour} mapping used with by, or a list of colours in category order — the two forms HoloViews takes.

None
dynamic bool

Re-shade on every viewport change; False bakes a static RGB.

True
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

width/height pin the canvas; everything else styles the result.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Source code in src/digitalearth/interactive/builders/bigdata.py
def trajectory(
    self,
    features: Any,
    *,
    track_column: str | None = None,
    by: str | None = None,
    dynspread: bool = True,
    cmap: str = "viridis",
    color_key: Any | None = None,
    dynamic: bool = True,
    clim: tuple[float, float] | None = None,
    cnorm: str | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Datashade millions of ordered track points as line density (GPS/AIS, DI.2b).

    Point rows are connected into per-track paths (NaN-separated, the ``Canvas.line`` recipe)
    and aggregated server-side; with ``by`` the tracks blend per class via ``count_cat``.

    Args:
        features: A point (Feature)GeoDataFrame whose row order walks each track; reprojected
            through pyramids first.
        track_column: Column identifying the track each point belongs to; ``None`` treats the
            whole table as one track.
        by: Optional categorical column colouring tracks per class (``count_cat`` blend).
        dynspread: Grow isolated pixels so sparse tracks stay visible.
        clim: Frozen ``(vmin, vmax)`` colour span (IN-4). ``None`` (default) re-autoranges per frame;
            a pair pins the shade's domain (passed to the shade operation as ``clims``).
        cnorm: Shade normalisation — ``"linear"`` / ``"log"`` / ``"eq_hist"``. ``None`` leaves
            HoloViews' default, but **defaults to ``"linear"`` when ``clim`` is set**, because
            Datashader refuses a span under ``eq_hist`` (the X-4 trap).
        cmap: Colormap for continuous shading (ignored when ``color_key`` is given).
        color_key: ``{category: colour}`` mapping used with ``by``, or a list of colours in category
            order — the two forms HoloViews takes.
        dynamic: Re-shade on every viewport change; ``False`` bakes a static RGB.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: ``width``/``height`` pin the canvas; everything else styles the result.

    Returns:
        The same map instance, so builder calls chain.
    """
    _require_holoviz()
    _reject_invalid_span(clim, cnorm, color_key, "trajectory")
    canvas: dict = {
        key: opts.pop(key) for key in ("width", "height") if key in opts
    }
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="lines",
        source=features,
        held=held,
        symbology=Symbology(
            props={
                "clim": describe(held, "clim", _travelling_pair(clim)),
                "cnorm": cnorm,
                "via": "trajectory",
                "track_column": track_column,
                "by": by,
                "dynspread": dynspread,
                "cmap": describe(held, "cmap", cmap, cmap_name(cmap)),
                "color_key": describe(held, "color_key", color_key),
                "dynamic": dynamic,
                "canvas": canvas,
                "common": {},
                "opts": described_opts,
            }
        ),
    )

live(*, kind='points', data=None, buffer=False, length=1000, name=None, visible=True, **opts) #

Add a live layer backed by a Pipe (replace) or Buffer (append) you push into (IN-17).

The layer is a DynamicMap that re-renders from the stream, so :meth:push updates only its glyphs rather than rebuilding the map. Needs a live kernel/server for a push to reach the browser.

Parameters:

Name Type Description Default
kind str

"points" (a point feed — moving vehicles, sensors) or "path" (a growing track).

'points'
data Any

The initial data, in the display CRS — a DataFrame (x/y columns) or anything the GeoViews element accepts; None starts empty (Pipe only).

None
buffer bool

False (default) uses a Pipe — a push replaces the layer's data; True uses a Buffer that appends each push and keeps the last length rows.

False
length int

The sliding-window size for buffer=True (ignored for a Pipe).

1000
name str | None

The caller's own layer id/label. None generates one from the HoloViews engine name (holoviews-1, holoviews-2, …) — it does not reflect kind, so name the layer when you want points vs path told apart (and the id is what :meth:push addresses).

None
visible bool

Whether the layer is drawn.

True
**opts Any

HoloViews style options applied to every frame of the live element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain. The stream is reached through :meth:live_stream

Self

and fed through :meth:push, both by the layer's id (:attr:InteractiveMap.layer_ids).

Raises:

Type Description
ValueError

for an unknown kind, or for buffer=True with no initial data (a Buffer needs a DataFrame to infer its columns).

Examples:

  • A point feed starts empty; pushing replaces its data, and the layer is a live DynamicMap:
    >>> import pandas as pd                                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> import holoviews as hv                                     # doctest: +SKIP
    >>> m = InteractiveMap().live(kind="points", name="cars")      # doctest: +SKIP
    >>> isinstance(m.layers[-1], hv.DynamicMap)                    # doctest: +SKIP
    True
    >>> m.push("cars", pd.DataFrame({"x": [0.0], "y": [0.0]})) is m  # doctest: +SKIP
    True
    >>> len(m.live_stream("cars").data)                           # doctest: +SKIP
    1
    
  • A Buffer tails the last length rows across pushes:
    >>> import pandas as pd                                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> start = pd.DataFrame({"x": [0.0], "y": [0.0]})            # doctest: +SKIP
    >>> m = InteractiveMap().live(                                # doctest: +SKIP
    ...     kind="points", data=start, buffer=True, length=2, name="track"
    ... )
    >>> m.push("track", pd.DataFrame({"x": [1.0], "y": [1.0]}))   # doctest: +SKIP
    >>> m.push("track", pd.DataFrame({"x": [2.0], "y": [2.0]}))   # doctest: +SKIP
    >>> len(m.live_stream("track").data)  # kept the last 2       # doctest: +SKIP
    2
    
Source code in src/digitalearth/interactive/app/live.py
def live(
    self,
    *,
    kind: str = "points",
    data: Any = None,
    buffer: bool = False,
    length: int = 1000,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a live layer backed by a ``Pipe`` (replace) or ``Buffer`` (append) you push into (IN-17).

    The layer is a ``DynamicMap`` that re-renders from the stream, so :meth:`push` updates only its glyphs
    rather than rebuilding the map. Needs a live kernel/server for a push to reach the browser.

    Args:
        kind: ``"points"`` (a point feed — moving vehicles, sensors) or ``"path"`` (a growing track).
        data: The initial data, in the **display CRS** — a DataFrame (``x``/``y`` columns) or anything the
            GeoViews element accepts; ``None`` starts empty (``Pipe`` only).
        buffer: ``False`` (default) uses a ``Pipe`` — a push **replaces** the layer's data; ``True`` uses a
            ``Buffer`` that **appends** each push and keeps the last ``length`` rows.
        length: The sliding-window size for ``buffer=True`` (ignored for a ``Pipe``).
        name: The caller's own layer id/label. ``None`` generates one from the HoloViews engine name
            (``holoviews-1``, ``holoviews-2``, …) — it does **not** reflect ``kind``, so name the layer
            when you want points vs path told apart (and the id is what :meth:`push` addresses).
        visible: Whether the layer is drawn.
        **opts: HoloViews style options applied to every frame of the live element.

    Returns:
        The same map instance, so builder calls chain. The stream is reached through :meth:`live_stream`
        and fed through :meth:`push`, both by the layer's id (:attr:`InteractiveMap.layer_ids`).

    Raises:
        ValueError: for an unknown ``kind``, or for ``buffer=True`` with no initial ``data`` (a ``Buffer``
            needs a DataFrame to infer its columns).

    Examples:
        - A point feed starts empty; pushing replaces its data, and the layer is a live ``DynamicMap``:
            ```python
            >>> import pandas as pd                                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> import holoviews as hv                                     # doctest: +SKIP
            >>> m = InteractiveMap().live(kind="points", name="cars")      # doctest: +SKIP
            >>> isinstance(m.layers[-1], hv.DynamicMap)                    # doctest: +SKIP
            True
            >>> m.push("cars", pd.DataFrame({"x": [0.0], "y": [0.0]})) is m  # doctest: +SKIP
            True
            >>> len(m.live_stream("cars").data)                           # doctest: +SKIP
            1

            ```
        - A ``Buffer`` tails the last ``length`` rows across pushes:
            ```python
            >>> import pandas as pd                                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> start = pd.DataFrame({"x": [0.0], "y": [0.0]})            # doctest: +SKIP
            >>> m = InteractiveMap().live(                                # doctest: +SKIP
            ...     kind="points", data=start, buffer=True, length=2, name="track"
            ... )
            >>> m.push("track", pd.DataFrame({"x": [1.0], "y": [1.0]}))   # doctest: +SKIP
            >>> m.push("track", pd.DataFrame({"x": [2.0], "y": [2.0]}))   # doctest: +SKIP
            >>> len(m.live_stream("track").data)  # kept the last 2       # doctest: +SKIP
            2

            ```
    """
    gv, hv = _require_holoviz()
    from holoviews import streams

    if kind not in _LIVE_KINDS:
        raise ValueError(
            f"unknown live kind {kind!r}; choose from {list(_LIVE_KINDS)}"
        )
    crs = gv.util.process_crs(self.crs)
    element_cls = {"points": gv.Points, "path": gv.Path}[kind]

    def _draw(data: Any) -> Any:
        """Build one frame of the live element from the stream's current data.

        Args:
            data: Whatever the ``Pipe``/``Buffer`` currently holds, or ``None`` before the first push.

        Returns:
            The GeoViews element for this frame, styled with the caller's ``**opts``.
        """
        element = element_cls([] if data is None else data, crs=crs)
        return element.opts(**opts) if opts else element

    if buffer:
        if data is None:
            raise ValueError(
                "live(buffer=True) needs an initial data= frame so the Buffer can infer its columns; "
                "pass the first batch, or use a Pipe (buffer=False) which starts empty"
            )
        stream: Any = streams.Buffer(data, length=length)
    else:
        stream = streams.Pipe(data=data)
    before = set(self.layer_ids)
    dmap = hv.DynamicMap(_draw, streams=[stream])
    self.add_layer(dmap, kind=None, name=name, visible=visible)
    # Key the stream off the id `add_layer` just issued — the one new id in the tree — rather than off
    # `_last_layer_id`, which is only the just-added layer while `custom:holoviews` sits in a non-underlay
    # band (an invariant this mixin does not own). The set difference is exactly that new id (I1).
    added = [layer_id for layer_id in self.layer_ids if layer_id not in before]
    self._live_streams[added[-1]] = stream
    return self

live_stream(layer_id) #

Return the Pipe/Buffer backing a live layer, to inspect or .send() to directly (IN-17).

Parameters:

Name Type Description Default
layer_id str

The live layer's id (:attr:InteractiveMap.layer_ids).

required

Returns:

Type Description
Any

The HoloViews stream — a Pipe for buffer=False or a Buffer for buffer=True.

Raises:

Type Description
KeyError

when layer_id is not a live layer, naming the ones that are.

Examples:

  • The stream a live layer was built with is reached by its id, ready to .send() to:
    >>> import pandas as pd                                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> m = InteractiveMap().live(kind="points", name="cars")      # doctest: +SKIP
    >>> stream = m.live_stream("cars")                            # doctest: +SKIP
    >>> stream.send(pd.DataFrame({"x": [0.0], "y": [0.0]}))        # doctest: +SKIP
    >>> len(m.live_stream("cars").data)                           # doctest: +SKIP
    1
    
Source code in src/digitalearth/interactive/app/live.py
def live_stream(self, layer_id: str) -> Any:
    """Return the ``Pipe``/``Buffer`` backing a live layer, to inspect or ``.send()`` to directly (IN-17).

    Args:
        layer_id: The live layer's id (:attr:`InteractiveMap.layer_ids`).

    Returns:
        The HoloViews stream — a ``Pipe`` for ``buffer=False`` or a ``Buffer`` for ``buffer=True``.

    Raises:
        KeyError: when ``layer_id`` is not a live layer, naming the ones that are.

    Examples:
        - The stream a ``live`` layer was built with is reached by its id, ready to ``.send()`` to:
            ```python
            >>> import pandas as pd                                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> m = InteractiveMap().live(kind="points", name="cars")      # doctest: +SKIP
            >>> stream = m.live_stream("cars")                            # doctest: +SKIP
            >>> stream.send(pd.DataFrame({"x": [0.0], "y": [0.0]}))        # doctest: +SKIP
            >>> len(m.live_stream("cars").data)                           # doctest: +SKIP
            1

            ```
    """
    self._require_live(layer_id)
    return self._live_streams[layer_id]

push(layer_id, data) #

Push new data into a live layer — replace (Pipe) or append (Buffer) — and redraw it (IN-17).

A thin, chainable wrapper over the stream's .send(). Needs a live kernel/server for the update to reach the browser; off-server it still updates the stream's data so the next render() reflects it.

Parameters:

Name Type Description Default
layer_id str

The live layer's id.

required
data Any

The new data, in the display CRS — a DataFrame for a Buffer (same columns as the seed), or anything the layer's element accepts for a Pipe.

required

Returns:

Type Description
Self

The same map instance, so pushes chain.

Raises:

Type Description
KeyError

when layer_id is not a live layer, naming the ones that are.

Examples:

  • Pushing to a Pipe layer replaces its data, and pushes chain:
    >>> import pandas as pd                                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> m = InteractiveMap().live(kind="points", name="cars")      # doctest: +SKIP
    >>> m.push("cars", pd.DataFrame({"x": [0.0, 1.0], "y": [0.0, 1.0]})) is m  # doctest: +SKIP
    True
    >>> len(m.live_stream("cars").data)                           # doctest: +SKIP
    2
    
Source code in src/digitalearth/interactive/app/live.py
def push(self, layer_id: str, data: Any) -> Self:
    """Push new data into a live layer — replace (``Pipe``) or append (``Buffer``) — and redraw it (IN-17).

    A thin, chainable wrapper over the stream's ``.send()``. Needs a live kernel/server for the update to
    reach the browser; off-server it still updates the stream's data so the next ``render()`` reflects it.

    Args:
        layer_id: The live layer's id.
        data: The new data, in the display CRS — a DataFrame for a ``Buffer`` (same columns as the seed),
            or anything the layer's element accepts for a ``Pipe``.

    Returns:
        The same map instance, so pushes chain.

    Raises:
        KeyError: when ``layer_id`` is not a live layer, naming the ones that are.

    Examples:
        - Pushing to a ``Pipe`` layer replaces its data, and pushes chain:
            ```python
            >>> import pandas as pd                                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> m = InteractiveMap().live(kind="points", name="cars")      # doctest: +SKIP
            >>> m.push("cars", pd.DataFrame({"x": [0.0, 1.0], "y": [0.0, 1.0]})) is m  # doctest: +SKIP
            True
            >>> len(m.live_stream("cars").data)                           # doctest: +SKIP
            2

            ```
    """
    self._require_live(layer_id)
    self._live_streams[layer_id].send(data)
    return self

tiles(url, *, level='underlay', name=None, visible=True, **opts) #

Draw raster tiles from a raw XYZ/WMTS URL template beneath the data layers (#268).

The URL-only half of the basemap entry points: a literal {Z}/{X}/{Y} (or {z}/{x}/{y}) tile template, drawn as a gv.WMTS. For a named provider or a keyed preset use :meth:basemap instead — the two no longer share one overloaded parameter.

Parameters:

Name Type Description Default
url str

A raw XYZ/WMTS URL template, e.g. "https://a.tile.example/{Z}/{X}/{Y}.png".

required
level str

"underlay" (default) keeps the tiles behind the data; "overlay" puts them on top.

'underlay'
name str | None

The caller's own name for the layer, used as its id and label; None generates one.

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden.

True
**opts Any

Extra HoloViews style options applied to the tile element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when url is not a URL template (use :meth:basemap for a named provider or keyed preset), when the display CRS is not Web Mercator, or when a non-Mercator projection is active.

Examples:

  • Draw a custom XYZ URL template:
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> url = "https://a.tile.example/{Z}/{X}/{Y}.png"             # doctest: +SKIP
    >>> InteractiveMap().tiles(url).layers[0]                      # doctest: +SKIP
    
Source code in src/digitalearth/interactive/decoration/decoration.py
def tiles(
    self,
    url: str,
    *,
    level: str = "underlay",
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Draw raster tiles from a raw XYZ/WMTS URL template beneath the data layers (#268).

    The URL-only half of the basemap entry points: a literal ``{Z}/{X}/{Y}`` (or ``{z}/{x}/{y}``) tile
    template, drawn as a ``gv.WMTS``. For a named provider or a keyed preset use :meth:`basemap` instead —
    the two no longer share one overloaded parameter.

    Args:
        url: A raw XYZ/WMTS URL template, e.g. ``"https://a.tile.example/{Z}/{X}/{Y}.png"``.
        level: ``"underlay"`` (default) keeps the tiles behind the data; ``"overlay"`` puts them on top.
        name: The caller's own name for the layer, used as its id and label; ``None`` generates one.
        visible: Whether the layer is drawn. ``False`` builds it hidden and describes it hidden.
        **opts: Extra HoloViews style options applied to the tile element.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: when ``url`` is not a URL template (use :meth:`basemap` for a named provider or keyed
            preset), when the display CRS is not Web Mercator, or when a non-Mercator projection is active.

    Examples:
        - Draw a custom XYZ URL template:
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> url = "https://a.tile.example/{Z}/{X}/{Y}.png"             # doctest: +SKIP
            >>> InteractiveMap().tiles(url).layers[0]                      # doctest: +SKIP

            ```
    """
    if not (isinstance(url, str) and "://" in url):
        raise ValueError(
            "tiles(url=...) takes a raw XYZ/WMTS URL template such as "
            f"'https://.../{{Z}}/{{X}}/{{Y}}.png'; use basemap(provider=...) for a named provider or "
            f"keyed preset (got {url!r})"
        )
    return self._draw_basemap(
        url,
        level=level,
        api_key=None,
        preset=None,
        name=name,
        visible=visible,
        caller="tiles",
        **opts,
    )

coastlines(resolution='110m', *, name=None, visible=True, **opts) #

Add the Natural-Earth coastline on top of the data layers.

Parameters:

Name Type Description Default
resolution str

Natural-Earth scale — "110m" (default), "50m" or "10m".

'110m'
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the feature element.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Examples:

  • Add a medium-resolution coastline on top of the data:
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> m = InteractiveMap().coastlines(resolution="50m")           # doctest: +SKIP
    >>> len(m.layers)                                               # doctest: +SKIP
    1
    

Raises:

Type Description
ValueError

when the display CRS is not Web Mercator.

Source code in src/digitalearth/interactive/decoration/decoration.py
def coastlines(
    self,
    resolution: str = "110m",
    *,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add the Natural-Earth coastline on top of the data layers.

    Args:
        resolution: Natural-Earth scale — ``"110m"`` (default), ``"50m"`` or ``"10m"``.
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the feature element.

    Returns:
        The same map instance, so builder calls chain.

    Examples:
        - Add a medium-resolution coastline on top of the data:
            ```python
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> m = InteractiveMap().coastlines(resolution="50m")           # doctest: +SKIP
            >>> len(m.layers)                                               # doctest: +SKIP
            1

            ```

    Raises:
        ValueError: when the display CRS is not Web Mercator.
    """
    _require_holoviz()
    # Refused here, because the message names the builder the caller called.
    self._require_web_mercator("coastlines")
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="coastlines",
        held=held,
        symbology=Symbology(
            props={
                "via": "coastlines",
                "resolution": resolution,
                "opts": described_opts,
            }
        ),
    )

graticule(lon_step=None, lat_step=None, *, spacing=None, name=None, visible=True, **opts) #

Add a longitude/latitude graticule at the requested spacing (parity with Map.graticule).

The spacing arguments mirror the static Map.graticule(lon_step, lat_step) so the same call means the same thing on both tiers. GeoViews draws the grid from Natural Earth's pre-cut graticules_<n> line layers rather than generating meridians on the fly, so only the shipped, symmetric steps can be honoured: 1, 5, 10, 15, 20 and 30 degrees, with lon_step == lat_step. Any other request raises instead of being quietly ignored.

Parameters:

Name Type Description Default
lon_step float | None

Meridian spacing in degrees; one of :data:_GRATICULE_STEPS. None (default) means :data:DEFAULT_GRATICULE_STEP — a named constant, not a literal, so a step the caller wrote can be told from one they did not (#336).

None
lat_step float | None

Parallel spacing in degrees; must equal lon_step. None (default) means :data:DEFAULT_GRATICULE_STEP, the same way round.

None
spacing float | None

One step for both, for a caller who wants a square grid; it overrides the two above, and warns when it does, because a call that names all three has had two of its own arguments thrown away (#336). The same keyword the static and web tiers take, so one call draws one grid on every tier that draws a graticule at all (#324) — but its value domain is this engine's, not theirs: only the shipped steps listed above are honoured, so spacing=7.5 raises here while it draws on both of them (review R-L10).

None
name str | None

The caller's own name for the layer, used as its id and its label; None (default) generates one from the kind, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the layer is drawn. False builds it hidden and describes it hidden — before, the flag fell through **opts to HoloViews, which hid the element while the figure went on calling it visible (#327).

True
**opts Any

Extra HoloViews style options applied to the grid feature.

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Warns:

Type Description
UserWarning

when spacing is given beside lon_step or lat_step, which discards the step — the same report the static tier makes, so the two tiers answer the over-specified call the same way (#336).

Raises:

Type Description
ValueError

when lon_step and lat_step differ, or when the step is not one of the Natural-Earth graticule spacings GeoViews can draw.

Examples:

  • A 10-degree graticule instead of the 30-degree default:
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> m = InteractiveMap().graticule(lon_step=10, lat_step=10)    # doctest: +SKIP
    >>> m.layers[-1].data.name                                      # doctest: +SKIP
    'graticules_10'
    
Source code in src/digitalearth/interactive/view/projection.py
def graticule(
    self,
    lon_step: float | None = None,
    lat_step: float | None = None,
    *,
    spacing: float | None = None,
    name: str | None = None,
    visible: bool = True,
    **opts: Any,
) -> Self:
    """Add a longitude/latitude graticule at the requested spacing (parity with ``Map.graticule``).

    The spacing arguments mirror the static ``Map.graticule(lon_step, lat_step)`` so the same call
    means the same thing on both tiers. GeoViews draws the grid from Natural Earth's pre-cut
    ``graticules_<n>`` line layers rather than generating meridians on the fly, so only the shipped,
    **symmetric** steps can be honoured: ``1``, ``5``, ``10``, ``15``, ``20`` and ``30`` degrees, with
    ``lon_step == lat_step``. Any other request raises instead of being quietly ignored.

    Args:
        lon_step: Meridian spacing in degrees; one of :data:`_GRATICULE_STEPS`. ``None`` (default)
            means :data:`DEFAULT_GRATICULE_STEP` — a named constant, not a literal, so a step the
            caller wrote can be told from one they did not (#336).
        lat_step: Parallel spacing in degrees; must equal ``lon_step``. ``None`` (default) means
            :data:`DEFAULT_GRATICULE_STEP`, the same way round.
        spacing: One step for both, for a caller who wants a square grid; it overrides the two
            above, and **warns** when it does, because a call that names all three has had two of its
            own arguments thrown away (#336). The same **keyword** the static and web tiers take, so
            one call draws one grid on every tier that draws a graticule at all (#324) — but its
            **value** domain is this engine's, not theirs: only the shipped steps listed above are
            honoured, so ``spacing=7.5`` raises here while it draws on both of them (review R-L10).
        name: The caller's own name for the layer, used as its id and its label; ``None``
            (default) generates one from the kind, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the layer is drawn. ``False`` builds it hidden **and** describes it
            hidden — before, the flag fell through ``**opts`` to HoloViews, which hid the
            element while the figure went on calling it visible (#327).
        **opts: Extra HoloViews style options applied to the grid feature.

    Returns:
        The same map instance, so builder calls chain.

    Warns:
        UserWarning: when ``spacing`` is given beside ``lon_step`` or ``lat_step``, which discards the
            step — the same report the static tier makes, so the two tiers answer the over-specified
            call the same way (#336).

    Raises:
        ValueError: when ``lon_step`` and ``lat_step`` differ, or when the step is not one of the
            Natural-Earth graticule spacings GeoViews can draw.

    Examples:
        - A 10-degree graticule instead of the 30-degree default:
            ```python
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> m = InteractiveMap().graticule(lon_step=10, lat_step=10)    # doctest: +SKIP
            >>> m.layers[-1].data.name                                      # doctest: +SKIP
            'graticules_10'

            ```
    """
    _require_holoviz()
    # Validated here, because the message names the caller's own arguments. The grid itself is built by
    # `draw_graticule` from exactly what this records, so the figure describes the graticule rather
    # than holding one somebody else built.
    if spacing is not None:
        # `spacing` names both steps by definition, so it overrides `lon_step`/`lat_step` — but a call
        # that named them too has had two of its own arguments thrown away, which used to happen in
        # silence (the static tier's R2-L3 defect, on this tier; #336). Warn naming them, matching the
        # static tier's wording, then let `spacing` win.
        if lon_step is not None or lat_step is not None:
            warnings.warn(
                f"graticule() was given spacing={spacing!r} together with "
                f"lon_step={lon_step!r}/lat_step={lat_step!r}; spacing sets both, so those two are "
                "discarded. Pass one or the other.",
                UserWarning,
                stacklevel=2,
            )
        lon_step = lat_step = spacing
    else:
        # A step the caller did not name falls back to the shared default — a named constant, not a
        # literal, so the two tiers cannot drift (#336).
        if lon_step is None:
            lon_step = DEFAULT_GRATICULE_STEP
        if lat_step is None:
            lat_step = DEFAULT_GRATICULE_STEP
    step = self._graticule_step(lon_step, lat_step)
    held: dict = {}
    described_opts = describe_opts(held, opts)
    return self.add_layer(
        None,
        name=name,
        visible=visible,
        kind="graticule",
        held=held,
        symbology=Symbology(
            props={
                "via": "graticule",
                "step": int(step),
                "opts": described_opts,
            }
        ),
    )

set_bounds(bounds=None, *, padding=0.0) #

Frame the map on a region, or on everything it draws.

Bokeh pans and zooms, so before this the view was whatever HoloViews autoranged to and there was no call a caller could make to open the map on a region — the tier had no framing method under any spelling. It still pans: this sets the initial view rather than locking it.

Parameters:

Name Type Description Default
bounds Bounds | Sequence[float] | None

A :class:~digitalearth.base.spec.bounds.Bounds in any CRS — it is reprojected to the display CRS, which is the point of passing one — or a bare (west, south, east, north) sequence taken to be in the display CRS. That is the bbox order :meth:~digitalearth.base.spec.bounds.Bounds.as_bbox and pyramids use, and it is the order every tier's set_bounds reads: the static tier kept matplotlib's [xmin, xmax, ymin, ymax] for one branch, so the same sequence framed two different rectangles across the 2-D tiers, and that ordering is gone rather than aliased.

None (the default) fits the map to its data: the union of what the panel's data layers cover, read from the elements themselves. Only the data band counts — a tile basemap, a graticule and a coastline are drawn around the subject rather than being it, and GeoViews reports a Feature's range in degrees whatever the display CRS is, so unioning one in would be wrong in units as well as in extent.

None
padding float

Breathing room around the frame, as a fraction of its own span — 0.05 leaves a 5% margin. Note the units are this tier's: a HoloViews figure is framed by data-coordinate limits, so a proportion of the span is the only padding that means anything, where the web tier's padding is a number of screen pixels.

0.0

Returns:

Type Description
Self

The same map instance, so builder calls chain — which is what the Core declares and what the web

Self

and 3-D tiers already answer.

Raises:

Type Description
ValueError

for a sequence that is not four values; when bounds is None and the map draws nothing with an extent, because silently doing nothing is indistinguishable from the call being dropped; or, from Bounds, for a non-finite edge or a padding below -0.5, which would turn the frame inside out.

Examples:

  • Open the map on a region rather than on whatever the data autoranges to:
    >>> from digitalearth.interactive import InteractiveMap       # doctest: +SKIP
    >>> m = InteractiveMap(crs=4326).set_bounds((3.0, 50.0, 7.0, 54.0))  # doctest: +SKIP
    >>> m.viewport.bounds.as_bbox()                              # doctest: +SKIP
    [3.0, 50.0, 7.0, 54.0]
    
Source code in src/digitalearth/interactive/view/projection.py
def set_bounds(
    self,
    bounds: Bounds | Sequence[float] | None = None,
    *,
    padding: float = 0.0,
) -> Self:
    """Frame the map on a region, or on everything it draws.

    Bokeh pans and zooms, so before this the view was whatever HoloViews autoranged to and there was no
    call a caller could make to open the map on a region — the tier had no framing method under any
    spelling. It still pans: this sets the *initial* view rather than locking it.

    Args:
        bounds: A :class:`~digitalearth.base.spec.bounds.Bounds` in **any** CRS — it is reprojected to
            the display CRS, which is the point of passing one — or a bare
            ``(west, south, east, north)`` sequence taken to be in the display CRS. That is the bbox
            order :meth:`~digitalearth.base.spec.bounds.Bounds.as_bbox` and pyramids use, and it is the
            order **every** tier's ``set_bounds`` reads: the static tier kept matplotlib's
            ``[xmin, xmax, ymin, ymax]`` for one branch, so the same sequence framed two different
            rectangles across the 2-D tiers, and that ordering is gone rather than aliased.

            ``None`` (the default) **fits the map to its data**: the union of what the panel's data
            layers cover, read from the elements themselves. Only the ``data`` band counts — a tile
            basemap, a graticule and a coastline are drawn around the subject rather than being it, and
            GeoViews reports a ``Feature``'s range in degrees whatever the display CRS is, so unioning
            one in would be wrong in units as well as in extent.
        padding: Breathing room around the frame, as a fraction of its own span — ``0.05`` leaves a 5%
            margin. Note the **units are this tier's**: a HoloViews figure is framed by data-coordinate
            limits, so a proportion of the span is the only padding that means anything, where the web
            tier's ``padding`` is a number of screen pixels.

    Returns:
        The same map instance, so builder calls chain — which is what the Core declares and what the web
        and 3-D tiers already answer.

    Raises:
        ValueError: for a sequence that is not four values; when ``bounds`` is ``None`` and the map
            draws nothing with an extent, because silently doing nothing is indistinguishable from the
            call being dropped; or, from `Bounds`, for a non-finite edge or a ``padding`` below
            ``-0.5``, which would turn the frame inside out.

    Examples:
        - Open the map on a region rather than on whatever the data autoranges to:
            ```python
            >>> from digitalearth.interactive import InteractiveMap       # doctest: +SKIP
            >>> m = InteractiveMap(crs=4326).set_bounds((3.0, 50.0, 7.0, 54.0))  # doctest: +SKIP
            >>> m.viewport.bounds.as_bbox()                              # doctest: +SKIP
            [3.0, 50.0, 7.0, 54.0]

            ```
    """
    self._frame_bounds = self._frame_asked(bounds, padding)
    return self

projection(name, **opts) #

Set the display projection, rendering through the matplotlib backend.

Parameters:

Name Type Description Default
name Any

A cartopy-projection name GeoViews resolves internally (e.g. "Orthographic", "Robinson", "Mollweide"), an EPSG code, or a pre-built cartopy CRS. Pass None to return to the default Bokeh Web-Mercator path.

required
**opts Any

Reserved for future projection options (currently unused).

{}

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when a tile basemap was already requested (tiles are Web-Mercator only and cannot compose with a non-Mercator projection).

ImportError

when the interactive extra is not installed.

Source code in src/digitalearth/interactive/view/projection.py
def projection(self, name: Any, **opts: Any) -> Self:
    """Set the display projection, rendering through the matplotlib backend.

    Args:
        name: A cartopy-projection name GeoViews resolves internally (e.g. ``"Orthographic"``,
            ``"Robinson"``, ``"Mollweide"``), an EPSG code, or a pre-built cartopy CRS. Pass
            ``None`` to return to the default Bokeh Web-Mercator path.
        **opts: Reserved for future projection options (currently unused).

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: when a tile basemap was already requested (tiles are Web-Mercator only and
            cannot compose with a non-Mercator projection).
        ImportError: when the ``interactive`` extra is not installed.
    """
    # Called for its actionable ImportError; the cartopy projection itself is resolved through the
    # modules GeoViews already imported (`_resolve_projection`).
    _require_holoviz()
    if name is None:
        self._projection = None
        return self
    if self._tiles_provider is not None or any(
        type(layer).__name__ in ("WMTS", "Tiles") for layer in self.layers
    ):
        raise ValueError(
            "projection() cannot compose with tile basemaps — Bokeh tiles render in "
            "Web-Mercator only. Drop tiles() to use a non-Mercator projection."
        )
    self._projection = self._resolve_projection(name)
    return self

theme(theme) #

Set the Bokeh theme every render of this map draws under (IN-18).

A dark-mode map used to be expressible only by threading bgcolor through **opts at every builder call; this records one theme on the map instead, applied to the Bokeh renderer whenever the map composes (:meth:render, the dashboard widgets, :meth:save). It is a builder, so it chains with the rest.

Parameters:

Name Type Description Default
theme Any

A Bokeh built-in theme name — one of :data:_BUILTIN_THEMES ("dark_minimal", "night_sky", …) — or a bokeh.themes.Theme instance built from a YAML/JSON file or a dict. None clears the theme back to Bokeh's default.

required

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

for a string that is not one of the built-in theme names.

Examples:

  • A built-in dark theme, set once and kept for every render:
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().theme("dark_minimal")._theme
    'dark_minimal'
    
  • An unknown name is refused, with the built-ins named:
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().theme("darkmode")  # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: unknown Bokeh theme 'darkmode'; choose one of [...] or pass a bokeh.themes.Theme
    
Source code in src/digitalearth/interactive/core/base.py
def theme(self, theme: Any) -> Self:
    """Set the Bokeh theme every render of this map draws under (IN-18).

    A dark-mode map used to be expressible only by threading ``bgcolor`` through ``**opts`` at every
    builder call; this records one theme on the map instead, applied to the Bokeh renderer whenever the
    map composes (:meth:`render`, the dashboard widgets, :meth:`save`). It is a builder, so it chains with
    the rest.

    Args:
        theme: A Bokeh built-in theme name — one of :data:`_BUILTIN_THEMES` (``"dark_minimal"``,
            ``"night_sky"``, …) — or a ``bokeh.themes.Theme`` instance built from a YAML/JSON file or a
            dict. ``None`` clears the theme back to Bokeh's default.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: for a string that is not one of the built-in theme names.

    Examples:
        - A built-in dark theme, set once and kept for every render:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> InteractiveMap().theme("dark_minimal")._theme
            'dark_minimal'

            ```
        - An unknown name is refused, with the built-ins named:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> InteractiveMap().theme("darkmode")  # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: unknown Bokeh theme 'darkmode'; choose one of [...] or pass a bokeh.themes.Theme

            ```
    """
    if isinstance(theme, str) and theme not in self._BUILTIN_THEMES:
        raise ValueError(
            f"unknown Bokeh theme {theme!r}; choose one of {list(self._BUILTIN_THEMES)} or pass a "
            f"bokeh.themes.Theme"
        )
    self._theme = theme
    return self

hover(*, tooltips=None, formatters=None, layer=None) #

Configure the Bokeh hover tooltips on a registered layer (DI.7).

Parameters:

Name Type Description Default
tooltips list | None

Bokeh HoverTool tooltips spec (e.g. [("value", "@value"), ("x", "$x")]); None keeps the default value+coord readout.

None
formatters dict | None

Optional Bokeh tooltip formatters mapping.

None
layer int | None

Index into :attr:layers — draw order, bottom first — of the layer to configure. None (the default) configures the layer the caller added last, which is not layers[-1] whenever that layer is drawn beneath an overlay such as coastlines; an underlay added after data does not take it over (see :meth:~digitalearth.interactive.core.base.InteractiveMapBase._last_layer_index, which is that rule. The colour keys read it too, but tighten it: a layer whose colour varies with nothing cannot take a key over, and a hover has no such condition — any layer can be hovered).

None

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when there is no layer to configure.

Source code in src/digitalearth/interactive/app/interaction.py
def hover(
    self,
    *,
    tooltips: list | None = None,
    formatters: dict | None = None,
    layer: int | None = None,
) -> Self:
    """Configure the Bokeh hover tooltips on a registered layer (DI.7).

    Args:
        tooltips: Bokeh ``HoverTool`` tooltips spec (e.g. ``[("value", "@value"), ("x", "$x")]``);
            ``None`` keeps the default value+coord readout.
        formatters: Optional Bokeh tooltip ``formatters`` mapping.
        layer: Index into :attr:`layers` — draw order, bottom first — of the layer to configure.
            ``None`` (the default) configures the layer the caller added last, which is not
            ``layers[-1]`` whenever that layer is drawn beneath an overlay such as coastlines; an
            underlay added after data does not take it over (see
            :meth:`~digitalearth.interactive.core.base.InteractiveMapBase._last_layer_index`, which is that
            rule. The colour keys read it too, but tighten it: a layer whose colour varies with nothing
            cannot take a key over, and a hover has no such condition — any layer can be hovered).

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: when there is no layer to configure.
    """
    from bokeh.models import HoverTool

    gv, hv = _require_holoviz()
    if not self.layers:
        raise ValueError(
            "hover() needs at least one layer — add a builder call first"
        )
    index = self._last_layer_index("hover") if layer is None else layer
    tool = HoverTool(tooltips=tooltips, formatters=formatters or {})
    self.layers[index] = self.layers[index].opts(tools=[tool], backend="bokeh")
    return self

on_tap(callback, *, source=None) #

Wire a Tap stream to callback and return the resulting DynamicMap (DI.7).

On click the callback receives (x, y) in the display CRS and returns a HoloViews element (e.g. a side panel). Needs a live kernel/server to round-trip — in static HTML the map renders without the tap response.

Parameters:

Name Type Description Default
callback Callable

callback(x, y) -> hv element invoked on each tap.

required
source Any

The element the tap listens on; defaults to the layer the caller added last — not the one drawn on top, which is a different layer whenever an overlay sits over it.

None

Returns:

Type Description
Any

The hv.DynamicMap driven by the tap stream.

Raises:

Type Description
ValueError

when there is no source layer.

Source code in src/digitalearth/interactive/app/interaction.py
def on_tap(self, callback: Callable, *, source: Any = None) -> Any:
    """Wire a ``Tap`` stream to ``callback`` and return the resulting ``DynamicMap`` (DI.7).

    On click the callback receives ``(x, y)`` in the display CRS and returns a HoloViews element
    (e.g. a side panel). Needs a live kernel/server to round-trip — in static HTML the map renders
    without the tap response.

    Args:
        callback: ``callback(x, y) -> hv element`` invoked on each tap.
        source: The element the tap listens on; defaults to the layer the caller added last — not the
            one drawn on top, which is a different layer whenever an overlay sits over it.

    Returns:
        The ``hv.DynamicMap`` driven by the tap stream.

    Raises:
        ValueError: when there is no source layer.
    """
    gv, hv = _require_holoviz()
    from holoviews import streams

    src = source
    if src is None:
        if self._last_layer_id is None:
            raise ValueError(
                "on_tap() needs a source layer — add a builder call or pass source="
            )
        src = self.layers[self._last_layer_index("on_tap")]
    tap = streams.Tap(source=src, x=0.0, y=0.0)
    return hv.DynamicMap(lambda x, y: callback(x, y), streams=[tap])

tap_profile(collection, *, source=None, band=DEFAULT_BAND) #

Click a cell to pull a time series from a DatasetCollection at that point (DI.7).

Returns a DynamicMap whose Tap callback reads each member's value at the clicked cell (via pyramids nearest_cell) and plots the series — the most-requested interactive feature over a static map. Needs a live kernel/server.

Parameters:

Name Type Description Default
collection Any

A pyramids DatasetCollection whose members are time steps.

required
source Any

The map layer the tap listens on; defaults to the layer the caller added last, as :meth:on_tap reads it.

None
band int

1-based band sampled at the clicked cell.

DEFAULT_BAND

Returns:

Type Description
Any

The hv.DynamicMap (a Curve time series per tap).

Raises:

Type Description
ValueError

when there is no source layer.

Source code in src/digitalearth/interactive/app/interaction.py
def tap_profile(
    self, collection: Any, *, source: Any = None, band: int = DEFAULT_BAND
) -> Any:
    """Click a cell to pull a time series from a ``DatasetCollection`` at that point (DI.7).

    Returns a ``DynamicMap`` whose ``Tap`` callback reads each member's value at the clicked cell
    (via pyramids ``nearest_cell``) and plots the series — the most-requested interactive feature
    over a static map. Needs a live kernel/server.

    Args:
        collection: A pyramids ``DatasetCollection`` whose members are time steps.
        source: The map layer the tap listens on; defaults to the layer the caller added last, as
            :meth:`on_tap` reads it.
        band: 1-based band sampled at the clicked cell.

    Returns:
        The ``hv.DynamicMap`` (a ``Curve`` time series per tap).

    Raises:
        ValueError: when there is no source layer.
    """
    import numpy as np

    gv, hv = _require_holoviz()
    if band < 1:
        raise ValueError(f"band is 1-based; got {band}")
    members = collection.datasets

    def _profile(x: float, y: float) -> Any:
        # pyramids' nearest_cell wants a GeoDataFrame/FeatureCollection; build the single clicked
        # point through pyramids (no shapely/geopandas import here, DX.3).
        from pyramids.feature import FeatureCollection

        point = FeatureCollection.from_xyz([x], [y], crs=self.crs)
        series = []
        for member in members:
            ds = (
                reproject(member, self.crs)
                if self._needs_reproject(member)
                else member
            )
            row, col = np.asarray(ds.nearest_cell(point))[0]
            arr = np.asarray(
                ds.read_array(band=band - 1)
            )  # Dataset.read_array is 0-based
            row_i, col_i = int(row), int(col)
            inside = 0 <= row_i < arr.shape[0] and 0 <= col_i < arr.shape[1]
            series.append(float(arr[row_i, col_i]) if inside else np.nan)
        return hv.Curve(list(enumerate(series)), "t", "value")

    return self.on_tap(_profile, source=source)

draw(kind='box', *, num_objects=None, name=None, visible=True) #

Add a draw/edit tool so the user can sketch an area-of-interest (DI.8).

Wraps a HoloViews draw stream around a fresh annotation layer: "box" → BoxEdit, "poly" → PolyDraw, "point" → PointDraw, "freehand" → FreehandDraw, plus the two editing tools that move the vertices of existing geometry (IN-8): "poly-edit" → PolyEdit and "curve-edit" → CurveEdit. Read the result back via :attr:drawn_geometry. Needs a live kernel/server — static HTML captures nothing.

Parameters:

Name Type Description Default
kind str

"box" / "poly" / "point" / "freehand" (draw new) or "poly-edit" / "curve-edit" (edit the vertices of existing geometry).

'box'
num_objects int | None

Max number of shapes (None = unlimited); ignored by the edit tools.

None
name str | None

The caller's own name for the annotation layer, used as its id and its label; None (default) generates one, and a name already on the map is suffixed -2, -3, … (#321).

None
visible bool

Whether the annotation layer is drawn. False builds it hidden and describes it hidden (#327).

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

for an unknown kind.

Source code in src/digitalearth/interactive/app/interaction.py
def draw(
    self,
    kind: str = "box",
    *,
    num_objects: int | None = None,
    name: str | None = None,
    visible: bool = True,
) -> Self:
    """Add a draw/edit tool so the user can sketch an area-of-interest (DI.8).

    Wraps a HoloViews draw stream around a fresh annotation layer: ``"box"`` → ``BoxEdit``,
    ``"poly"`` → ``PolyDraw``, ``"point"`` → ``PointDraw``, ``"freehand"`` → ``FreehandDraw``, plus the
    two *editing* tools that move the vertices of existing geometry (IN-8): ``"poly-edit"`` →
    ``PolyEdit`` and ``"curve-edit"`` → ``CurveEdit``. Read the result back via :attr:`drawn_geometry`.
    Needs a live kernel/server — static HTML captures nothing.

    Args:
        kind: ``"box"`` / ``"poly"`` / ``"point"`` / ``"freehand"`` (draw new) or ``"poly-edit"`` /
            ``"curve-edit"`` (edit the vertices of existing geometry).
        num_objects: Max number of shapes (``None`` = unlimited); ignored by the edit tools.
        name: The caller's own name for the annotation layer, used as its id and its label;
            ``None`` (default) generates one, and a name already on the map is suffixed
            ``-2``, ``-3``, … (#321).
        visible: Whether the annotation layer is drawn. ``False`` builds it hidden **and**
            describes it hidden (#327).

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        ValueError: for an unknown ``kind``.
    """
    gv, hv = _require_holoviz()
    from holoviews import streams

    crs = gv.util.process_crs(self.crs)
    if kind == "box":
        layer = gv.Rectangles([], crs=crs)
        stream = streams.BoxEdit(source=layer, num_objects=num_objects or 0)
    elif kind == "poly":
        layer = gv.Polygons([], crs=crs)
        stream = streams.PolyDraw(source=layer, num_objects=num_objects or 0)
    elif kind == "point":
        layer = gv.Points([], crs=crs)
        stream = streams.PointDraw(source=layer, num_objects=num_objects or 0)
    elif kind == "freehand":
        layer = gv.Path([], crs=crs)
        stream = streams.FreehandDraw(source=layer, num_objects=num_objects or 0)
    elif kind == "poly-edit":
        # Edits the *vertices* of existing polygons (IN-8) — drag/add/delete nodes — rather than drawing
        # a new shape. PolyEdit takes no num_objects; it operates on whatever polygons the layer holds.
        layer = gv.Polygons([], crs=crs)
        stream = streams.PolyEdit(source=layer)
    elif kind == "curve-edit":
        # Edits the vertices of an existing path/curve (IN-8): move the nodes of a line in place.
        layer = gv.Path([], crs=crs)
        stream = streams.CurveEdit(source=layer)
    else:
        raise ValueError(
            f"unknown draw kind {kind!r}; choose "
            "'box'/'poly'/'point'/'freehand'/'poly-edit'/'curve-edit'"
        )
    # Appended, not overwritten (IN-11): a map can carry several draw tools at once, and a second
    # `draw()` no longer silently replaces the first tool's binding. `_draw_stream` tracks the most
    # recent so the single-tool `drawn_geometry` read keeps meaning what it did.
    self._draw_streams.append(stream)
    self._draw_stream = stream
    self.add_layer(
        layer,
        name=name,
        visible=visible,
        kind="custom:holoviews",
    )
    return self

aoi_crop(dataset) #

Crop dataset (in pyramids) to the drawn box and return the clipped raster (DI.8).

Reads the drawn bbox (display CRS) and calls Dataset.crop — the crop itself is pyramids', this method only reads the drawn coordinates.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset to crop.

required

Returns:

Type Description
Any

The cropped Dataset.

Raises:

Type Description
ValueError

when nothing has been drawn yet.

Source code in src/digitalearth/interactive/app/interaction.py
def aoi_crop(self, dataset: Any) -> Any:
    """Crop ``dataset`` (in pyramids) to the drawn box and return the clipped raster (DI.8).

    Reads the drawn bbox (display CRS) and calls ``Dataset.crop`` — the crop itself is pyramids',
    this method only reads the drawn coordinates.

    Args:
        dataset: A pyramids ``Dataset`` to crop.

    Returns:
        The cropped ``Dataset``.

    Raises:
        ValueError: when nothing has been drawn yet.
    """
    bbox = self.drawn_geometry
    if not isinstance(bbox, tuple):
        raise ValueError(
            "aoi_crop() needs a drawn box — call draw('box') and draw a region first"
        )
    return dataset.crop(bbox=bbox, epsg=self.crs)

cross_filter(*panels, selection_mode='union', cross_filter_mode='intersect', index_cols=None, selected_color=None, unselected_color=None, unselected_alpha=0.1, show_regions=True) #

Link selections across panels so brushing one cross-filters the others (DI.8 / IN-5).

Wraps holoviews.selection.link_selections and — the point of IN-5 — exposes the parameters that decide how a brush selects and lets the result be read back into Python: selection_expr on the returned linker is the live predicate, and selection_param(element) hands back the filtered data. So brushing an interactive map returns data, the same payoff :meth:aoi_crop already gives a drawn box. Needs a live kernel/server.

Parameters:

Name Type Description Default
*panels Any

HoloViews elements/overlays to link (defaults to this map's render when empty).

()
selection_mode str

How a new box combines with the current selection on one element — "union" (default), "intersect", "overwrite" or "inverse".

'union'
cross_filter_mode str

How selections combine across elements — "intersect" (default) or "overwrite".

'intersect'
index_cols list | None

Columns that identify a row across elements, so a selection in one table highlights the same records in another; None links by the geometry/position instead.

None
selected_color str | None

Colour drawn for selected glyphs; None keeps HoloViews' default.

None
unselected_color str | None

Colour drawn for unselected glyphs; None keeps the default.

None
unselected_alpha float

Opacity of the unselected glyphs, so the selection stands out.

0.1
show_regions bool

Draw the selection geometry (the box/lasso) over the data.

True

Returns:

Type Description
Any

The link_selections instance applied to the panels. Read .selection_expr for the live

Any

predicate, or .selection_param(element) for the filtered data.

Examples:

  • Link a map to a companion panel and read the brush settings back off the linker; its selection_expr is the live predicate a kernel updates as you drag:
    >>> from pyramids.dataset import Dataset                      # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap       # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")      # doctest: +SKIP
    >>> linker = InteractiveMap().field(dem).cross_filter(        # doctest: +SKIP
    ...     selection_mode="intersect", unselected_alpha=0.3
    ... )
    >>> linker.selection_mode                                     # doctest: +SKIP
    'intersect'
    >>> linker.unselected_alpha                                   # doctest: +SKIP
    0.3
    
Source code in src/digitalearth/interactive/app/interaction.py
def cross_filter(
    self,
    *panels: Any,
    selection_mode: str = "union",
    cross_filter_mode: str = "intersect",
    index_cols: list | None = None,
    selected_color: str | None = None,
    unselected_color: str | None = None,
    unselected_alpha: float = 0.1,
    show_regions: bool = True,
) -> Any:
    """Link selections across ``panels`` so brushing one cross-filters the others (DI.8 / IN-5).

    Wraps ``holoviews.selection.link_selections`` and — the point of IN-5 — exposes the parameters that
    decide *how* a brush selects and lets the result be read back into Python: ``selection_expr`` on the
    returned linker is the live predicate, and ``selection_param(element)`` hands back the filtered data.
    So brushing an interactive map returns data, the same payoff :meth:`aoi_crop` already gives a drawn
    box. Needs a live kernel/server.

    Args:
        *panels: HoloViews elements/overlays to link (defaults to this map's render when empty).
        selection_mode: How a new box combines with the current selection *on one element* —
            ``"union"`` (default), ``"intersect"``, ``"overwrite"`` or ``"inverse"``.
        cross_filter_mode: How selections combine *across* elements — ``"intersect"`` (default) or
            ``"overwrite"``.
        index_cols: Columns that identify a row across elements, so a selection in one table highlights
            the same records in another; ``None`` links by the geometry/position instead.
        selected_color: Colour drawn for selected glyphs; ``None`` keeps HoloViews' default.
        unselected_color: Colour drawn for unselected glyphs; ``None`` keeps the default.
        unselected_alpha: Opacity of the unselected glyphs, so the selection stands out.
        show_regions: Draw the selection geometry (the box/lasso) over the data.

    Returns:
        The ``link_selections`` instance applied to the panels. Read ``.selection_expr`` for the live
        predicate, or ``.selection_param(element)`` for the filtered data.

    Examples:
        - Link a map to a companion panel and read the brush settings back off the linker; its
          ``selection_expr`` is the live predicate a kernel updates as you drag:
            ```python
            >>> from pyramids.dataset import Dataset                      # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap       # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")      # doctest: +SKIP
            >>> linker = InteractiveMap().field(dem).cross_filter(        # doctest: +SKIP
            ...     selection_mode="intersect", unselected_alpha=0.3
            ... )
            >>> linker.selection_mode                                     # doctest: +SKIP
            'intersect'
            >>> linker.unselected_alpha                                   # doctest: +SKIP
            0.3

            ```
    """
    gv, hv = _require_holoviz()
    from holoviews.selection import link_selections

    targets = list(panels) if panels else [self.render()]
    combined = targets[0]
    for panel in targets[1:]:
        combined = combined + panel
    options: dict[str, Any] = {
        "selection_mode": selection_mode,
        "cross_filter_mode": cross_filter_mode,
        "unselected_alpha": unselected_alpha,
        "show_regions": show_regions,
    }
    if index_cols is not None:
        options["index_cols"] = index_cols
    if selected_color is not None:
        options["selected_color"] = selected_color
    if unselected_color is not None:
        options["unselected_color"] = unselected_color
    linker = link_selections.instance(**options)
    linker(combined)
    return linker

layer_control(*, layers=None, position='top-right', controls=None, reorder=False) #

Build a layer manager — per-layer visibility, an opacity slider, a basemap switch (DI.13).

The three keywords are the ones the Tier-2 contract declares and the web tier answers to as well — the layers to include, the position, the controls to expose — and the map comes back, so one call adds a layer control on either tier (#264). The panel itself is held on the map and read back through :attr:layer_control_panel; before, this method returned it, and so ended any chain it appeared in.

The toggle order follows draw order — the order layers is in, which is the band each layer's kind declares and then the order they were built in within that band, so a basemap added last is still the first toggle. reorder=True adds a ▲/▼ button per offered layer that moves it within its band (move_layer(layer_id, index)) and re-stacks the overlay live (IN-1); it is off by default because the buttons are furniture most maps do not need. It is still not one of the controls: those are the vocabulary the two tiers share, and only this tier builds the reorder buttons, so advertising it there would make the web tier refuse a name this one honours.

The control is keyed by layer id, not by the position a layer held when it was built: toggling, reordering and removing all address the layer, so the switch keeps working after the overlay is re-stacked or a layer is taken off the map.

Bokeh renders tiles in EPSG:3857 only, so the basemap switch is Web-Mercator-only — and which way that lands depends on whether it was asked for. Left at the default controls the switch is furniture this method offers unprompted, so a non-Mercator map drops it and logs why; named in controls it is an explicit request, and a non-Mercator map is refused with its CRS named. That is the one policy this module applies to an explicit basemap request — the same answer dashboard(widgets=("basemap",)) gives.

Parameters:

Name Type Description Default
layers Sequence[str] | None

The layers to offer, by id from :attr:~digitalearth.interactive.core.base.InteractiveMapBase.layer_ids; None (default) offers every layer on the map. A layer left out is hidden from the switch, not from the map — it stays in the composed overlay whatever the toggles say, which is what the web tier's layers= means too.

None
position str

Which of :data:~digitalearth.base.controls.CONTROL_POSITIONS the widget column sits in. The corner is honoured as far as a two-cell row can: *-left puts the widgets before the map and *-right after it, while top-*/bottom-* align the column to the top or the bottom of the row. Note "top-right" is the default both tiers share, so the widgets sit to the right of the map rather than the left.

'top-right'
controls Sequence[str] | None

Which controls to expose, from :data:~digitalearth.base.controls.LAYER_CONTROLS; None (default) offers all three, and "visibility" cannot be dropped. Naming a control is an explicit request — see the basemap policy above.

None
reorder bool

Add a ▲/▼ reorder button per offered layer (IN-1). False (default) builds visibility/opacity/basemap only.

False

Returns:

Type Description
Self

The same map instance, so builder calls chain. The panel is :attr:layer_control_panel.

Raises:

Type Description
ValueError

when position is not one of the four corners; when controls names something outside the shared vocabulary, drops "visibility", or names a control this tier cannot build; when there are no layers to control; when a layers id is not on this map; or when "basemap" is named on a map whose display CRS is not EPSG:3857 (Bokeh renders tiles in Web Mercator only).

Examples:

  • One toggle per registered layer, labelled by index and element type, in draw order, carrying each layer's id as its value — and the map comes back, so the control is part of the chain rather than the end of it:
    >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
    >>> from pyramids.feature import FeatureCollection             # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
    >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
    >>> m = InteractiveMap().field(dem).points(fc).layer_control()  # doctest: +SKIP
    >>> list(m.layer_control_panel[1][0].options)                  # doctest: +SKIP
    ['0: Image', '1: Points']
    
  • reorder=True adds the move buttons, so the overlay can be re-stacked from the control:
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> m = InteractiveMap().field(dem).points(fc).layer_control(reorder=True)  # doctest: +SKIP
    >>> bool(m.layer_control_panel.select(type(m.layer_control_panel[1][-1][0])))  # doctest: +SKIP
    True
    
  • Unprompted, the switch is furniture: on a Web-Mercator map the controls are toggles + opacity + basemap; on any other display CRS it is dropped (and logged) rather than drawn misaligned:
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> mercator = InteractiveMap().field(dem).layer_control()     # doctest: +SKIP
    >>> len(mercator.layer_control_panel[1])                       # doctest: +SKIP
    3
    >>> other = InteractiveMap(crs=4326).field(dem).layer_control()  # doctest: +SKIP
    >>> len(other.layer_control_panel[1])                          # doctest: +SKIP
    2
    
  • Named outright, the same condition is refused instead, with the display CRS named:
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> try:                                                       # doctest: +SKIP
    ...     other.layer_control(controls=("visibility", "basemap"))
    ... except ValueError as error:
    ...     print(str(error).split(" — ")[0])
    layer_control basemap() needs the Web-Mercator display CRS (crs=3857)
    
See Also

layer_control_panel: the panel this builds, held on the map. digitalearth.base.controls.resolved_controls: the shared control vocabulary.

Source code in src/digitalearth/interactive/app/dashboard.py
def layer_control(
    self,
    *,
    layers: Sequence[str] | None = None,
    position: str = "top-right",
    controls: Sequence[str] | None = None,
    reorder: bool = False,
) -> Self:
    """Build a layer manager — per-layer visibility, an opacity slider, a basemap switch (DI.13).

    The three keywords are the ones the Tier-2 contract declares and the web tier answers to as well —
    the layers to include, the position, the controls to expose — and **the map comes back**, so one call
    adds a layer control on either tier (#264). The panel itself is held on the map and read back through
    :attr:`layer_control_panel`; before, this method returned it, and so ended any chain it appeared in.

    The toggle order follows **draw** order — the order `layers` is in, which is the band each layer's
    kind declares and then the order they were built in within that band, so a basemap added last is
    still the first toggle. ``reorder=True`` adds a ``▲``/``▼`` button per offered layer that moves it
    within its band (``move_layer(layer_id, index)``) and re-stacks the overlay live (IN-1); it is **off
    by default** because the buttons are furniture most maps do not need. It is still not one of the
    ``controls``: those are the vocabulary the two tiers share, and only this tier builds the reorder
    buttons, so advertising it there would make the web tier refuse a name this one honours.

    The control is keyed by layer **id**, not by the position a layer held when it was built: toggling,
    reordering and removing all address the layer, so the switch keeps working after the overlay is
    re-stacked or a layer is taken off the map.

    Bokeh renders tiles in EPSG:3857 only, so the basemap switch is Web-Mercator-only — and which
    way that lands depends on whether it was *asked for*. Left at the default ``controls`` the switch
    is furniture this method offers unprompted, so a non-Mercator map drops it and logs why; named in
    ``controls`` it is an explicit request, and a non-Mercator map is refused with its CRS named. That
    is the one policy this module applies to an explicit basemap request — the same answer
    ``dashboard(widgets=("basemap",))`` gives.

    Args:
        layers: The layers to offer, by id from
            :attr:`~digitalearth.interactive.core.base.InteractiveMapBase.layer_ids`; ``None`` (default)
            offers every layer on the map. A layer left out is hidden from the switch, **not** from the
            map — it stays in the composed overlay whatever the toggles say, which is what the web
            tier's ``layers=`` means too.
        position: Which of :data:`~digitalearth.base.controls.CONTROL_POSITIONS` the widget column sits
            in. The corner is honoured as far as a two-cell row can: ``*-left`` puts the widgets before
            the map and ``*-right`` after it, while ``top-*``/``bottom-*`` align the column to the top or
            the bottom of the row. Note ``"top-right"`` is the default both tiers share, so the widgets
            sit to the **right** of the map rather than the left.
        controls: Which controls to expose, from
            :data:`~digitalearth.base.controls.LAYER_CONTROLS`; ``None`` (default) offers all three, and
            ``"visibility"`` cannot be dropped. Naming a control is an explicit request — see the
            basemap policy above.
        reorder: Add a ``▲``/``▼`` reorder button per offered layer (IN-1). ``False`` (default) builds
            visibility/opacity/basemap only.

    Returns:
        The same map instance, so builder calls chain. The panel is :attr:`layer_control_panel`.

    Raises:
        ValueError: when ``position`` is not one of the four corners; when ``controls`` names something
            outside the shared vocabulary, drops ``"visibility"``, or names a control this tier cannot
            build; when there are no layers to control; when a ``layers`` id is not on this map; or when
            ``"basemap"`` is named on a map whose display CRS is not EPSG:3857 (Bokeh renders tiles in
            Web Mercator only).

    Examples:
        - One toggle per registered layer, labelled by index and element type, in draw order, carrying
          each layer's id as its value — and the map comes back, so the control is part of the chain
          rather than the end of it:
            ```python
            >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
            >>> from pyramids.feature import FeatureCollection             # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
            >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
            >>> m = InteractiveMap().field(dem).points(fc).layer_control()  # doctest: +SKIP
            >>> list(m.layer_control_panel[1][0].options)                  # doctest: +SKIP
            ['0: Image', '1: Points']

            ```
        - ``reorder=True`` adds the move buttons, so the overlay can be re-stacked from the control:
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> m = InteractiveMap().field(dem).points(fc).layer_control(reorder=True)  # doctest: +SKIP
            >>> bool(m.layer_control_panel.select(type(m.layer_control_panel[1][-1][0])))  # doctest: +SKIP
            True

            ```
        - Unprompted, the switch is furniture: on a Web-Mercator map the controls are toggles +
          opacity + basemap; on any other display CRS it is dropped (and logged) rather than
          drawn misaligned:
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> mercator = InteractiveMap().field(dem).layer_control()     # doctest: +SKIP
            >>> len(mercator.layer_control_panel[1])                       # doctest: +SKIP
            3
            >>> other = InteractiveMap(crs=4326).field(dem).layer_control()  # doctest: +SKIP
            >>> len(other.layer_control_panel[1])                          # doctest: +SKIP
            2

            ```
        - Named outright, the same condition is refused instead, with the display CRS named:
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> try:                                                       # doctest: +SKIP
            ...     other.layer_control(controls=("visibility", "basemap"))
            ... except ValueError as error:
            ...     print(str(error).split(" — ")[0])
            layer_control basemap() needs the Web-Mercator display CRS (crs=3857)

            ```

    See Also:
        layer_control_panel: the panel this builds, held on the map.
        digitalearth.base.controls.resolved_controls: the shared control vocabulary.
    """
    pn = _require_panel()
    # Before the labels are built. A map built with `tiles=` defers its basemap until something renders,
    # and the flush inserts it at index 0 — so labels frozen beforehand named the layer one place to
    # their left, and the control drew the basemap where the data should be (review H10).
    self._flush_deferred_tiles()
    check_control_position(position)
    wanted, requested = _controls_named(
        controls, caller="InteractiveMap.layer_control()"
    )
    if not self.layers:
        raise ValueError(
            "layer_control() needs at least one layer — add a builder call first"
        )
    offered = self._control_layer_indices(layers)
    # Label → id, in draw order. The label still shows the build-time position for a human to read, but
    # the control carries the **id**: a toggle, a reorder or a removal addresses the layer, not the
    # position it happened to hold when the control was built (IN-1).
    offered_ids = [self.layer_ids[index] for index in offered]
    label_to_id = {
        f"{index}: {type(self.layers[index]).__name__}": layer_id
        for index, layer_id in zip(offered, offered_ids)
    }
    widgets = self._layer_control_widgets(
        pn, wanted, label_to_id=label_to_id, requested=requested
    )
    # A layer nobody offered is not a layer the viewer chose to hide, so it is composed in whatever the
    # toggles say — the same thing `layers=` means on the web tier, where the switch lists a subset of a
    # map that still draws all of it. Named by id, so a reorder cannot turn "always on" into a different
    # layer than the one the caller left off the switch.
    offered_set = set(offered_ids)
    bound: dict = {
        "shown": widgets["visibility"],
        "always": tuple(
            layer_id for layer_id in self.layer_ids if layer_id not in offered_set
        ),
    }
    if "opacity" in widgets:
        bound["op"] = widgets["opacity"]
    if "basemap" in widgets:
        bound["basemap"] = widgets["basemap"]
    view = pn.bind(self._compose_visible_layers, **bound)
    controls_built = list(widgets.values())
    if reorder:
        # Reordering is `move_layer(layer_id, index)`, which this tier has; what no tier had was a
        # widget to drive it (#242). A pair of up/down buttons per offered layer is that widget: each
        # click moves the layer within its band and re-triggers the composed view, so the overlay
        # re-stacks live. The toggles keep working across the move because they carry ids, not positions.
        controls_built.append(
            self._reorder_controls(pn, offered_ids, widgets["visibility"])
        )
    # The corner, as far as a row of two cells can honour one: the side is the order of the cells, and
    # the top/bottom half is the column's own alignment across the row.
    column = pn.Column(
        *controls_built, align="start" if position.startswith("top") else "end"
    )
    body = pn.panel(view)
    self._layer_control_panel = (
        pn.Row(column, body) if position.endswith("left") else pn.Row(body, column)
    )
    return self

attribute_table(features, *, linked=False, source=None) #

Build a Tabulator attribute table of a vector FeatureCollection (DI.13 / IN-5).

With linked=False (the default) the table is a read-only view of the attributes. With linked=True it is a two-way selection companion to the map: a Selection1D stream is shared between the table's row selection and a map layer's element, so selecting rows highlights the matching geometry and brushing the map selects the matching rows. Either way the cells are disabled so the view cannot be edited into disagreeing with the data.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection (or GeoDataFrame) whose non-geometry columns populate the table.

required
linked bool

When True (IN-5), wire a two-way selection link to source — the table becomes row-selectable and its selection mirrors the map's, in both directions, through one shared Selection1D stream (a re-entrancy guard stops the echo). Needs a live kernel to round-trip a gesture, but the Python link itself is live immediately.

False
source Any

The map layer the link listens on; defaults to the layer added last. Ignored when linked=False.

None

Returns:

Type Description
Any

A panel.widgets.Tabulator of the attribute columns — paginated and disabled; row-

Any

selectable and selection-linked to the map when linked=True.

Raises:

Type Description
ValueError

when linked=True but the map has no layer to link to.

Examples:

  • The geometry column is dropped; what is left is the attributes, unchanged:
    >>> from pyramids.feature import FeatureCollection             # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
    >>> table = InteractiveMap().attribute_table(fc)               # doctest: +SKIP
    >>> list(table.value.columns)                                  # doctest: +SKIP
    ['fid']
    >>> len(table.value) == len(fc)                                # doctest: +SKIP
    True
    
  • linked=True returns a row-selectable table whose selection drives the map and back:
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> m = InteractiveMap().points(fc)                           # doctest: +SKIP
    >>> table = m.attribute_table(fc, linked=True)                 # doctest: +SKIP
    >>> table.selection = [0, 2]        # selecting rows ...        # doctest: +SKIP
    >>> m._table_links[-1][1].index     # ... drives the stream     # doctest: +SKIP
    [0, 2]
    
Source code in src/digitalearth/interactive/app/dashboard.py
def attribute_table(
    self, features: Any, *, linked: bool = False, source: Any = None
) -> Any:
    """Build a ``Tabulator`` attribute table of a vector ``FeatureCollection`` (DI.13 / IN-5).

    With ``linked=False`` (the default) the table is a **read-only view** of the attributes. With
    ``linked=True`` it is a **two-way selection companion** to the map: a ``Selection1D`` stream is
    shared between the table's row selection and a map layer's element, so selecting rows highlights the
    matching geometry and brushing the map selects the matching rows. Either way the cells are
    ``disabled`` so the view cannot be edited into disagreeing with the data.

    Args:
        features: A pyramids ``FeatureCollection`` (or GeoDataFrame) whose non-geometry columns
            populate the table.
        linked: When ``True`` (IN-5), wire a two-way selection link to ``source`` — the table becomes
            row-selectable and its selection mirrors the map's, in both directions, through one shared
            ``Selection1D`` stream (a re-entrancy guard stops the echo). Needs a live kernel to
            round-trip a *gesture*, but the Python link itself is live immediately.
        source: The map layer the link listens on; defaults to the layer added last. Ignored when
            ``linked=False``.

    Returns:
        A ``panel.widgets.Tabulator`` of the attribute columns — paginated and ``disabled``; row-
        selectable and selection-linked to the map when ``linked=True``.

    Raises:
        ValueError: when ``linked=True`` but the map has no layer to link to.

    Examples:
        - The geometry column is dropped; what is left is the attributes, unchanged:
            ```python
            >>> from pyramids.feature import FeatureCollection             # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> fc = FeatureCollection.read_file("tests/data/points.geojson")  # doctest: +SKIP
            >>> table = InteractiveMap().attribute_table(fc)               # doctest: +SKIP
            >>> list(table.value.columns)                                  # doctest: +SKIP
            ['fid']
            >>> len(table.value) == len(fc)                                # doctest: +SKIP
            True

            ```
        - ``linked=True`` returns a row-selectable table whose selection drives the map and back:
            ```python
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> m = InteractiveMap().points(fc)                           # doctest: +SKIP
            >>> table = m.attribute_table(fc, linked=True)                 # doctest: +SKIP
            >>> table.selection = [0, 2]        # selecting rows ...        # doctest: +SKIP
            >>> m._table_links[-1][1].index     # ... drives the stream     # doctest: +SKIP
            [0, 2]

            ```
    """
    pn = _require_panel()
    pn.extension("tabulator")
    frame = features.drop(columns=[features.geometry.name], errors="ignore")
    if not linked:
        return pn.widgets.Tabulator(
            frame, disabled=True, pagination="remote", page_size=20
        )
    return self._linked_attribute_table(frame, source=source)

share(*, params=('cmap', 'extent', 'time', 'basemap')) #

Sync the listed view parameters into the URL for a shareable, reproducible view (DI.13).

Uses panel.state.location — available only under a running panel serve. Off-server (e.g. in a notebook or test) it returns the params it would sync rather than failing, so the call is safe everywhere. A pyramids-backed app must be served, not exported to WASM/Pyodide (no GDAL in the browser).

Parameters:

Name Type Description Default
params Sequence[str]

The view parameters to serialise into the URL query string.

('cmap', 'extent', 'time', 'basemap')

Returns:

Type Description
Any

The panel.io.location.Location it synced to, or the params tuple when off-server.

Source code in src/digitalearth/interactive/app/dashboard.py
def share(
    self, *, params: Sequence[str] = ("cmap", "extent", "time", "basemap")
) -> Any:
    """Sync the listed view parameters into the URL for a shareable, reproducible view (DI.13).

    Uses ``panel.state.location`` — available only under a running ``panel serve``. Off-server
    (e.g. in a notebook or test) it returns the params it *would* sync rather than failing, so the
    call is safe everywhere. A pyramids-backed app must be **served**, not exported to WASM/Pyodide
    (no GDAL in the browser).

    Args:
        params: The view parameters to serialise into the URL query string.

    Returns:
        The ``panel.io.location.Location`` it synced to, or the ``params`` tuple when off-server.
    """
    pn = _require_panel()
    location = getattr(pn.state, "location", None)
    if location is None:  # off-server (notebook/test) — nothing to bind to yet
        return tuple(params)
    location.sync(self, {name: name for name in params})
    return location

dashboard(*, widgets=_DEFAULT_DASHBOARD_WIDGETS, sidebar=True, title='', template=None) #

Wrap the map and reactive widgets into a Panel layout.

The returned object is a panel.viewable.Viewable: a sidebar (or inline row) of widgets bound to the map's style, beside the live map. The widget set is a declared vocabulary (IN-9), :data:_DASHBOARD_WIDGETS — "cmap" (colormap selector), "alpha" (opacity slider), "basemap" (tile-provider selector, Web-Mercator-only) — so a name outside it is refused with a did-you-mean rather than silently dropped, and a new widget is one entry, not another elif.

Parameters:

Name Type Description Default
widgets Sequence[str]

Which widgets to expose, in order.

_DEFAULT_DASHBOARD_WIDGETS
sidebar bool

Lay widgets out in a left sidebar (True) or a top row (False). Ignored when template is given — a template has its own sidebar.

True
title str

Dashboard title (falls back to the map's title).

''
template str | None

A Panel template to host the app in (IN-9) — "fast", "bootstrap", "material" or "vanilla". None (default) returns the plain row/column layout.

None

Returns:

Type Description
Any

A panel.viewable.Viewable hosting the map + widgets — a template instance when template

Any

is given, else the row/column layout.

Raises:

Type Description
ValueError

for an unknown widget name (with a did-you-mean), an unknown template name, or when "basemap" is requested on a map whose display CRS is not EPSG:3857 (Bokeh renders tiles in Web Mercator only).

Examples:

  • Build a dashboard with colormap + opacity controls:
    >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
    >>> app = InteractiveMap().field(dem).dashboard(widgets=("cmap", "alpha"))  # doctest: +SKIP
    >>> sorted({w.name for w in app.select()} & {"Colormap", "Opacity"})  # doctest: +SKIP
    ['Colormap', 'Opacity']
    
Source code in src/digitalearth/interactive/app/dashboard.py
def dashboard(
    self,
    *,
    widgets: Sequence[str] = _DEFAULT_DASHBOARD_WIDGETS,
    sidebar: bool = True,
    title: str = "",
    template: str | None = None,
) -> Any:
    """Wrap the map and reactive widgets into a Panel layout.

    The returned object is a ``panel.viewable.Viewable``: a sidebar (or inline row) of widgets
    bound to the map's style, beside the live map. The widget set is a **declared vocabulary** (IN-9),
    :data:`_DASHBOARD_WIDGETS` — ``"cmap"`` (colormap selector), ``"alpha"`` (opacity slider),
    ``"basemap"`` (tile-provider selector, Web-Mercator-only) — so a name outside it is refused with a
    did-you-mean rather than silently dropped, and a new widget is one entry, not another ``elif``.

    Args:
        widgets: Which widgets to expose, in order.
        sidebar: Lay widgets out in a left sidebar (``True``) or a top row (``False``). Ignored when
            ``template`` is given — a template has its own sidebar.
        title: Dashboard title (falls back to the map's ``title``).
        template: A Panel template to host the app in (IN-9) — ``"fast"``, ``"bootstrap"``,
            ``"material"`` or ``"vanilla"``. ``None`` (default) returns the plain row/column layout.

    Returns:
        A ``panel.viewable.Viewable`` hosting the map + widgets — a template instance when ``template``
        is given, else the row/column layout.

    Raises:
        ValueError: for an unknown widget name (with a did-you-mean), an unknown ``template`` name, or
            when ``"basemap"`` is requested on a map whose display CRS is not EPSG:3857 (Bokeh renders
            tiles in Web Mercator only).

    Examples:
        - Build a dashboard with colormap + opacity controls:
            ```python
            >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
            >>> app = InteractiveMap().field(dem).dashboard(widgets=("cmap", "alpha"))  # doctest: +SKIP
            >>> sorted({w.name for w in app.select()} & {"Colormap", "Opacity"})  # doctest: +SKIP
            ['Colormap', 'Opacity']

            ```
    """
    pn = _require_panel()
    controls, bindings = self._build_widgets(pn, widgets)

    def _view(**values: Any) -> Any:
        return self._render_with_overrides(values)

    view = pn.bind(_view, **bindings)
    panel_map = pn.panel(view)
    if template is not None:
        return self._templated(pn, template, controls, panel_map, title)
    heading = (
        pn.pane.Markdown(f"## {title or self.title}")
        if (title or self.title)
        else None
    )
    controls_box = pn.Column(*controls) if controls else None
    if sidebar:
        body = (
            pn.Row(controls_box, panel_map) if controls_box else pn.Row(panel_map)
        )
    else:
        body = (
            pn.Column(controls_box, panel_map)
            if controls_box
            else pn.Column(panel_map)
        )
    return pn.Column(heading, body) if heading else body

serve(*, start=False, onload=None, periodic=None, period_ms=1000, threaded=True, num_procs=1, **kwargs) #

Deploy the dashboard: wire its per-session state, mark it servable, optionally launch it (IN-10).

Previously this only called app.servable(). Now the deployment is modelled and its session state is wired through pn.state: an onload hook runs per connecting session, and a periodic callback refreshes the view on a timer — the live half of IN-10, beside :meth:export_plan's export half. With start=True it actually launches a pn.serve server (threaded) and returns it; otherwise it marks the app servable (for panel serve app.py) and returns the viewable.

Parameters:

Name Type Description Default
start bool

When True, launch a pn.serve server now and return it; when False (default), mark the app servable and return the viewable for panel serve.

False
onload Callable | None

A no-arg callable run once per session when a viewer connects, via pn.state.onload — where per-session data (a user's AOI, a cached read) is initialised.

None
periodic Callable | None

A no-arg callable run every period_ms via pn.state.add_periodic_callback — a live data refresh. It is created per session when the session loads (not at call time, so no timer spins before a viewer connects), and each session's handle is kept on the map so close() can stop it.

None
period_ms int

The period for periodic, in milliseconds.

1000
threaded bool

Passed to pn.serve when start=True; also modelled in :meth:serve_plan.

True
num_procs int

Passed to pn.serve when start=True; also modelled in :meth:serve_plan.

1
**kwargs Any

Forwarded to :meth:dashboard.

{}

Returns:

Type Description
Any

The running panel.io.server.Server when start=True, else the servable

Any

panel.viewable.Viewable.

Source code in src/digitalearth/interactive/app/dashboard.py
def serve(
    self,
    *,
    start: bool = False,
    onload: Callable | None = None,
    periodic: Callable | None = None,
    period_ms: int = 1000,
    threaded: bool = True,
    num_procs: int = 1,
    **kwargs: Any,
) -> Any:
    """Deploy the dashboard: wire its per-session state, mark it servable, optionally launch it (IN-10).

    Previously this only called ``app.servable()``. Now the deployment is modelled and its session state
    is wired through ``pn.state``: an ``onload`` hook runs per connecting session, and a ``periodic``
    callback refreshes the view on a timer — the live half of IN-10, beside :meth:`export_plan`'s export
    half. With ``start=True`` it actually launches a ``pn.serve`` server (threaded) and returns it;
    otherwise it marks the app servable (for ``panel serve app.py``) and returns the viewable.

    Args:
        start: When ``True``, launch a ``pn.serve`` server now and return it; when ``False`` (default),
            mark the app servable and return the viewable for ``panel serve``.
        onload: A no-arg callable run once per session when a viewer connects, via ``pn.state.onload`` —
            where per-session data (a user's AOI, a cached read) is initialised.
        periodic: A no-arg callable run every ``period_ms`` via ``pn.state.add_periodic_callback`` —
            a live data refresh. It is created per session when the session loads (not at call time, so
            no timer spins before a viewer connects), and each session's handle is kept on the map so
            ``close()`` can stop it.
        period_ms: The period for ``periodic``, in milliseconds.
        threaded: Passed to ``pn.serve`` when ``start=True``; also modelled in :meth:`serve_plan`.
        num_procs: Passed to ``pn.serve`` when ``start=True``; also modelled in :meth:`serve_plan`.
        **kwargs: Forwarded to :meth:`dashboard`.

    Returns:
        The running ``panel.io.server.Server`` when ``start=True``, else the servable
        ``panel.viewable.Viewable``.
    """
    pn = _require_panel()
    app = self.dashboard(**kwargs)
    # Per-session state (IN-10), installed through a single `pn.state.onload` hook so it attaches **per
    # connecting session**, not once at call time (review R2-M1). `add_periodic_callback` starts its timer
    # the instant it is created, so creating it here would spin a live timer before any viewer exists and
    # register the hooks against whatever `curdoc` happened to be current; deferring both to onload makes
    # the per-session claim true and leaves `serve(start=False)` a pure "mark servable" until a session
    # loads. Each session's periodic handle is kept on the map so `close()` can stop it.
    if onload is not None or periodic is not None:

        def _install_session_state() -> None:
            """Run the caller's onload and start this session's periodic refresh, once per session."""
            if onload is not None:
                onload()
            if periodic is not None:
                self._session_callbacks.append(
                    pn.state.add_periodic_callback(periodic, period=period_ms)
                )

        pn.state.onload(_install_session_state)
    app.servable()
    if start:
        return pn.serve(app, threaded=threaded, num_procs=num_procs, show=False)
    return app

save_app(path, *, embed=True, **kwargs) #

Export the dashboard to a standalone HTML file (no server).

Panel's embed bakes the discrete widget states into the page, so the exported file is interactive offline within Panel's combinatorial limits (a few discrete widgets; continuous sliders are sampled). A live, unrestricted app must be served, not exported — and a pyramids-backed app cannot run in WASM/Pyodide (no GDAL in the browser).

Before writing, the export is modelled with :meth:export_plan (IN-10): if embed would bake more states than the cap, the oversize is logged with the per-widget breakdown — so a truncated file is explained rather than discovered. :meth:export_plan lets a caller check this before calling here.

Parameters:

Name Type Description Default
path Any

Destination .html file (str or pathlib.Path).

required
embed bool

Bake widget states for offline interactivity (True) or export a static snapshot (False).

True
**kwargs Any

Forwarded to :meth:dashboard.

{}

Returns:

Type Description
Path

pathlib.Path: the file written, matching the tier's save/save_animation (#248).

Examples:

  • Export an offline, self-contained dashboard page:
    >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
    >>> InteractiveMap().field(dem).save_app("app.html").name     # doctest: +SKIP
    'app.html'
    
Source code in src/digitalearth/interactive/app/dashboard.py
def save_app(self, path: Any, *, embed: bool = True, **kwargs: Any) -> Path:
    """Export the dashboard to a standalone HTML file (no server).

    Panel's ``embed`` bakes the discrete widget states into the page, so the exported file is
    interactive offline within Panel's combinatorial limits (a few discrete widgets; continuous
    sliders are sampled). A live, unrestricted app must be served, not exported — and a
    pyramids-backed app cannot run in WASM/Pyodide (no GDAL in the browser).

    Before writing, the export is modelled with :meth:`export_plan` (IN-10): if ``embed`` would bake more
    states than the cap, the oversize is logged with the per-widget breakdown — so a truncated file is
    explained rather than discovered. :meth:`export_plan` lets a caller check this before calling here.

    Args:
        path: Destination ``.html`` file (``str`` or ``pathlib.Path``).
        embed: Bake widget states for offline interactivity (``True``) or export a static
            snapshot (``False``).
        **kwargs: Forwarded to :meth:`dashboard`.

    Returns:
        pathlib.Path: the file written, matching the tier's ``save``/``save_animation`` (#248).

    Examples:
        - Export an offline, self-contained dashboard page:
            ```python
            >>> from pyramids.dataset import Dataset                       # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap        # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")       # doctest: +SKIP
            >>> InteractiveMap().field(dem).save_app("app.html").name     # doctest: +SKIP
            'app.html'

            ```
    """
    if embed:
        widgets = kwargs.get("widgets", _DEFAULT_DASHBOARD_WIDGETS)
        plan = self.export_plan(widgets=widgets)
        if plan.warning is not None:
            from loguru import logger

            logger.warning(plan.warning)
    app = self.dashboard(**kwargs)
    app.save(path, embed=embed)
    return Path(path)

play(*, fps=DEFAULT_FPS, loop=True, layer=None) #

Wrap the time cube in a Panel layout with an auto-advancing Player widget.

Parameters:

Name Type Description Default
fps float

Playback frames per second (the Player interval). Defaults to :data:~digitalearth.base.animation.DEFAULT_FPS, the one rate every tier reads (#256), so the same animation plays at the same speed on every backend.

DEFAULT_FPS
loop bool

Loop at the end (True) or stop (False).

True
layer str | None

The id of the temporal layer to animate (IN-12); None animates the first one, which is the only one most maps carry.

None

Returns:

Type Description
Any

A panel.viewable.Viewable hosting the map + a bound time Player.

Raises:

Type Description
ValueError

when no timecube layer has been added.

ImportError

when the interactive extra (which provides panel) is absent.

Examples:

  • Play a time cube at the shared default speed; the player steps through the cube's own time keys, not a frame index:
    >>> from pyramids.dataset.collection import DatasetCollection     # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> cube = DatasetCollection.from_files(["jan.tif", "feb.tif"])   # doctest: +SKIP
    >>> app = InteractiveMap().timecube(cube).play()                  # doctest: +SKIP
    >>> app[1].value == app[1].options[0]   # starts on step one  # doctest: +SKIP
    True
    
  • fps is the playback rate, translated into the Player's millisecond interval — two frames a second is a 500 ms step:
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> m = InteractiveMap().timecube(cube)                          # doctest: +SKIP
    >>> app = m.play(fps=2.0, loop=False)                            # doctest: +SKIP
    >>> app[1].interval                                               # doctest: +SKIP
    500
    >>> app[1].loop_policy                                            # doctest: +SKIP
    'once'
    
  • Playback needs a time cube; anything else is refused rather than played empty:
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> try:                                                          # doctest: +SKIP
    ...     InteractiveMap().play()
    ... except ValueError as error:
    ...     print(str(error).split(" — ")[0])
    no time cube to animate
    
Source code in src/digitalearth/interactive/temporal/animation.py
def play(
    self, *, fps: float = DEFAULT_FPS, loop: bool = True, layer: str | None = None
) -> Any:
    """Wrap the time cube in a Panel layout with an auto-advancing ``Player`` widget.

    Args:
        fps: Playback frames per second (the Player interval). Defaults to
            :data:`~digitalearth.base.animation.DEFAULT_FPS`, the one rate every tier reads (#256), so
            the same animation plays at the same speed on every backend.
        loop: Loop at the end (``True``) or stop (``False``).
        layer: The id of the temporal layer to animate (IN-12); ``None`` animates the first one, which
            is the only one most maps carry.

    Returns:
        A ``panel.viewable.Viewable`` hosting the map + a bound time ``Player``.

    Raises:
        ValueError: when no ``timecube`` layer has been added.
        ImportError: when the ``interactive`` extra (which provides panel) is absent.

    Examples:
        - Play a time cube at the shared default speed; the player steps through the cube's
          own time keys, not a frame index:
            ```python
            >>> from pyramids.dataset.collection import DatasetCollection     # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> cube = DatasetCollection.from_files(["jan.tif", "feb.tif"])   # doctest: +SKIP
            >>> app = InteractiveMap().timecube(cube).play()                  # doctest: +SKIP
            >>> app[1].value == app[1].options[0]   # starts on step one  # doctest: +SKIP
            True

            ```
        - ``fps`` is the playback rate, translated into the Player's millisecond interval —
          two frames a second is a 500 ms step:
            ```python
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> m = InteractiveMap().timecube(cube)                          # doctest: +SKIP
            >>> app = m.play(fps=2.0, loop=False)                            # doctest: +SKIP
            >>> app[1].interval                                               # doctest: +SKIP
            500
            >>> app[1].loop_policy                                            # doctest: +SKIP
            'once'

            ```
        - Playback needs a time cube; anything else is refused rather than played empty:
            ```python
            >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
            >>> try:                                                          # doctest: +SKIP
            ...     InteractiveMap().play()
            ... except ValueError as error:
            ...     print(str(error).split(" — ")[0])
            no time cube to animate

            ```
    """
    import panel as pn

    gv, hv = _require_holoviz()
    dmap = self._time_dynamicmap(layer)
    # A timecube DynamicMap carries its frame keys on the kdim's explicit `.values`; a frames() HoloMap
    # carries them as its own keys instead. Take whichever is populated so both kinds play (IN-12).
    values = list(dmap.kdims[0].values) or list(dmap.keys())
    # DiscretePlayer (not Player) steps through arbitrary labelled values (ints / datetimes).
    player = pn.widgets.DiscretePlayer(
        options=values,
        value=values[0],
        interval=max(1, int(1000 / fps)),
        loop_policy="loop" if loop else "once",
    )
    view = pn.bind(lambda value: dmap[value], player)
    return pn.Column(pn.panel(view), player)

save_animation(path, *, fps=DEFAULT_FPS, layer=None, **kwargs) #

Export the time cube as a GIF/MP4 (matplotlib backend) or a scrubber HTML.

.gif/.mp4 materialise the DynamicMap to a finite HoloMap and render via the matplotlib backend (.mp4 needs ffmpeg). .html writes a client-side scrubber that plays offline with no server.

Parameters:

Name Type Description Default
path Any

Output file (.gif / .mp4 / .html), as str or pathlib.Path.

required
fps float

Frames per second. Defaults to :data:~digitalearth.base.animation.DEFAULT_FPS, the one rate every tier reads (#256).

DEFAULT_FPS
layer str | None

The id of the temporal layer to export (IN-12); None exports the first one.

None
**kwargs Any

Forwarded to :func:holoviews.save.

{}

Returns:

Type Description
Path

pathlib.Path: the file written, matching :meth:~digitalearth.interactive.core.base.InteractiveMapBase.save (#248).

Raises:

Type Description
ValueError

when no timecube layer has been added.

Examples:

  • Export a GIF; the returned Path can be inspected or moved without re-wrapping it (#248 — this used to come back as a bare str):
    >>> from pyramids.dataset.collection import DatasetCollection     # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> cube = DatasetCollection.from_files(["jan.tif", "feb.tif"])   # doctest: +SKIP
    >>> m = InteractiveMap().timecube(cube)                          # doctest: +SKIP
    >>> out = m.save_animation("rain.gif")                           # doctest: +SKIP
    >>> out.suffix, out.exists()                                      # doctest: +SKIP
    ('.gif', True)
    
  • The suffix picks the writer: .html is the client-side scrubber, which needs no server and no ffmpeg, and fps sets its playback rate:
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> out = InteractiveMap().timecube(cube).save_animation(         # doctest: +SKIP
    ...     "rain.html", fps=8.0
    ... )
    >>> out.name                                                      # doctest: +SKIP
    'rain.html'
    >>> "<html" in out.read_text(encoding="utf-8")[:200].lower()      # doctest: +SKIP
    True
    
  • Exporting needs a time cube, same as :meth:play:
    >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
    >>> try:                                                          # doctest: +SKIP
    ...     InteractiveMap().save_animation("nothing.gif")
    ... except ValueError as error:
    ...     print(str(error).split(" — ")[0])
    no time cube to animate
    
Source code in src/digitalearth/interactive/temporal/animation.py
    def save_animation(
        self,
        path: Any,
        *,
        fps: float = DEFAULT_FPS,
        layer: str | None = None,
        **kwargs: Any,
    ) -> Path:
        """Export the time cube as a GIF/MP4 (matplotlib backend) or a scrubber HTML.

        ``.gif``/``.mp4`` materialise the DynamicMap to a finite ``HoloMap`` and render via the
        matplotlib backend (``.mp4`` needs ffmpeg). ``.html`` writes a client-side **scrubber** that
        plays offline with no server.

        Args:
            path: Output file (``.gif`` / ``.mp4`` / ``.html``), as ``str`` or ``pathlib.Path``.
            fps: Frames per second. Defaults to :data:`~digitalearth.base.animation.DEFAULT_FPS`, the
                one rate every tier reads (#256).
            layer: The id of the temporal layer to export (IN-12); ``None`` exports the first one.
            **kwargs: Forwarded to :func:`holoviews.save`.

        Returns:
            pathlib.Path: the file written, matching :meth:`~digitalearth.interactive.core.base.\
InteractiveMapBase.save` (#248).

        Raises:
            ValueError: when no ``timecube`` layer has been added.

        Examples:
            - Export a GIF; the returned ``Path`` can be inspected or moved without re-wrapping it
              (#248 — this used to come back as a bare ``str``):
                ```python
                >>> from pyramids.dataset.collection import DatasetCollection     # doctest: +SKIP
                >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
                >>> cube = DatasetCollection.from_files(["jan.tif", "feb.tif"])   # doctest: +SKIP
                >>> m = InteractiveMap().timecube(cube)                          # doctest: +SKIP
                >>> out = m.save_animation("rain.gif")                           # doctest: +SKIP
                >>> out.suffix, out.exists()                                      # doctest: +SKIP
                ('.gif', True)

                ```
            - The suffix picks the writer: ``.html`` is the client-side scrubber, which needs no
              server and no ffmpeg, and ``fps`` sets its playback rate:
                ```python
                >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
                >>> out = InteractiveMap().timecube(cube).save_animation(         # doctest: +SKIP
                ...     "rain.html", fps=8.0
                ... )
                >>> out.name                                                      # doctest: +SKIP
                'rain.html'
                >>> "<html" in out.read_text(encoding="utf-8")[:200].lower()      # doctest: +SKIP
                True

                ```
            - Exporting needs a time cube, same as :meth:`play`:
                ```python
                >>> from digitalearth.interactive import InteractiveMap           # doctest: +SKIP
                >>> try:                                                          # doctest: +SKIP
                ...     InteractiveMap().save_animation("nothing.gif")
                ... except ValueError as error:
                ...     print(str(error).split(" — ")[0])
                no time cube to animate

                ```
        """
        gv, hv = _require_holoviz()
        holomap = self._to_holomap(self._time_dynamicmap(layer))
        suffix = str(path).lower().rsplit(".", 1)[-1]
        if suffix == "html":
            hv.save(holomap, path, fmt="scrubber", fps=fps, **kwargs)
        else:
            hv.save(holomap, path, backend="matplotlib", fps=fps, **kwargs)
        return Path(path)

colorbar(layer_id=None, *, label=None, visible=True) #

Show the continuous colour key of a layer (the Core name, #261, order 24).

A guide on the layer's own colour encoding rather than a show= toggle on whichever layer was added last: it is recorded first and the HoloViews options are applied from the record, so the key moves with its layer, goes away with it, and is carried by the figure.

Bokeh draws one colorbar per plot, whatever the opts say. Measured: two guided rasters overlaid, each with colorbar=True and its own clabel, render a single ColorBar — the one belonging to the layer lowest in draw order. So guiding a second layer does not stack a second bar; it decides which layer's bar is the one drawn. That is the same one-key-per-panel limit the web tier states from the other direction ("a second legend replaces the first"), and it is the engine's, not this tier's.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's key to show. None (default) takes the most recent layer whose colour varies with its data — see :meth:_guided_layer for exactly what "most recent" means, which is the care the old toggle took plus one tightening.

None
label str | None

What to call the key — the variable and its units, usually. It reaches the drawn bar as HoloViews' clabel, and is recorded as the guide's title. None leaves whatever the builder resolved (field takes its own clabel=, defaulting to the variable's units).

None
visible bool

Whether the key is drawn. False records the guide switched off and applies colorbar=False, so a caller passing a flag through does not have to branch — and the layer is resolved and checked before the flag is read, so one spelling of a call is not valid only half the time (the web tier's review L7).

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
KeyError

when layer_id names no layer on this map.

ValueError

when the named layer's colour varies with nothing, or — for None — when no layer's does. Also for a label that is not a non-empty string, which :class:~digitalearth.base.spec.encoding.Guide refuses.

ImportError

when the interactive extra is not installed.

Examples:

  • Title the raster's colour key:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().field(dem).colorbar(label="Flow (m³/s)")  # doctest: +SKIP
    >>> m.get_layer(m.layer_ids[0]).symbology.guide().title         # doctest: +SKIP
    'Flow (m³/s)'
    
  • Drop it again, by name:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().field(dem, name="flow")                # doctest: +SKIP
    >>> m.colorbar("flow", visible=False).save("m.html").name       # doctest: +SKIP
    'm.html'
    
See Also

digitalearth.base.spec.style.Symbology.with_guide: where the guide is attached.

Source code in src/digitalearth/interactive/legends/legend.py
def colorbar(
    self,
    layer_id: str | None = None,
    *,
    label: str | None = None,
    visible: bool = True,
) -> Self:
    """Show the continuous colour key of a layer (the Core name, #261, order 24).

    A guide on the layer's own colour encoding rather than a ``show=`` toggle on whichever layer was
    added last: it is recorded first and the HoloViews options are applied **from the record**, so the key
    moves with its layer, goes away with it, and is carried by the figure.

    Bokeh draws **one** colorbar per plot, whatever the opts say. Measured: two guided rasters overlaid,
    each with ``colorbar=True`` and its own ``clabel``, render a single ``ColorBar`` — the one belonging
    to the layer lowest in draw order. So guiding a second layer does not stack a second bar; it decides
    which layer's bar is the one drawn. That is the same one-key-per-panel limit the web tier states from
    the other direction ("a second legend replaces the first"), and it is the engine's, not this tier's.

    Args:
        layer_id: Which layer's key to show. `None` (default) takes the most recent layer whose colour
            varies with its data — see :meth:`_guided_layer` for exactly what "most recent" means, which
            is the care the old toggle took plus one tightening.
        label: What to call the key — the variable and its units, usually. It reaches the drawn bar as
            HoloViews' ``clabel``, and is recorded as the guide's title. `None` leaves whatever the
            builder resolved (``field`` takes its own ``clabel=``, defaulting to the variable's units).
        visible: Whether the key is drawn. `False` records the guide switched **off** and applies
            ``colorbar=False``, so a caller passing a flag through does not have to branch — and the
            layer is resolved and checked before the flag is read, so one spelling of a call is not valid
            only half the time (the web tier's review L7).

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        KeyError: when `layer_id` names no layer on this map.
        ValueError: when the named layer's colour varies with nothing, or — for `None` — when no layer's
            does. Also for a ``label`` that is not a non-empty string, which
            :class:`~digitalearth.base.spec.encoding.Guide` refuses.
        ImportError: when the ``interactive`` extra is not installed.

    Examples:
        - Title the raster's colour key:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().field(dem).colorbar(label="Flow (m³/s)")  # doctest: +SKIP
            >>> m.get_layer(m.layer_ids[0]).symbology.guide().title         # doctest: +SKIP
            'Flow (m³/s)'

            ```
        - Drop it again, by name:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().field(dem, name="flow")                # doctest: +SKIP
            >>> m.colorbar("flow", visible=False).save("m.html").name       # doctest: +SKIP
            'm.html'

            ```

    See Also:
        digitalearth.base.spec.style.Symbology.with_guide: where the guide is attached.
    """
    # Called for its actionable ImportError before anything else: every option below is applied for the
    # Bokeh backend, and `_require_holoviz` is what registers it.
    _require_holoviz()
    target = self._guided_layer("colorbar", layer_id)
    described = self._record_guide(
        target, Guide(show=bool(visible), title=label), kind="colorbar"
    )
    self._draw_guide(
        target, "colorbar", **fold_guide(described.symbology, described.label)
    )
    return self

legend(layer_id=None, *, title=None, labels=None, visible=True) #

Show the keyed colour list of a layer (the Core name, #261, order 24).

The same guide :meth:colorbar records, drawn as Bokeh's keyed box instead of a continuous bar. Both methods explain one layer's color encoding and so write one guide: calling both on a layer leaves the last title and the last visible, and draws both keys.

Bokeh builds one legend per plot, from the labelled members of the overlay, so show_legend decides whether this layer contributes a row rather than whether it gets a box of its own — measured: a single element with show_legend=True renders no legend at all, because there is no overlay to build one from. A layer's row is captioned by its name=, which is what labels renames.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's key to show. None (default) is the most recent layer whose colour varies with its data, exactly as :meth:colorbar resolves it.

None
title str | None

Heading above the key. It reaches the drawn box through Bokeh's own Legend.title, and is recorded as the guide's title.

None
labels Sequence[str] | None

Explicit row labels, replacing the derived one. A layer contributes one row to a Bokeh legend — its own label — so this takes one entry; a count that does not match is refused rather than zipped, which would drop the difference and leave rows out of the key (the web tier's rule, for the same reason).

None
visible bool

Whether the layer contributes to the key. False records the guide switched off and applies show_legend=False. Checked after the layer is resolved, never before.

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
KeyError

when layer_id names no layer on this map.

ValueError

when the named layer's colour varies with nothing, or — for None — when no layer's does; when labels does not hold one entry per row; and for a title that is not a non-empty string.

ImportError

when the interactive extra is not installed.

Examples:

  • Key a contour layer, and title the box:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().contours(dem).legend(title="Contours")  # doctest: +SKIP
    >>> m.get_layer(m.layer_ids[0]).symbology.guide().show          # doctest: +SKIP
    True
    
  • Or take it off again:
    >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
    >>> m = InteractiveMap().contours(dem).legend(visible=False)    # doctest: +SKIP
    >>> m.save("m.html").name                                       # doctest: +SKIP
    'm.html'
    
See Also

digitalearth.base.spec.style.Symbology.with_guide: where the guide is attached.

Source code in src/digitalearth/interactive/legends/legend.py
def legend(
    self,
    layer_id: str | None = None,
    *,
    title: str | None = None,
    labels: Sequence[str] | None = None,
    visible: bool = True,
) -> Self:
    """Show the keyed colour list of a layer (the Core name, #261, order 24).

    The same guide :meth:`colorbar` records, drawn as Bokeh's keyed box instead of a continuous bar. Both
    methods explain one layer's ``color`` encoding and so write one guide: calling both on a layer leaves
    the last title and the last ``visible``, and draws both keys.

    Bokeh builds **one** legend per plot, from the labelled members of the overlay, so ``show_legend``
    decides whether this layer *contributes a row* rather than whether it gets a box of its own —
    measured: a single element with ``show_legend=True`` renders no legend at all, because there is no
    overlay to build one from. A layer's row is captioned by its ``name=``, which is what ``labels``
    renames.

    Args:
        layer_id: Which layer's key to show. `None` (default) is the most recent layer whose colour
            varies with its data, exactly as :meth:`colorbar` resolves it.
        title: Heading above the key. It reaches the drawn box through Bokeh's own ``Legend.title``, and
            is recorded as the guide's title.
        labels: Explicit row labels, replacing the derived one. A layer contributes **one** row to a
            Bokeh legend — its own label — so this takes one entry; a count that does not match is
            refused rather than zipped, which would drop the difference and leave rows out of the key
            (the web tier's rule, for the same reason).
        visible: Whether the layer contributes to the key. `False` records the guide switched off and
            applies ``show_legend=False``. Checked after the layer is resolved, never before.

    Returns:
        The same map instance, so builder calls chain.

    Raises:
        KeyError: when `layer_id` names no layer on this map.
        ValueError: when the named layer's colour varies with nothing, or — for `None` — when no layer's
            does; when ``labels`` does not hold one entry per row; and for a ``title`` that is not a
            non-empty string.
        ImportError: when the ``interactive`` extra is not installed.

    Examples:
        - Key a contour layer, and title the box:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().contours(dem).legend(title="Contours")  # doctest: +SKIP
            >>> m.get_layer(m.layer_ids[0]).symbology.guide().show          # doctest: +SKIP
            True

            ```
        - Or take it off again:
            ```python
            >>> from pyramids.dataset import Dataset                        # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap         # doctest: +SKIP
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")        # doctest: +SKIP
            >>> m = InteractiveMap().contours(dem).legend(visible=False)    # doctest: +SKIP
            >>> m.save("m.html").name                                       # doctest: +SKIP
            'm.html'

            ```

    See Also:
        digitalearth.base.spec.style.Symbology.with_guide: where the guide is attached.
    """
    _require_holoviz()
    target = self._guided_layer("legend", layer_id)
    rows = None if labels is None else list(labels)
    derived = [self._layer_tree.get(target).label]
    if rows is not None and len(rows) != len(derived):
        # Refused before the guide is recorded, so a rejected call leaves the description untouched.
        raise ValueError(
            f"legend(labels=...) has {len(rows)} entries and layer {target!r} contributes "
            f"{len(derived)} row to a Bokeh legend ({derived[0]!r}); zip would drop the difference and "
            "leave rows out of the key"
        )
    described = self._record_guide(
        target, Guide(show=bool(visible), title=title), kind="legend", labels=rows
    )
    self._draw_guide(
        target, "legend", **fold_guide(described.symbology, described.label)
    )
    return self

get_layer(layer_id) #

Return the description of one layer, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to look up.

required

Returns:

Name Type Description
Its LayerSpec

class:~digitalearth.base.spec.LayerSpec — kind, source, symbology, band and visibility.

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do.

Examples:

  • What a builder recorded, read back by id:
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().add_layer("mine", name="obs").get_layer("obs").kind
    'custom:holoviews'
    
Source code in src/digitalearth/interactive/core/base.py
def get_layer(self, layer_id: str) -> LayerSpec:
    """Return the description of one layer, by id.

    Args:
        layer_id: The layer to look up.

    Returns:
        Its :class:`~digitalearth.base.spec.LayerSpec` — kind, source, symbology, band and visibility.

    Raises:
        KeyError: if no layer has that id, naming the ids that do.

    Examples:
        - What a builder recorded, read back by id:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> InteractiveMap().add_layer("mine", name="obs").get_layer("obs").kind
            'custom:holoviews'

            ```
    """
    self._require_layer(layer_id)
    return self._layer_tree.get(layer_id)

move_layer(layer_id, index) #

Move a layer in draw order, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to move.

required
index int

Its position afterwards, counted as a list index is — 0 is the bottom, -1 the top. A layer moves within its band: reordering the data layers is what a layer switcher does, and dragging the basemap over them is not.

required

Returns:

Type Description
Self

This map (chainable).

Raises:

Type Description
KeyError

if no layer has that id.

IndexError

if the position is outside the map, or outside the layer's band.

Note

This reaches the picture: render() overlays :attr:layers bottom first, and :meth:_change rebuilds that list in the new order.

Examples:

  • Two layers, reordered by id:
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap().add_layer("under", name="under")
    >>> m = m.add_layer("over", name="over")
    >>> m.move_layer("over", 0).layer_ids
    ['over', 'under']
    >>> m.layers
    ['over', 'under']
    
Source code in src/digitalearth/interactive/core/base.py
def move_layer(self, layer_id: str, index: int) -> Self:
    """Move a layer in draw order, by id.

    Args:
        layer_id: The layer to move.
        index: Its position afterwards, counted as a list index is — `0` is the bottom, `-1` the top. A
            layer moves within its band: reordering the data layers is what a layer switcher does, and
            dragging the basemap over them is not.

    Returns:
        This map (chainable).

    Raises:
        KeyError: if no layer has that id.
        IndexError: if the position is outside the map, or outside the layer's band.

    Note:
        This reaches the picture: `render()` overlays :attr:`layers` bottom first, and :meth:`_change`
        rebuilds that list in the new order.

    Examples:
        - Two layers, reordered by id:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap().add_layer("under", name="under")
            >>> m = m.add_layer("over", name="over")
            >>> m.move_layer("over", 0).layer_ids
            ['over', 'under']
            >>> m.layers
            ['over', 'under']

            ```
    """
    # Asked here rather than left to `LayerTree.move`, so an unknown id is refused in the same words as
    # every other layer-management call on this tier: the tree names itself, the facade names the map.
    self._require_layer(layer_id)
    self._change(self._figure_with(self._layer_tree.move(layer_id, index)))
    return self

remove_layer(layer_id) #

Take a layer off the map, by id.

Parameters:

Name Type Description Default
layer_id str

The layer to remove.

required

Returns:

Type Description
Self

This map (chainable).

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do — a silent no-op here would look exactly like a layer that refused to go away.

Note

The id goes back to the pool, so a name removed and asked for again is handed back unsuffixed: an id is reserved exactly while the layer is on the map, which is the lifetime all four tiers share (:func:~digitalearth.base.spec.layer.free_layer_id).

The in-memory data is not forgotten. A figure_spec captured before the removal still names it, and drawing that figure again needs it; :meth:close is where this map lets its data go.

Examples:

  • A layer added and then removed leaves nothing behind:
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap().add_layer("mine", name="obs")
    >>> m.remove_layer("obs").layer_ids
    []
    >>> m.layers
    []
    
Source code in src/digitalearth/interactive/core/base.py
def remove_layer(self, layer_id: str) -> Self:
    """Take a layer off the map, by id.

    Args:
        layer_id: The layer to remove.

    Returns:
        This map (chainable).

    Raises:
        KeyError: if no layer has that id, naming the ids that do — a silent no-op here would look
            exactly like a layer that refused to go away.

    Note:
        The **id** goes back to the pool, so a name removed and asked for again is handed back
        unsuffixed: an id is reserved exactly while the layer is on the map, which is the lifetime all
        four tiers share (:func:`~digitalearth.base.spec.layer.free_layer_id`).

        The in-memory **data** is not forgotten. A `figure_spec` captured before the removal still names
        it, and drawing that figure again needs it; :meth:`close` is where this map lets its data go.

    Examples:
        - A layer added and then removed leaves nothing behind:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap().add_layer("mine", name="obs")
            >>> m.remove_layer("obs").layer_ids
            []
            >>> m.layers
            []

            ```
    """
    self._require_layer(layer_id)
    self._change(self._figure_with(self._layer_tree.remove(layer_id)))
    # After the change, not before: a drawer reads the credential and the engine values out of these,
    # so dropping them first would leave the reconcile unable to draw the layer it is taking off.
    self._layer_keys.pop(layer_id, None)
    self._layer_held.pop(layer_id, None)
    self._live_streams.pop(layer_id, None)
    self._issued_ids.discard(layer_id)
    if self._last_layer_id == layer_id:
        remaining = self._layer_tree.ids
        self._last_layer_id = remaining[-1] if remaining else None
    return self

replace_layer(layer) #

Swap a layer's description for another, keeping its id and its place in draw order.

This is how a layer is restyled or re-pointed after it has been drawn: the drawer builds the element again from the new description, since a HoloViews element carries the options it was built with.

A layer of the caller's own is the exception, because there is no description to build it from. A replacement that changes only what the figure says about such a layer — its label, its band, whether it is drawn — is honoured, and one that changes what the element is is refused: its kind, its source, its slice, its symbology, its filter or its group. Hand the new object to :meth:add_layer instead (:data:~digitalearth.interactive.render.renderer.KEPT_KINDS).

Parameters:

Name Type Description Default
layer LayerSpec

The new description. Its id names the layer it replaces.

required

Returns:

Type Description
Self

This map (chainable).

Raises:

Type Description
CapabilityError

if the replacement names a kind this tier does not draw, naming the kind and the backend that has no drawer for it. Raised off the declaration, before a description is built or the engine is touched. It subclasses ValueError, so a caller catching that catches this. Also for a layer this tier keeps rather than draws, as above — refused before the first layer is drawn, so a refused replacement leaves the map exactly as it was.

KeyError

if no layer has that id, naming the ids that do.

ValueError

if layer is not a LayerSpec, or if it draws from data and names no source_id: the drawers read the source out of the figure, and a missing one reaches the drawer as None and fails somewhere it cannot explain.

Examples:

  • A layer re-described keeps its id and its place:
    >>> from dataclasses import replace
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap().add_layer("mine", name="obs")
    >>> _ = m.replace_layer(replace(m.get_layer("obs"), label="Observations"))
    >>> m.get_layer("obs").label
    'Observations'
    
Source code in src/digitalearth/interactive/core/base.py
def replace_layer(self, layer: LayerSpec) -> Self:
    """Swap a layer's description for another, keeping its id and its place in draw order.

    This is how a layer is restyled or re-pointed after it has been drawn: the drawer builds the element
    again from the new description, since a HoloViews element carries the options it was built with.

    **A layer of the caller's own is the exception**, because there is no description to build it from. A
    replacement that changes only what the figure *says* about such a layer — its label, its band,
    whether it is drawn — is honoured, and one that changes what the element *is* is refused: its kind,
    its source, its slice, its symbology, its filter or its group. Hand the new object to
    :meth:`add_layer` instead (:data:`~digitalearth.interactive.render.renderer.KEPT_KINDS`).

    Args:
        layer: The new description. Its id names the layer it replaces.

    Returns:
        This map (chainable).

    Raises:
        CapabilityError: if the replacement names a kind this tier does not draw, naming the kind and the
            backend that has no drawer for it. Raised off the declaration, before a description is built
            or the engine is touched. It subclasses ``ValueError``, so a caller catching that catches this.
            Also for a layer this tier *keeps* rather than draws, as above — refused before the first
            layer is drawn, so a refused replacement leaves the map exactly as it was.
        KeyError: if no layer has that id, naming the ids that do.
        ValueError: if `layer` is not a `LayerSpec`, or if it draws from data and names no `source_id`:
            the drawers read the source out of the figure, and a missing one reaches the drawer as
            `None` and fails somewhere it cannot explain.

    Examples:
        - A layer re-described keeps its id and its place:
            ```python
            >>> from dataclasses import replace
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap().add_layer("mine", name="obs")
            >>> _ = m.replace_layer(replace(m.get_layer("obs"), label="Observations"))
            >>> m.get_layer("obs").label
            'Observations'

            ```
    """
    # By type before by id: `getattr(layer, "id", None)` made the id lookup fail first, so a caller who
    # passed the id where the description belongs was answered "no layer None on this map" — an id they
    # never wrote, about an argument that was not a description at all (review M9, the static tier's L1).
    if not isinstance(layer, LayerSpec):
        raise ValueError(
            f"{type(self).__name__}.replace_layer needs a LayerSpec — the new description, not an id; "
            f"got {type(layer).__name__}"
        )
    self._require_layer(layer.id)
    # The first production caller of `Capabilities.require` (D-10). A replacement is the one
    # layer-management call that can name a **new kind**, so it is the one that can ask this tier for
    # something it does not have — and refusing here, off the declaration, refuses before a description
    # is built or the engine is touched. Without it the refusal came from the drawer table, part-way
    # through a reconcile, and said nothing about what the tier declares.
    CAPABILITIES.require(layer.kind, caller="InteractiveMap.replace_layer")
    if layer.source_id is None and kind_info(layer.kind).takes != "none":
        raise ValueError(
            f"layer {layer.id!r} is a {layer.kind!r} layer, which draws from data, so its replacement "
            f"needs a source_id; got None"
        )
    self._change(self._figure_with(self._layer_tree.replace(layer)))
    return self

set_visible(layer_id, visible=True) #

Show or hide a layer, by id.

The layer stays on the map and in its description — which is what lets it be switched back on, and what tells a saved figure that the layer is there but not drawn.

Parameters:

Name Type Description Default
layer_id str

The layer to toggle.

required
visible bool

Whether it is drawn.

True

Returns:

Type Description
Self

This map (chainable).

Raises:

Type Description
KeyError

if no layer has that id, naming the ids that do.

Warns:

Type Description
UserWarning

when the element has no keyword to say it with — a basemap, a dynamic=True layer whose DynamicMap has produced no frame yet, or an object handed to :meth:add_layer that HoloViews has no option tree for at all. The layer stays drawn and the warning says so (:func:~digitalearth.interactive.render.renderer._show).

Note

Every layer is hidden on its element: Bokeh takes visible=False and draws nothing for it, while the overlay render() composes is unchanged. That includes a layer of the caller's own. The tier holds no description to rebuild such an element from — which is why custom:holoviews is named in the renderer contract's UNDRAWN_KINDS — but it does hold the object, and hiding it is the same .opts() call. It used to be described hidden and nothing more, so a caller was told the layer was hidden while render() went on drawing it, without even the warning above (review H8).

Examples:

  • A hidden layer is still described, and comes back on:
    >>> import warnings
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap().add_layer("mine", name="obs")
    >>> with warnings.catch_warnings():  # a str has no `visible` option, so this warns
    ...     warnings.simplefilter("ignore", UserWarning)
    ...     m.set_visible("obs", False).figure_spec.layers.is_visible("obs")
    False
    >>> with warnings.catch_warnings():
    ...     warnings.simplefilter("ignore", UserWarning)
    ...     m.set_visible("obs").figure_spec.layers.is_visible("obs")
    True
    
Source code in src/digitalearth/interactive/core/base.py
def set_visible(self, layer_id: str, visible: bool = True) -> Self:
    """Show or hide a layer, by id.

    The layer stays on the map and in its description — which is what lets it be switched back on, and
    what tells a saved figure that the layer is there but not drawn.

    Args:
        layer_id: The layer to toggle.
        visible: Whether it is drawn.

    Returns:
        This map (chainable).

    Raises:
        KeyError: if no layer has that id, naming the ids that do.

    Warns:
        UserWarning: when the element has no keyword to say it with — a basemap, a `dynamic=True` layer
            whose `DynamicMap` has produced no frame yet, or an object handed to :meth:`add_layer` that
            HoloViews has no option tree for at all. The layer stays drawn and the warning says so
            (:func:`~digitalearth.interactive.render.renderer._show`).

    Note:
        Every layer is hidden **on its element**: Bokeh takes `visible=False` and draws nothing for it,
        while the overlay `render()` composes is unchanged. That includes a layer of the caller's own.
        The tier holds no *description* to rebuild such an element from — which is why
        `custom:holoviews` is named in the renderer contract's `UNDRAWN_KINDS` — but it does hold the
        object, and hiding it is the same `.opts()` call. It used to be described hidden and nothing
        more, so a caller was told the layer was hidden while `render()` went on drawing it, without
        even the warning above (review H8).

    Examples:
        - A hidden layer is still described, and comes back on:
            ```python
            >>> import warnings
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap().add_layer("mine", name="obs")
            >>> with warnings.catch_warnings():  # a str has no `visible` option, so this warns
            ...     warnings.simplefilter("ignore", UserWarning)
            ...     m.set_visible("obs", False).figure_spec.layers.is_visible("obs")
            False
            >>> with warnings.catch_warnings():
            ...     warnings.simplefilter("ignore", UserWarning)
            ...     m.set_visible("obs").figure_spec.layers.is_visible("obs")
            True

            ```
    """
    self._require_layer(layer_id)
    self._change(
        self._figure_with(self._layer_tree.set_visible(layer_id, bool(visible)))
    )
    return self

add_layer(layer, *, kind=None, name=None, visible=True, band=None, source=None, symbology=None, key=None, held=None, color_field=None) #

Register a HoloViews/GeoViews element as a map layer and return self (chainable).

The low-level entry point the capability mixins build on — every builder method ends here.

A builder of a drawn kind passes layer=None and a symbology: the layer is described first and its drawer builds the element from that description, which is what "render from the description" means here.

An object you build yourself is a custom layer: what a figure keeps is its description — an id, the kind custom:holoviews, a label, a band and whether it is visible — and never the object, which has no description to write. The object stays with the scene that was handed it, so a figure saved and loaded again names the layer but cannot rebuild it, and another backend cannot draw it at all (:mod:digitalearth.base.custom says which case a reader is in).

Parameters:

Name Type Description Default
layer Any

Any HoloViews/GeoViews element (or overlay-able object), or None for a layer of a kind this tier draws — that one is built by its drawer from symbology.

required
kind str | None

The registered, engine-neutral kind the layer is — "raster", "points", … A kind listed in :data:~digitalearth.interactive.render.renderer.DRAWN_KINDS is drawn from its description; None makes it a custom layer (custom:holoviews).

None
name str | None

The caller's own name for the layer, used as its id when it is free and as its label.

None
visible bool

Whether the layer is described as visible — and, for a kind this tier draws, applied: the drawer is asked for it and the element is hidden when the tree says the layer is not drawn (its own flag, and its group's).

True
band str | None

The draw-order band, for a kind that does not imply one — what a custom layer needs, since the engine name says nothing about what it draws.

None
source Any

What the layer draws, recorded under its id; None for a layer drawn from no data.

None
symbology Any

How it looks, as values — the description its drawer reads.

None
key Any

A credential the layer's drawer needs, held on the map rather than in symbology so a figure written to JSON carries no API key. None for every layer that needs none.

None
held Mapping[str, Any] | None

The engine values this layer's drawer needs that a description cannot carry — a colormap object, a tile provider, and the half of the caller's own keywords JSON cannot spell (the rest is described, since M3). A value the drawer reads by name is filed by that name; the keyword and style buckets are filed nested, under their own keys, and :func:held_props merges each into the described mapping of the same name. Held on the map for the same reason key is; see :func:describe. None for a layer whose description says everything about it.

None
color_field str | None

The name of the value a custom layer's colour encodes. A hand-built element publishes no colour encoding of its own, so without this the layer has no colour key and :meth:colorbar/:meth:legend refuse it (#349). Naming it publishes Encoding.by_field("color", color_field) for the layer; it fills only the custom case, since a drawn kind brings its own symbology. None (default) leaves the layer keyless.

None

Returns:

Type Description
Self

The same map instance, so builder calls chain: m.field(dem).basemap().coastlines(). A drawer

Self

that declined to draw the layer leaves the map as it was — the description, the registered

Self

source, the held key and the id are all let go again, so nothing names a layer that was never

Self

drawn.

Raises:

Type Description
KeyError

when kind is one this tier draws but symbology records no via it has a recipe for — a builder routed to a kind without saying how it drew it. The refusal names the recipes that kind is drawn by.

Exception

whatever the layer's drawer raises — an :class:~digitalearth.base.crs.OffLimbError from a warp that places nothing, a KeyError for a column the data does not have — re-raised after the layer is let go exactly as a declined one is.

Examples:

  • Two layers of one band register in call order and return the map for chaining (any object can stand in for a HoloViews element here — the registry does not inspect it):
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap()
    >>> m.add_layer("raster-layer").add_layer("vector-layer") is m
    True
    >>> m.layers
    ['raster-layer', 'vector-layer']
    
  • A band decides where the element lands, not the order it was added in: a reference layer registered second is drawn beneath the data layer registered first:
    >>> from digitalearth.interactive import InteractiveMap
    >>> m = InteractiveMap().add_layer("observations")
    >>> m = m.add_layer("grid", name="grid", band="reference")
    >>> m.layers
    ['grid', 'observations']
    >>> m.layer_ids
    ['grid', 'holoviews-1']
    
  • With the engine installed, real elements register the same way:
    >>> import holoviews as hv                       # doctest: +SKIP
    >>> m = InteractiveMap()                         # doctest: +SKIP
    >>> m.add_layer(hv.Points([(0, 0)])).layers    # doctest: +SKIP
    [:Points   [x,y]]
    
Source code in src/digitalearth/interactive/core/base.py
def add_layer(
    self,
    layer: Any,
    *,
    kind: str | None = None,
    name: str | None = None,
    visible: bool = True,
    band: str | None = None,
    source: Any = None,
    symbology: Any = None,
    key: Any = None,
    held: Mapping[str, Any] | None = None,
    color_field: str | None = None,
) -> Self:
    """Register a HoloViews/GeoViews element as a map layer and return ``self`` (chainable).

    The low-level entry point the capability mixins build on — every builder method ends here.

    A builder of a drawn kind passes ``layer=None`` and a ``symbology``: the layer is described first
    and its drawer builds the element from that description, which is what "render from the description"
    means here.

    An object you build yourself is a **custom layer**: what a figure keeps is its description — an id, the
    kind `custom:holoviews`, a label, a band and whether it is visible — and never the object, which has no
    description to write. The object stays with the scene that was handed it, so a figure saved and loaded
    again names the layer but cannot rebuild it, and another backend cannot draw it at all
    (:mod:`digitalearth.base.custom` says which case a reader is in).

    Args:
        layer: Any HoloViews/GeoViews element (or overlay-able object), or ``None`` for a layer of a
            kind this tier draws — that one is built by its drawer from ``symbology``.
        kind: The registered, engine-neutral kind the layer is — ``"raster"``, ``"points"``, … A kind
            listed in :data:`~digitalearth.interactive.render.renderer.DRAWN_KINDS` is drawn from its
            description; ``None`` makes it a custom layer (``custom:holoviews``).
        name: The caller's own name for the layer, used as its id when it is free and as its label.
        visible: Whether the layer is described as visible — and, for a kind this tier draws, applied:
            the drawer is asked for it and the element is hidden when the tree says the layer is not
            drawn (its own flag, and its group's).
        band: The draw-order band, for a kind that does not imply one — what a custom layer needs,
            since the engine name says nothing about what it draws.
        source: What the layer draws, recorded under its id; ``None`` for a layer drawn from no data.
        symbology: How it looks, as values — the description its drawer reads.
        key: A credential the layer's drawer needs, held on the map rather than in ``symbology`` so a
            figure written to JSON carries no API key. ``None`` for every layer that needs none.
        held: The engine values this layer's drawer needs that a description cannot carry — a colormap
            object, a tile provider, and the half of the caller's own keywords JSON cannot spell (the
            rest is described, since M3). A value the drawer reads by name is filed by that name; the
            keyword and style buckets are filed *nested*, under their own keys, and
            :func:`held_props` merges each into the described mapping of the same name. Held on the
            map for the same reason ``key`` is; see :func:`describe`. ``None`` for a layer whose
            description says everything about it.
        color_field: The name of the value a **custom** layer's colour encodes. A hand-built element
            publishes no colour encoding of its own, so without this the layer has no colour key and
            :meth:`colorbar`/:meth:`legend` refuse it (#349). Naming it publishes
            ``Encoding.by_field("color", color_field)`` for the layer; it fills only the custom case,
            since a drawn kind brings its own ``symbology``. ``None`` (default) leaves the layer keyless.

    Returns:
        The same map instance, so builder calls chain: ``m.field(dem).basemap().coastlines()``. A drawer
        that declined to draw the layer leaves the map as it was — the description, the registered
        source, the held key and the id are all let go again, so nothing names a layer that was never
        drawn.

    Raises:
        KeyError: when ``kind`` is one this tier draws but ``symbology`` records no ``via`` it has a
            recipe for — a builder routed to a kind without saying how it drew it. The refusal names
            the recipes that kind is drawn by.
        Exception: whatever the layer's drawer raises — an
            :class:`~digitalearth.base.crs.OffLimbError` from a warp that places nothing, a ``KeyError``
            for a column the data does not have — re-raised after the layer is let go exactly as a
            declined one is.

    Examples:
        - Two layers of one band register in call order and return the map for chaining (any object
          can stand in for a HoloViews element here — the registry does not inspect it):
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap()
            >>> m.add_layer("raster-layer").add_layer("vector-layer") is m
            True
            >>> m.layers
            ['raster-layer', 'vector-layer']

            ```
        - A ``band`` decides where the element lands, not the order it was added in: a reference layer
          registered second is drawn beneath the data layer registered first:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> m = InteractiveMap().add_layer("observations")
            >>> m = m.add_layer("grid", name="grid", band="reference")
            >>> m.layers
            ['grid', 'observations']
            >>> m.layer_ids
            ['grid', 'holoviews-1']

            ```
        - With the engine installed, real elements register the same way:
            ```python
            >>> import holoviews as hv                       # doctest: +SKIP
            >>> m = InteractiveMap()                         # doctest: +SKIP
            >>> m.add_layer(hv.Points([(0, 0)])).layers    # doctest: +SKIP
            [:Points   [x,y]]

            ```
    """
    # A builder that says what it drew is described; one that does not is a caller's own object,
    # which has no description to write beyond the fact that it exists
    # (:mod:`digitalearth.base.custom`).
    from digitalearth.interactive.render.renderer import DRAWN_KINDS

    self._guard_element_crs(layer, caller="add_layer")
    resolved = kind or custom_kind("holoviews")
    layer_id = self._layer_id(resolved.split(":")[-1], name)
    # A custom layer publishes no colour encoding of its own, so `color_field` is the caller's one way to
    # say what it varies by — recorded as the colour encoding a key hangs on, exactly as a builder's is,
    # under the same `via="custom"` marker the static and web tiers set (#349). `custom:holoviews` is a
    # KEPT kind (drawn by being held, never from a recipe), so the marker is descriptive and never reaches
    # the via-dispatch in `renderer.make_draw`. A drawn kind carries its own `symbology`, so the two
    # cannot both be given.
    if color_field is not None:
        if symbology is not None or resolved in DRAWN_KINDS:
            raise ValueError(
                "add_layer(color_field=...) names the colour field of a custom layer, so it takes no "
                "kind= and no symbology=; a drawn kind carries its own colour"
            )
        symbology = Symbology(
            props={"via": "custom"},
            encodings={"color": Encoding.by_field("color", color_field)},
        )
    # Everything from here to the draw is undone together if any of it raises. The layer is described
    # before its drawer runs, so a drawer that refuses — an off-limb warp, `strict=True`, a column that
    # is not there — would otherwise leave the figure naming a layer nothing drew, its data registered
    # for the life of the process, and every later layer inserted at an index counted past the ghost.
    try:
        if key is not None:
            self._layer_keys[layer_id] = key
        if held:
            self._layer_held[layer_id] = dict(held)
        self._index_layer(
            layer_id,
            name,
            kind=resolved,
            visible=visible,
            band=band,
            source=source,
            symbology=symbology,
        )
        if resolved in DRAWN_KINDS:
            # The element is built from the description rather than handed in: the builder passed `None`
            # and its drawer makes the real one, which is what "render from the description" means.
            drawn = self._renderer.draw_layer(self.figure_spec, layer_id)
            if drawn is None:
                self._forget_layer(layer_id)
                return self
            layer = drawn.element
    except BaseException:
        self._forget_layer(layer_id)
        raise
    # Placed where the description puts it, not where the call happened to arrive. The tree orders by
    # draw-order band, so a basemap added last still goes under the data and a graticule added first
    # still goes over it — and the list `_compose` overlays cannot disagree with the figure the map
    # reports, which is what it did when a builder had to remember to insert at the front itself.
    self.layers.insert(self._layer_tree.ids.index(layer_id), layer)
    self._note_last_layer(layer_id)
    return self

render() #

Compose the registered layers into one HoloViews object (overlaid with *).

Returns:

Name Type Description
Any

The single element when one layer is registered, an hv.Overlay of all layers in draw

Any

order otherwise (an empty map renders as a blank hv.Overlay). The overlay's order is the

order Any

attr:figure_spec describes, because each element was placed where its layer's band

Any

put it rather than where the builder call happened to arrive.

Raises:

Type Description
ImportError

when the interactive extra is not installed.

Examples:

  • Two registered layers compose into an overlay in draw order (needs the engine):
    >>> import holoviews as hv                                   # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap      # doctest: +SKIP
    >>> m = InteractiveMap()                                     # doctest: +SKIP
    >>> _ = m.add_layer(hv.Points([(0, 0)]))                   # doctest: +SKIP
    >>> _ = m.add_layer(hv.Points([(1, 1)]))                   # doctest: +SKIP
    >>> overlay = m.render()                                     # doctest: +SKIP
    >>> len(overlay)                                             # doctest: +SKIP
    2
    
  • An empty map renders as a blank overlay rather than raising:
    >>> from digitalearth.interactive import InteractiveMap      # doctest: +SKIP
    >>> len(InteractiveMap().render())                           # doctest: +SKIP
    0
    
Source code in src/digitalearth/interactive/core/base.py
def render(self) -> Any:
    """Compose the registered layers into one HoloViews object (overlaid with ``*``).

    Returns:
        The single element when one layer is registered, an ``hv.Overlay`` of all layers in draw
        order otherwise (an empty map renders as a blank ``hv.Overlay``). The overlay's order is the
        order :attr:`figure_spec` describes, because each element was placed where its layer's band
        put it rather than where the builder call happened to arrive.

    Raises:
        ImportError: when the ``interactive`` extra is not installed.

    Examples:
        - Two registered layers compose into an overlay in draw order (needs the engine):
            ```python
            >>> import holoviews as hv                                   # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap      # doctest: +SKIP
            >>> m = InteractiveMap()                                     # doctest: +SKIP
            >>> _ = m.add_layer(hv.Points([(0, 0)]))                   # doctest: +SKIP
            >>> _ = m.add_layer(hv.Points([(1, 1)]))                   # doctest: +SKIP
            >>> overlay = m.render()                                     # doctest: +SKIP
            >>> len(overlay)                                             # doctest: +SKIP
            2

            ```
        - An empty map renders as a blank overlay rather than raising:
            ```python
            >>> from digitalearth.interactive import InteractiveMap      # doctest: +SKIP
            >>> len(InteractiveMap().render())                           # doctest: +SKIP
            0

            ```
    """
    self._flush_deferred_tiles()
    self._apply_theme()
    return self._projected(self._compose(self.layers))

save(path, **kwargs) #

Save the composed map — interactive HTML (Bokeh) or a raster via the matplotlib backend.

Parameters:

Name Type Description Default
path Any

Output file (str or pathlib.Path). *.html writes a self-contained interactive Bokeh page; .png and the other raster suffixes render through HoloViews' matplotlib backend (headless, no browser/selenium needed). A vector suffix is refused — see below.

required
**kwargs Any

Forwarded to :func:holoviews.save (e.g. fmt, dpi).

{}

Returns:

Type Description
Path

pathlib.Path: the file written — every tier's save returns a Path (#248), so the

Path

result can be opened, moved or asserted on without re-wrapping it.

Raises:

Type Description
ImportError

when the interactive extra is not installed.

ValueError

for a vector suffix (.svg/.pdf/.pgf). This tier declares export_vector absent, because its figure is a Bokeh canvas and a vector export is the static tier's — and the static tier declares that capability as its own alone. The matplotlib fallback the raster suffixes use would write those three too, so a caller asking for one got a file the declaration says the tier cannot produce, drawn by a renderer that is not this tier's (review L3). Build the same map with digitalearth.Map for a vector file.

Examples:

  • The suffix picks the backend — .html is interactive Bokeh, .png renders headless through matplotlib (needs the engine):
    >>> import holoviews as hv                                   # doctest: +SKIP
    >>> from digitalearth.interactive import InteractiveMap      # doctest: +SKIP
    >>> m = InteractiveMap().add_layer(hv.Points([(0, 0)]))    # doctest: +SKIP
    >>> m.save("map.html").name                                  # doctest: +SKIP
    'map.html'
    >>> m.save("map.png").suffix                                 # doctest: +SKIP
    '.png'
    
  • A vector file is the static tier's, and the refusal says so rather than writing one (it needs no engine: nothing is rendered for a call that cannot be honoured):
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().save("map.svg")           # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    ValueError: InteractiveMap.save('map.svg') cannot write a vector file: ...
    
Source code in src/digitalearth/interactive/core/base.py
def save(self, path: Any, **kwargs: Any) -> Path:
    """Save the composed map — interactive HTML (Bokeh) or a raster via the matplotlib backend.

    Args:
        path: Output file (``str`` or ``pathlib.Path``). ``*.html`` writes a self-contained
            interactive Bokeh page; ``.png`` and the other raster suffixes render through HoloViews'
            matplotlib backend (headless, no browser/selenium needed). A vector suffix is refused —
            see below.
        **kwargs: Forwarded to :func:`holoviews.save` (e.g. ``fmt``, ``dpi``).

    Returns:
        pathlib.Path: the file written — every tier's ``save`` returns a ``Path`` (#248), so the
        result can be opened, moved or asserted on without re-wrapping it.

    Raises:
        ImportError: when the ``interactive`` extra is not installed.
        ValueError: for a vector suffix (``.svg``/``.pdf``/``.pgf``). This tier declares
            ``export_vector`` absent, because its figure is a Bokeh canvas and a vector export is the
            static tier's — and the static tier declares that capability as its own alone. The
            matplotlib fallback the raster suffixes use would write those three too, so a caller asking
            for one got a file the declaration says the tier cannot produce, drawn by a renderer that
            is not this tier's (review L3). Build the same map with ``digitalearth.Map`` for a vector
            file.

    Examples:
        - The suffix picks the backend — ``.html`` is interactive Bokeh, ``.png`` renders
          headless through matplotlib (needs the engine):
            ```python
            >>> import holoviews as hv                                   # doctest: +SKIP
            >>> from digitalearth.interactive import InteractiveMap      # doctest: +SKIP
            >>> m = InteractiveMap().add_layer(hv.Points([(0, 0)]))    # doctest: +SKIP
            >>> m.save("map.html").name                                  # doctest: +SKIP
            'map.html'
            >>> m.save("map.png").suffix                                 # doctest: +SKIP
            '.png'

            ```
        - A vector file is the static tier's, and the refusal says so rather than writing one (it
          needs no engine: nothing is rendered for a call that cannot be honoured):
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> InteractiveMap().save("map.svg")           # doctest: +ELLIPSIS
            Traceback (most recent call last):
                ...
            ValueError: InteractiveMap.save('map.svg') cannot write a vector file: ...

            ```
    """
    suffix = Path(str(path)).suffix.lower()
    if suffix in VECTOR_SUFFIXES:
        # Refused before the figure is rendered, so nothing is drawn and nothing is written for a call
        # that cannot be honoured. The reason is read from the declaration rather than repeated, so the
        # two cannot say different things (review L3).
        raise ValueError(
            f"InteractiveMap.save({str(path)!r}) cannot write a vector file: the interactive tier "
            f"declares export_vector absent - {CAPABILITIES.reason('export_vector')}. Build the map "
            f"with digitalearth.Map for {suffix}, or save .png or .html here."
        )
    _, hv = _require_holoviz()
    obj = self.render()
    backend = "bokeh" if str(path).lower().endswith(".html") else "matplotlib"
    hv.save(obj, path, backend=backend, **kwargs)
    return Path(path)

show() #

Render the map and display it inline when IPython is available.

Returns:

Type Description
Any

The composed HoloViews object (which a notebook front-end renders richly).

Raises:

Type Description
ImportError

when the interactive extra is not installed.

Source code in src/digitalearth/interactive/core/base.py
def show(self) -> Any:
    """Render the map and display it inline when IPython is available.

    Returns:
        The composed HoloViews object (which a notebook front-end renders richly).

    Raises:
        ImportError: when the ``interactive`` extra is not installed.
    """
    obj = self.render()
    try:
        from IPython.display import display

        display(obj)
    except (
        ImportError
    ):  # plain-script use: returning the object is all there is to show
        pass
    return obj

close() #

Let go of the in-memory data this map registered.

The object registry is process-global and holds strong references, so a session that builds maps keeps every dataset they drew until something says otherwise. This is the caller saying so. Closing twice is harmless, and a map that registered nothing has nothing to forget.

An object: source in a figure_spec captured from this map cannot be opened afterwards — which is what "closed" means for a figure whose data lived only in this process. Save the data and reference it by path to keep such a figure readable.

The credentials held for keyed basemaps go too, and with them the engine values held beside each layer: they are kept off the figure so it can be written down without them, and a closed map has nothing left to draw with them.

What does not go is the figure: the layer tree, the elements already built and the pointer the toggles follow all survive, so a closed map still renders, saves and can have its colorbar or legend switched. Closing lets go of the data, not of the picture — a colorbar() after close() acts on a layer that is still there, which is why the pointer is not cleared here as it is in :meth:_forget_layer (review N8). Only a layer that was forgotten takes the pointer with it.

Examples:

  • A map that drew nothing closes quietly, with no engine installed:
    >>> from digitalearth.interactive import InteractiveMap
    >>> InteractiveMap().close()
    
See Also

exit: calls this on the way out of a with block.

Source code in src/digitalearth/interactive/core/base.py
def close(self) -> None:
    """Let go of the in-memory data this map registered.

    The object registry is process-global and holds strong references, so a session that builds maps
    keeps every dataset they drew until something says otherwise. This is the caller saying so. Closing
    twice is harmless, and a map that registered nothing has nothing to forget.

    An `object:` source in a `figure_spec` captured from this map cannot be opened afterwards — which is
    what "closed" means for a figure whose data lived only in this process. Save the data and reference
    it by path to keep such a figure readable.

    The credentials held for keyed basemaps go too, and with them the engine values held beside each
    layer: they are kept off the figure so it can be written down without them, and a closed map has
    nothing left to draw with them.

    What does **not** go is the figure: the layer tree, the elements already built and the pointer the
    toggles follow all survive, so a closed map still renders, saves and can have its colorbar or
    legend switched. Closing lets go of the *data*, not of the picture — a `colorbar()` after `close()`
    acts on a layer that is still there, which is why the pointer is not cleared here as it is in
    :meth:`_forget_layer` (review N8). Only a layer that was forgotten takes the pointer with it.

    Examples:
        - A map that drew nothing closes quietly, with no engine installed:
            ```python
            >>> from digitalearth.interactive import InteractiveMap
            >>> InteractiveMap().close()

            ```

    See Also:
        __exit__: calls this on the way out of a ``with`` block.
    """
    forget_namespace(self._objects_ns)
    self._layer_keys.clear()
    self._layer_held.clear()
    self._live_streams.clear()
    # Release the two registries the capability rows added (review L1): a `pn.state` periodic callback
    # (IN-10) keeps the event loop pinning the whole map after close unless it is stopped, and a linked
    # attribute table (IN-5) holds the map through its Selection1D subscriber. Stop each periodic
    # callback best-effort — a handle registered off-server may never have started — then drop both.
    for callback in self._session_callbacks:
        stop = getattr(callback, "stop", None)
        if callable(stop):
            try:
                stop()
            except (
                ValueError,
                RuntimeError,
            ):  # already stopped / no running loop to detach from
                pass
    self._session_callbacks.clear()
    self._table_links.clear()