Skip to content

Web maps#

WebMap renders pyramids rasters and vectors as MapLibre GL JS / deck.gl layers and exports the result as one self-contained HTML page.

from digitalearth.web import WebMap

(
    WebMap()
    .basemap()
    .choropleth(gdf, column="pop", name="Population")
    .legend(title="People per km²")
    .layer_control()
    .set_title("Population, 2024", subtitle="Source: CBS")
    .save("map.html")
)

The map frames itself on the data you gave it, so there is no center/zoom to work out by hand — pass them only when you want a view of your own.

What this tier is for#

Thematic maps, 3-D layers, contours, and sharing the result as one file. It is deliberately not a peer of the static tier for scientific field rendering: vector/flow fields, unstructured meshes and KDE have no native MapLibre primitive and live in digitalearth.static and digitalearth.interactive.

Naming layers, and why the name matters#

py-maplibregl's layer switcher has no separate label: its JavaScript captions each row with the layer's id and reads that same string back to toggle it. So a name= you pass becomes the layer's id, and that is what a viewer reads in the switcher:

WebMap().basemap().choropleth(gdf, column="pop", name="Population").layer_control()
# the switcher shows: Population

Without a name a layer gets a generated id (fill-4), which is what the switcher would then show. A repeated name is suffixed (Population-2) because two layers cannot share a MapLibre id. WebMap.layer_ids lists them, and remove_layer(id) drops one.

The big-data path works the same way: past big_data_threshold features, points/polygons render a deck.gl layer rather than one MapLibre style layer per feature, but the layer still owns a tree slot, so name= and visible= are honoured and WebMap.layer_ids/remove_layer/set_visible/move_layer all reach it like any other layer. (tiles_3d, whose tileset streams from a URL, is the one deck builder still off the tree.)

Drawing order#

Layers sit in three bands, and a later call cannot slip under an earlier band:

  1. basemaps — basemap(), tiles() (add_underlay)
  2. reference — graticule() (add_reference)
  3. data — everything else (add_layer)

Within a band, layers keep the order you added them in. That is why .basemap().graticule() works: a reference grid belongs over the ground and under the data, which neither end of a flat list can express.

A builder that draws several MapLibre layers — cluster (bubbles, counts, loose points) and graticule (lines, degree labels) — appears once in layer_ids, under its main layer. remove_layer takes the whole group; the layer switcher toggles only that main layer, because that is what py-maplibregl's control does.

Sharing a page safely#

  • A keyed basemap puts its credential in the saved HTML. See Keyed basemaps — treat such a file as a secret.
  • Values from your data are escaped before they reach the legend or the title, so a hostile attribute in a downloaded shapefile cannot inject markup into the page you share.

Time series#

timeslider(collection) gives a notebook an ipywidgets slider. A saved page has no kernel, so it gets a step picker instead — the steps are labelled with the times you passed, because those labels become the layer ids. save("out.gif") writes the steps as an animation, which needs a headless browser (Playwright or Selenium); that is deliberately not part of digitalearth[web]. The method behind that suffix is save_animation(path, fps=...).

How this tier spells a few things#

Three keywords are worth naming, because the word alone does not say which of two sizes it means: a marker's visual size is size=, a label's font size is text_size=, and a frame rate is fps= — frames per second, not seconds per frame. padding on set_bounds is a number of screen pixels here, where the two 2-D tiers pad by a fraction of the frame's own span; a page is framed in pixels, so that is the only padding that means anything on it.

digitalearth.web.map.WebMap #

Bases: RasterMixin, VectorMixin, BigDataMixin, MeshMixin, ThreeDMixin, TemporalMixin, DecorationMixin, LegendMixin, ExportMixin, WebMapBase

Web map: pan/zoom (and 3-D) MapLibre + deck.gl layers built from pyramids data, shareable as HTML.

The web sibling of the static :class:~digitalearth.static.map.Map, the interactive :class:~digitalearth.interactive.map.InteractiveMap and the true-3D :class:~digitalearth.three_d.scene3d.Scene3D: raster/vector builders turn pyramids objects into MapLibre/deck.gl layers (reprojected to the display CRS through pyramids first), register them as layers, and render()/save() compose them into one maplibre widget / standalone HTML page. Needs the optional web extra (pip install 'digitalearth[web]') only when a builder/render method is actually called — importing this module works without it.

Examples:

  • Importing and constructing needs no MapLibre engine:
    >>> from digitalearth.web import WebMap
    >>> m = WebMap(zoom=4, style="voyager")
    >>> m.layers
    []
    >>> (m.zoom, m.style, m.crs)
    (4, 'voyager', 4326)
    
  • Layers register in draw order and the builders chain:
    >>> from digitalearth.web import WebMap
    >>> m = WebMap()
    >>> m.add_layer("dem").add_layer("basemap") is m
    True
    >>> m.layers
    ['dem', 'basemap']
    
  • With the web extra installed, the map renders and saves, handing back the :class:pathlib.Path it wrote. The path is compared by name rather than echoed, so the example reads the same on every platform (repr is PosixPath or WindowsPath):
    >>> import tempfile
    >>> from pathlib import Path
    >>> from pyramids.dataset import Dataset
    >>> from digitalearth.web import WebMap
    >>> dem = Dataset.read_file("examples/data/acc4000.tif")
    >>> with tempfile.TemporaryDirectory() as folder:
    ...     written = WebMap().field(dem).basemap().save(Path(folder) / "map.html")
    ...     (written.name, written.is_file())
    ('map.html', True)
    
See Also

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

Source code in src/digitalearth/web/map.py
class WebMap(
    RasterMixin,
    VectorMixin,
    BigDataMixin,
    MeshMixin,
    ThreeDMixin,
    TemporalMixin,
    DecorationMixin,
    LegendMixin,
    ExportMixin,
    WebMapBase,
):
    """Web map: pan/zoom (and 3-D) MapLibre + deck.gl layers built from pyramids data, shareable as HTML.

    The web sibling of the static :class:`~digitalearth.static.map.Map`, the interactive
    :class:`~digitalearth.interactive.map.InteractiveMap` and the true-3D
    :class:`~digitalearth.three_d.scene3d.Scene3D`: raster/vector builders turn pyramids objects into
    MapLibre/deck.gl layers (reprojected to the display CRS through pyramids first), register them as layers,
    and ``render()``/``save()`` compose them into one ``maplibre`` widget / standalone HTML page. Needs the
    optional ``web`` extra (``pip install 'digitalearth[web]'``) only when a builder/render method is
    actually called — importing this module works without it.

    Examples:
        - Importing and constructing needs no MapLibre engine:
            ```python
            >>> from digitalearth.web import WebMap
            >>> m = WebMap(zoom=4, style="voyager")
            >>> m.layers
            []
            >>> (m.zoom, m.style, m.crs)
            (4, 'voyager', 4326)

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

            ```
        - With the ``web`` extra installed, the map renders and saves, handing back the
          :class:`pathlib.Path` it wrote. The path is compared by name rather than echoed, so the
          example reads the same on every platform (``repr`` is ``PosixPath`` or ``WindowsPath``):
            ```python
            >>> import tempfile
            >>> from pathlib import Path
            >>> from pyramids.dataset import Dataset
            >>> from digitalearth.web import WebMap
            >>> dem = Dataset.read_file("examples/data/acc4000.tif")
            >>> with tempfile.TemporaryDirectory() as folder:
            ...     written = WebMap().field(dem).basemap().save(Path(folder) / "map.html")
            ...     (written.name, written.is_file())
            ('map.html', True)

            ```

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

layer_ids property #

The MapLibre ids of the data layers added so far, in draw order.

The registry used to be write-only: builders minted ids internally and nothing surfaced them, so a caller could not address a layer afterwards to hide, remove or switch it.

Returns:

Type Description
list[str]

The layer ids, bottom first, as a new list: the order they were added in, except that a graticule,

list[str]

which is drawn in the reference band beneath the data, is listed before every layer that is not a

list[str]

graticule, whenever it was added. A layer the caller named carries that name as its id; an unnamed one

list[str]

gets a generated id. A generated id counts the layers of its kind: a layer no longer takes a

list[str]

second number for the MapLibre source beside it, because that source is named after the layer

list[str]

(#296) rather than allocated next to it.

Examples:

  • Named and unnamed layers, in the order they were added:
    >>> from digitalearth.web import WebMap
    >>> m = WebMap().text(4.9, 52.4, "Amsterdam", name="amsterdam").text(2.35, 48.86, "Paris")
    >>> m.layer_ids
    ['amsterdam', 'text-1']
    
  • A graticule added last is listed first, because it is drawn beneath the data:
    >>> from digitalearth.web import WebMap
    >>> WebMap().text(4.9, 52.4, "Amsterdam", name="amsterdam").graticule().layer_ids
    ['Graticule', 'amsterdam']
    
  • A map with no data layers has no ids:
    >>> from digitalearth.web import WebMap
    >>> WebMap().layer_ids
    []
    

set_bounds(bounds=None, *, padding=0.0, padding_px=20, animate=False) #

Frame the map on bounds, or on everything added so far.

Without this the view comes only from the center/zoom given to the constructor, so a map of one country opened on the whole world unless the caller worked out a centre themselves.

Parameters:

Name Type Description Default
bounds Any | None

(west, south, east, north) in lon/lat. None uses the extent of the data added so far, which is what most callers want and is applied automatically anyway (see :meth:_map_view).

None
padding float

Breathing room around the extent, as a fraction of its own span — 0.05 leaves a 5% margin, exactly as it does on the 2-D tiers, so a call ports between tiers unchanged (#340). It grows the framed rectangle itself, through the shared :meth:~digitalearth.base.spec.Bounds.padded, before the view is fitted. 0.0 (default) leaves the extent as given. Was a number of screen pixels until #340; that control kept its own honest name, padding_px.

0.0
padding_px Any

MapLibre's own viewport padding passed to fitBounds — a number of pixels, or its per-edge mapping ({"top": 40, "bottom": 10, ...}). This is the pixel breathing room the engine leaves inside the viewport, which has no fraction-of-span equivalent, so it keeps a name of its own rather than overloading padding.

20
animate bool

Whether the browser eases into the new view rather than jumping.

False

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when bounds is None and nothing with an extent has been added yet — there is nothing to frame on, and silently doing nothing would look like the call was ignored; or when padding is a fraction that would invert the rectangle (below -0.5), refused by :meth:~digitalearth.base.spec.Bounds.padded. A non-zero padding also routes the bounds through :class:~digitalearth.base.spec.Bounds, which refuses a non-finite edge or an inverted (west > east) box — so an antimeridian-crossing frame must be requested with the default padding=0.0 (padding_px still applies to it).

Examples:

  • Frame on an explicit box:
    >>> from digitalearth.web import WebMap                     # doctest: +SKIP
    >>> WebMap().basemap().set_bounds((4.0, 51.0, 7.0, 54.0))  # doctest: +SKIP
    
Source code in src/digitalearth/web/core/base.py
def set_bounds(
    self,
    bounds: Any | None = None,
    *,
    padding: float = 0.0,
    padding_px: Any = 20,
    animate: bool = False,
) -> Self:
    """Frame the map on ``bounds``, or on everything added so far.

    Without this the view comes only from the ``center``/``zoom`` given to the constructor, so a map of
    one country opened on the whole world unless the caller worked out a centre themselves.

    Args:
        bounds: ``(west, south, east, north)`` in lon/lat. ``None`` uses the extent of the data added
            so far, which is what most callers want and is applied automatically anyway (see
            :meth:`_map_view`).
        padding: Breathing room around the extent, **as a fraction of its own span** — ``0.05`` leaves a
            5% margin, exactly as it does on the 2-D tiers, so a call ports between tiers unchanged
            (#340). It grows the framed rectangle itself, through the shared
            :meth:`~digitalearth.base.spec.Bounds.padded`, before the view is fitted. ``0.0`` (default)
            leaves the extent as given. Was a number of screen pixels until #340; that control kept its
            own honest name, ``padding_px``.
        padding_px: MapLibre's own viewport padding passed to ``fitBounds`` — a number of pixels, or its
            per-edge mapping (``{"top": 40, "bottom": 10, ...}``). This is the pixel breathing room the
            engine leaves inside the viewport, which has no fraction-of-span equivalent, so it keeps a
            name of its own rather than overloading ``padding``.
        animate: Whether the browser eases into the new view rather than jumping.

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

    Raises:
        ValueError: when ``bounds`` is ``None`` and nothing with an extent has been added yet — there
            is nothing to frame on, and silently doing nothing would look like the call was ignored; or
            when ``padding`` is a fraction that would invert the rectangle (below ``-0.5``), refused by
            :meth:`~digitalearth.base.spec.Bounds.padded`. A **non-zero** ``padding`` also routes the
            bounds through :class:`~digitalearth.base.spec.Bounds`, which refuses a non-finite edge or an
            inverted (``west > east``) box — so an antimeridian-crossing frame must be requested with the
            default ``padding=0.0`` (``padding_px`` still applies to it).

    Examples:
        - Frame on an explicit box:
            ```python
            >>> from digitalearth.web import WebMap                     # doctest: +SKIP
            >>> WebMap().basemap().set_bounds((4.0, 51.0, 7.0, 54.0))  # doctest: +SKIP

            ```
    """
    if bounds is None:
        if self._data_bounds is None:
            raise ValueError(
                "set_bounds() has nothing to frame on: no layer with an extent has been added yet. "
                "Add the data first, or pass bounds=(west, south, east, north)."
            )
        bounds = list(self._data_bounds)
    values = [float(value) for value in bounds]
    if len(values) != 4:
        raise ValueError(
            f"set_bounds(bounds=...) takes (west, south, east, north); got {len(values)} values"
        )
    west, south, east, north = values
    # `padding` is a fraction of the framed span — the one meaning it carries on every tier (#340) — grown
    # here through the shared `Bounds.padded`, but only when asked for. At the default 0.0 the bounds pass
    # straight to `fitBounds` as they did before #340, so an antimeridian-crossing box (west > east) —
    # which only this tier accepts — still frames; a non-zero fraction routes through `Bounds`, whose
    # constructor requires west <= east and finite edges. MapLibre's own per-edge pixel padding is a
    # different quantity with no fraction equivalent, so it keeps its own name and is what reaches
    # `fitBounds`.
    if padding:
        box = Bounds(west, south, east, north, 4326).padded(float(padding))
        west, south, east, north = box.xmin, box.ymin, box.xmax, box.ymax
    self._fit = {
        "bounds": [west, south, east, north],
        # Not int(): MapLibre also accepts {top, bottom, left, right}, and casting turns that into a
        # TypeError about int() rather than about the argument.
        "padding": padding_px if isinstance(padding_px, dict) else int(padding_px),
        "animate": bool(animate),
    }
    return self

layer_control(*, layers=None, position='top-right', controls=None, theme='default', opacity=None, order=None) #

Add a switcher so a viewer can turn the data layers on and off, dim them, and reorder them.

A map with a basemap, a choropleth and a point overlay had no way to look underneath — which is the single most common thing anyone does with a web map. The switch lists the data layers by default: basemaps are the ground, not something a viewer toggles — but naming "basemap" in controls= opts them in as a basemap gallery (WB-14). The gallery opens on the first basemap and hides the rest, so a viewer switches the ground from there. py-maplibregl's switcher is checkboxes rather than a radio, so a viewer can re-show more than one at once; the page simply starts on a single ground.

The three keywords are the ones the Tier-2 contract declares and the interactive tier now answers to as well — the layers to include, the position, the controls to expose — so the same call adds a layer control on either tier (#264). What was layer_ids= here is layers=, the name that tier uses for the same thing.

The manager widens past visibility (WB-8/WB-14), and most of the widening is declarative. opacity= dims a layer and order= reorders the stack, each applied now — opacity through :meth:~digitalearth.web.core.base.WebMapBase.replace_layer, which rewrites the layer's own paint, and order through :meth:~digitalearth.web.core.base.WebMapBase.move_layer — so the saved page draws the layers dimmed and in that order. The switcher itself stays a live page-side control (py-maplibregl's LayerSwitcherControl), and controls=["visibility", "basemap"] adds the basemap layers to it (WB-14) so the ground is switchable too. A live opacity slider or a drag-to-reorder control would each need a browser-JS layer this tier does not ship (the X-2 limitation), so controls= still refuses "opacity" rather than accept a control it cannot build — the inertness #242/#244 removed. So controls= selects the live switcher controls, while opacity=/order= are a one-time transform baked into the page and recorded on the switcher's furniture.

Parameters:

Name Type Description Default
layers list | None

The layers to offer, by id, defaulting to every data layer added so far — that is, :attr:~digitalearth.web.core.base.WebMapBase.layer_ids without the basemaps, which are addressable but are the ground rather than something a viewer toggles. Pass a subset to hide the rest from the switch without hiding them from the map, or name a basemap to offer it after all.

None
position str

One of the four corners in :data:~digitalearth.base.controls.CONTROL_POSITIONS — MapLibre's, and now both tiers'.

'top-right'
controls list | None

Which controls to expose, from :data:~digitalearth.base.controls.LAYER_CONTROLS. None (the default) offers ("visibility",) — a row per data layer. "basemap" may be added (["visibility", "basemap"]) to list the basemap layers in the same switcher (WB-14), so the ground is switchable. "opacity" is refused rather than accepted and dropped: a live opacity slider is a control py-maplibregl does not ship (use opacity= for a one-time dim). What the shared resolver answers is recorded on the switcher's furniture, so the panel says which controls it draws rather than leaving a reader to know that this tier draws one.

None
theme str

"default" or "simple" — py-maplibregl's two switcher styles. This tier's own keyword: it styles the switcher rather than choosing what the switcher contains.

'default'
opacity dict | None

A mapping of layer id to opacity in [0, 1], applied now by rewriting each named layer's paint through :meth:~digitalearth.web.core.base.WebMapBase.replace_layer. A layer that records no opacity to change — a text annotation has none — is refused rather than silently left opaque. None dims nothing.

None
order list | None

The bottom-to-top draw order for the named layers, applied now through :meth:~digitalearth.web.core.base.WebMapBase.move_layer. The ids must share a draw-order band — a layer cannot be dragged under the basemap, which is the one move the bands forbid — and an order that crosses a band is refused with the IndexError move_layer raises. None leaves the order untouched.

None
Note

A row toggles exactly one MapLibre layer, because that is what py-maplibregl's control does. Builders that draw more than one layer — cluster (bubbles, counts, loose points) and graticule (lines, degree labels) — are listed once, under their main layer, so toggling a cluster hides its bubbles while the count labels remain. remove_layer does take the whole group. Hiding the parts together needs a control py-maplibregl does not ship.

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when position is not one of the four legal corners, when controls names something outside the shared vocabulary or something this tier cannot build, when no data layer has been added yet, when an id was given (in layers, opacity or order) that is not on this map, when an opacity value is not a finite fraction in [0, 1], or when an opacity names a layer that records no opacity to change.

IndexError

when order would move a layer out of its draw-order band, as :meth:~digitalearth.web.core.base.WebMapBase.move_layer refuses it.

Examples:

  • Two layers and a switch between them:
    >>> from digitalearth.web import WebMap                            # doctest: +SKIP
    >>> (                                                              # doctest: +SKIP
    ...     WebMap()
    ...     .basemap()
    ...     .choropleth(gdf, column="pop", name="Population")
    ...     .layer_control()
    ... )
    
See Also

digitalearth.web.core.base.WebMapBase.layer_ids: the ids this offers by default. digitalearth.base.controls.resolved_controls: the shared control vocabulary.

Source code in src/digitalearth/web/decoration/decoration.py
def layer_control(
    self,
    *,
    layers: list | None = None,
    position: str = "top-right",
    controls: list | None = None,
    theme: str = "default",
    opacity: dict | None = None,
    order: list | None = None,
) -> Self:
    """Add a switcher so a viewer can turn the data layers on and off, dim them, and reorder them.

    A map with a basemap, a choropleth and a point overlay had no way to look underneath — which is the
    single most common thing anyone does with a web map. The switch lists the data layers by default:
    basemaps are the ground, not something a viewer toggles — but naming ``"basemap"`` in ``controls=``
    opts them in as a basemap gallery (WB-14). The gallery opens on the **first** basemap and hides the
    rest, so a viewer switches the ground from there. py-maplibregl's switcher is checkboxes rather than a
    radio, so a viewer *can* re-show more than one at once; the page simply starts on a single ground.

    The three keywords are the ones the Tier-2 contract declares and the interactive tier now answers to
    as well — the layers to include, the position, the controls to expose — so the same call adds a layer
    control on either tier (#264). What was ``layer_ids=`` here is ``layers=``, the name that tier uses
    for the same thing.

    **The manager widens past visibility (WB-8/WB-14), and most of the widening is declarative.**
    ``opacity=`` dims a layer and ``order=`` reorders the stack, each applied **now** — ``opacity``
    through :meth:`~digitalearth.web.core.base.WebMapBase.replace_layer`, which rewrites the layer's own
    paint, and ``order`` through :meth:`~digitalearth.web.core.base.WebMapBase.move_layer` — so the saved page
    draws the layers dimmed and in that order. The switcher itself stays a **live page-side control**
    (py-maplibregl's ``LayerSwitcherControl``), and ``controls=["visibility", "basemap"]`` adds the
    basemap layers to it (WB-14) so the ground is switchable too. A live opacity *slider* or a
    drag-to-reorder control would each need a browser-JS layer this tier does not ship (the X-2
    limitation), so ``controls=`` still refuses ``"opacity"`` rather than accept a control it cannot
    build — the inertness #242/#244 removed. So ``controls=`` selects the *live* switcher controls, while
    ``opacity=``/``order=`` are a one-time transform baked into the page and recorded on the switcher's
    furniture.

    Args:
        layers: The layers to offer, by id, defaulting to every data layer added so far — that is,
            :attr:`~digitalearth.web.core.base.WebMapBase.layer_ids` without the basemaps, which are
            addressable but are the ground rather than something a viewer toggles. Pass a subset to
            hide the rest from the switch without hiding them from the map, or name a basemap to offer
            it after all.
        position: One of the four corners in
            :data:`~digitalearth.base.controls.CONTROL_POSITIONS` — MapLibre's, and now both tiers'.
        controls: Which controls to expose, from
            :data:`~digitalearth.base.controls.LAYER_CONTROLS`. ``None`` (the default) offers
            ``("visibility",)`` — a row per data layer. ``"basemap"`` may be added
            (``["visibility", "basemap"]``) to list the basemap layers in the same switcher (WB-14), so
            the ground is switchable. ``"opacity"`` is **refused** rather than accepted and dropped: a
            live opacity slider is a control py-maplibregl does not ship (use ``opacity=`` for a
            one-time dim). What the shared resolver answers is recorded on the switcher's furniture, so
            the panel says which controls it draws rather than leaving a reader to know that this tier
            draws one.
        theme: ``"default"`` or ``"simple"`` — py-maplibregl's two switcher styles. This tier's own
            keyword: it styles the switcher rather than choosing what the switcher contains.
        opacity: A mapping of layer id to opacity in ``[0, 1]``, applied **now** by rewriting each named
            layer's paint through :meth:`~digitalearth.web.core.base.WebMapBase.replace_layer`. A layer that
            records no opacity to change — a text annotation has none — is refused rather than silently
            left opaque. ``None`` dims nothing.
        order: The bottom-to-top draw order for the named layers, applied **now** through
            :meth:`~digitalearth.web.core.base.WebMapBase.move_layer`. The ids must share a draw-order band —
            a layer cannot be dragged under the basemap, which is the one move the bands forbid — and an
            order that crosses a band is refused with the ``IndexError`` ``move_layer`` raises. ``None``
            leaves the order untouched.

    Note:
        A row toggles exactly one MapLibre layer, because that is what py-maplibregl's control does.
        Builders that draw more than one layer — ``cluster`` (bubbles, counts, loose points) and
        ``graticule`` (lines, degree labels) — are listed once, under their main layer, so toggling a
        cluster hides its bubbles while the count labels remain. ``remove_layer`` does take the whole
        group. Hiding the parts together needs a control py-maplibregl does not ship.

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

    Raises:
        ValueError: when ``position`` is not one of the four legal corners, when ``controls`` names
            something outside the shared vocabulary or something this tier cannot build, when no data
            layer has been added yet, when an id was given (in ``layers``, ``opacity`` or ``order``)
            that is not on this map, when an ``opacity`` value is not a finite fraction in ``[0, 1]``,
            or when an ``opacity`` names a layer that records no opacity to change.
        IndexError: when ``order`` would move a layer out of its draw-order band, as
            :meth:`~digitalearth.web.core.base.WebMapBase.move_layer` refuses it.

    Examples:
        - Two layers and a switch between them:
            ```python
            >>> from digitalearth.web import WebMap                            # doctest: +SKIP
            >>> (                                                              # doctest: +SKIP
            ...     WebMap()
            ...     .basemap()
            ...     .choropleth(gdf, column="pop", name="Population")
            ...     .layer_control()
            ... )

            ```

    See Also:
        digitalearth.web.core.base.WebMapBase.layer_ids: the ids this offers by default.
        digitalearth.base.controls.resolved_controls: the shared control vocabulary.
    """
    _require_maplibre()
    _check_position(position)
    # The answer is kept, not only the refusal: `resolved_controls` is the one place that knows what this
    # tier can build, and it de-duplicates and orders the names. Recording what it returned is what makes
    # the panel's description and the refusal read one list (review R2-L13). The default goes through it
    # too, so "everything this tier can build" is resolved rather than re-spelled here.
    exposed = resolved_controls(
        _DEFAULT_CONTROLS if controls is None else controls,
        offered=_OFFERED_CONTROLS,
        caller="WebMap.layer_control()",
    )
    if theme not in _SWITCHER_THEMES:
        raise ValueError(
            f"layer_control(theme={theme!r}) must be one of {sorted(_SWITCHER_THEMES)}"
        )
    available = self.layer_ids
    # The default offers the *data* layers, not every id: a basemap is described and addressable like
    # any other layer since it started recording one, and offering it by default would put "turn the
    # ground off" at the top of every switcher. Naming ``"basemap"`` in ``controls=`` opts the basemap
    # layers in (WB-14) — a basemap gallery, so a viewer can switch the ground among the basemaps on the
    # map — and a caller can still name specific ids in ``layers=`` whatever the controls.
    offer_basemaps = "basemap" in exposed
    offered = [
        layer_id
        for layer_id in available
        if offer_basemaps or self._layer_tree.get(layer_id).kind != "basemap"
    ]
    if not offered:
        raise ValueError(
            "layer_control() has nothing to switch: no data layer has been added yet. A basemap is "
            "the ground rather than a layer a viewer toggles — pass controls=['visibility', 'basemap'] "
            "to offer the basemaps themselves."
        )
    wanted = list(layers) if layers is not None else offered
    named = [*wanted, *(opacity or {}), *(order or [])]
    unknown = [layer_id for layer_id in named if layer_id not in available]
    if unknown:
        raise ValueError(
            f"layer_control() was given {unknown}, which are not on this map; its layers are "
            f"{available}"
        )
    # The declarative half (WB-8): dim, then reorder, through the map's own `replace_layer`/`move_layer`
    # rather than a new mechanism, so the saved page draws what the layers now carry. The WHOLE request is
    # validated before any layer is touched — mirroring `_bind_attribute`'s whole-list pre-check (M2):
    # `_resolve_layer_opacity` rewrites every target's paint (raising on a bad value or a layer with no
    # opacity to dim) and `_check_layer_order` proves the full order a legal in-band permutation on a trial
    # tree, both without mutating. Only then are they applied — opacity before order because `replace_layer`
    # keeps a layer's place, so the two do not fight — and both before the switcher is recorded. So a refusal
    # leaves no half-built control behind: no opacity applied, no move done, no furniture recorded (M1).
    resolved_opacity = self._resolve_layer_opacity(opacity)
    self._check_layer_order(order)
    applied_opacity = self._apply_layer_opacity(resolved_opacity)
    applied_order = self._apply_layer_order(order)
    # The basemap gallery (WB-14) opens on ONE ground. py-maplibregl's switcher is checkboxes, and every
    # basemap is registered visible, so without this a saved page would draw all of them stacked opaque
    # (the last one winning) rather than letting a viewer switch between them. Start the gallery on the
    # first offered basemap and hide the rest, so the page opens on one ground and the switcher switches it.
    if offer_basemaps:
        gallery = [
            layer_id
            for layer_id in wanted
            if self._layer_tree.get(layer_id).kind == "basemap"
        ]
        for extra in gallery[1:]:
            self.set_visible(extra, False)
    # Held as a request, not appended as a layer: the live layers are resolved when the widget is
    # built, so removing a layer afterwards cannot leave a dead row in the saved page, and calling
    # this twice replaces the request rather than stacking a second identical panel.
    self._switcher = {
        "layer_ids": wanted,
        "theme": theme,
        "position": position,
    }
    self._record_furniture(
        "layer_switcher",
        anchor=position,
        layers=tuple(wanted),
        theme=theme,
        controls=exposed,
        opacity=applied_opacity,
        order=applied_order,
    )
    return self

remove_layer(layer_id) #

Drop a previously added layer from the map.

Building a WebMap was one-way: a mistake meant starting over, which in a notebook — where these maps are built — is the normal workflow.

Parameters:

Name Type Description Default
layer_id str

An id from :attr:layer_ids.

required

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Note

The colour key goes with the layer. A key is asked for by hanging a :class:~digitalearth.base.spec.encoding.Guide on the layer's own color encoding (:meth:~digitalearth.web.legends.legend.LegendMixin.legend), so removing the layer removes the guide, and the panel — derived from the guides the live layers carry — is rebuilt without it. A surviving layer that carries its own guide then shows its own key. Nothing has to be rebuilt by hand, and no key describes a layer that is gone.

The running data extent is not like that, and is not cleared until the last layer goes. It is a "most recent" accessor rather than a model of what is on the map, so after removing one layer of several it still spans the removed one; call :meth:set_bounds if that matters. :attr:last_legend and :attr:last_breaks are "most recent" accessors too — that is what they are for — but they no longer decide what is drawn: both are handed to the most recent surviving classification here, together, so neither describes a removed layer and the two cannot answer for different layers (review L7); the key is drawn from the guides regardless.

The id is not one of those either: it goes back to the pool, so a name removed and asked for again is handed back unsuffixed. That is the lifetime all four tiers share — :func:~digitalearth.base.spec.layer.free_layer_id states it.

Raises:

Type Description
KeyError

when no such layer was added, listing the ids that were — a silent no-op here would look exactly like a layer that refused to go away.

Examples:

  • Remove one layer; the map is returned, so calls chain:
    >>> from digitalearth.web import WebMap
    >>> m = WebMap().text(4.9, 52.4, "Amsterdam", name="amsterdam").text(2.35, 48.86, "Paris", name="paris")
    >>> m.remove_layer("amsterdam") is m, m.layer_ids, len(m.layers)
    (True, ['paris'], 1)
    
  • An id that was never added is refused, naming the ids that were:
    >>> from digitalearth.web import WebMap
    >>> WebMap().text(4.9, 52.4, "Amsterdam", name="amsterdam").remove_layer("paris")
    Traceback (most recent call last):
        ...
    KeyError: "no layer 'paris' on this map; added layers are ['amsterdam']"
    
Source code in src/digitalearth/web/core/base.py
def remove_layer(self, layer_id: str) -> Self:
    """Drop a previously added layer from the map.

    Building a `WebMap` was one-way: a mistake meant starting over, which in a notebook — where these
    maps are built — is the normal workflow.

    Args:
        layer_id: An id from :attr:`layer_ids`.

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

    Note:
        **The colour key goes with the layer.** A key is asked for by hanging a
        :class:`~digitalearth.base.spec.encoding.Guide` on the layer's own ``color`` encoding
        (:meth:`~digitalearth.web.legends.legend.LegendMixin.legend`), so removing the layer removes the
        guide, and the panel — derived from the guides the live layers carry — is rebuilt without it. A
        surviving layer that carries its own guide then shows its own key. Nothing has to be rebuilt by
        hand, and no key describes a layer that is gone.

        The **running data extent** is not like that, and is not cleared until the last layer goes. It is
        a "most recent" accessor rather than a model of what is on the map, so after removing one layer
        of several it still spans the removed one; call :meth:`set_bounds` if that matters.
        :attr:`last_legend` and :attr:`last_breaks` are "most recent" accessors too — that is what they
        are for — but they no longer decide what is drawn: both are handed to the most recent
        *surviving* classification here, **together**, so neither describes a removed layer and the two
        cannot answer for different layers (review L7); the key is drawn from the guides regardless.

        The **id** is not one of those either: it goes back to the pool, so a name removed and asked for
        again is handed back unsuffixed. That is the lifetime all four tiers share —
        :func:`~digitalearth.base.spec.layer.free_layer_id` states it.

    Raises:
        KeyError: when no such layer was added, listing the ids that were — a silent no-op here would
            look exactly like a layer that refused to go away.

    Examples:
        - Remove one layer; the map is returned, so calls chain:
            ```python
            >>> from digitalearth.web import WebMap
            >>> m = WebMap().text(4.9, 52.4, "Amsterdam", name="amsterdam").text(2.35, 48.86, "Paris", name="paris")
            >>> m.remove_layer("amsterdam") is m, m.layer_ids, len(m.layers)
            (True, ['paris'], 1)

            ```
        - An id that was never added is refused, naming the ids that were:
            ```python
            >>> from digitalearth.web import WebMap
            >>> WebMap().text(4.9, 52.4, "Amsterdam", name="amsterdam").remove_layer("paris")
            Traceback (most recent call last):
                ...
            KeyError: "no layer 'paris' on this map; added layers are ['amsterdam']"

            ```
    """
    from digitalearth.web.render.renderer import derived_ids

    self._require_layer(layer_id)
    # The id is free again the moment it addresses nothing — the lifetime
    # :func:`~digitalearth.base.spec.layer.free_layer_id` states, and the one the 3-D tier already had
    # by reading its ids off the live tree. This tier reserved a removed layer's id for the life of the
    # map, so `remove_layer("wells")` followed by a new `wells` drew `wells-2` with nothing called
    # `wells` on the map — and on this tier the id is the caption the layer switcher shows (review
    # R2-M9). The ids its drawer derived were reserved with it, so they go back with it too.
    freed = (layer_id, *derived_ids(self._layer_tree.get(layer_id).kind, layer_id))
    # Read above but given back below, because the removal can still be refused: `LayerTree.remove` turns
    # down a layer another one takes its elevation from. Freeing the ids first left the pool one id short
    # of a tree that still held the layer, so the next builder call under that name died inside
    # `LayerTree.add` — "already in the tree" — instead of being suffixed the way every other tier
    # suffixes it (review R2-M8). The other three tiers evaluate the tree change inside the `_change(...)`
    # argument, which is what keeps the question in one place there.
    self._layer_tree = self._layer_tree.remove(layer_id)
    self._issued_ids.difference_update(freed)
    # A caller's own object is matched by identity: a `maplibre` `Layer` is a model that refuses the marker
    # attribute the builders' closures carry, so there is nothing on it to compare by id.
    held = self._custom.pop(layer_id, None)
    # The reference goes out of *this* map's figure, and the object stays registered: a `FigureSpec`
    # captured before the removal still names it, and forgetting here made every such figure dangle
    # (review M6). `close()` is where a map lets its data go, which is the caller saying they are
    # finished with every figure it produced.
    self._sources.pop(layer_id, None)
    self._forget_legend(layer_id)
    self._forget_slider_frame(layer_id)

    def _is_layer(layer: Any) -> bool:
        """Whether a queued layer is the one being removed.

        Args:
            layer: The queued closure or object.

        Returns:
            `True` for the builder closure that carries this id, or for the caller's own held object.
        """
        if getattr(layer, "_digitalearth_layer_id", None) == layer_id:
            return True
        return held is not None and layer is held

    # The reference band is addressed by a count, so a layer removed from it gives its slot back. Otherwise the
    # next `add_reference` inserts one place too high — above data it belongs beneath.
    self._reference_count -= sum(
        1
        for layer in self._queued[
            self._underlay_count : self._underlay_count + self._reference_count
        ]
        if _is_layer(layer)
    )
    self._underlay_count -= sum(
        1 for layer in self._queued[: self._underlay_count] if _is_layer(layer)
    )
    # The overlay band is counted from the top, for the same reason: remove a label and the next data layer
    # would otherwise be queued one place too low, beneath a label that is no longer there.
    self._overlay_count -= sum(
        1
        for layer in self._queued[len(self._queued) - self._overlay_count :]
        if _is_layer(layer)
    )
    self._queued = [layer for layer in self._queued if not _is_layer(layer)]
    # The renderer keeps its own record of what it drew, and nothing else clears it: `_reconcile` only
    # removes ids that `diff` reports, and a layer removed here is in neither figure it compares. Left
    # alone, the MapLibre source and layer objects of every removed layer are held for the map's life.
    self._renderer.remove(layer_id)
    remaining = self.layer_ids
    if self._last_layer_id == layer_id:
        self._last_layer_id = remaining[-1] if remaining else None
    self._forget_temporal_step(layer_id)
    if not remaining:
        # Nothing is drawn any more, so the classification a legend would describe is gone with it.
        self._data_bounds = None
        self.last_breaks = None
        self.last_legend = None
    # The guide went with the layer's description, so the key is rebuilt from what is left. This is the
    # one layer-management method that does not go through `_change` — the tree is written above, in a
    # sequence that also frees ids and unqueues closures — so it asks for the rebuild itself.
    from digitalearth.web.decoration.decoration import refresh_legend_panel

    refresh_legend_panel(self)
    return self

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

Add a key for a classified layer (recipe W2).

A thematic map is unreadable without one, and until this the tier drew the classes and left the caller to build a key out of band from last_breaks. The classification records what it actually coloured with (:attr:~digitalearth.web.core.base.WebMapBase.last_legend), so the key shows the rendered colours rather than a second guess at them.

The three shapes a classification can take are all handled: a categorical one gets a swatch per category, a graduated one a swatch per class with its range, and a continuous ramp a gradient bar with its end values.

The key belongs to the layer, not to the map (DE-48, order 24). What this call records is a :class:~digitalearth.base.spec.encoding.Guide on the layer's color :class:~digitalearth.base.spec.encoding.Encoding — show, the heading, and the corner — and the panel is derived from the guides the live layers carry, every time the layers change. So the key moves, hides and disappears with the layer it describes: remove the layer and the key goes, hide it and the key goes, show it again and the key comes back. It also travels: a guide survives FigureSpec being written and read back, which a panel built once never did.

Parameters:

Name Type Description Default
layer_id str | None

Which layer's classes to describe. None takes the topmost visible layer that published a colour scale — a classified choropleth/points, or a raster band's ramp, since a band carries a colour encoding of its own — and so the most recent one a viewer can see, since a key drawn for nothing on screen is the thing this call exists to avoid. It falls back to the topmost such layer of any visibility when none is visible. Under visible=False it instead takes the layer whose key is drawn, so "no key" takes off the key there is.

None
title str | None

Heading above the key. None uses the classified column's name, followed by the units in parentheses when :func:~digitalearth.base.autostyle.auto_style supplied them for the raster the classification came from. A title given here always wins, and a unit is never guessed: without one the heading is the bare column name, as it always was.

None
position str

One of the four MapLibre corners. Recorded as the guide's anchor, which takes the same four spellings (:data:~digitalearth.base.registry.FURNITURE_ANCHORS and :data:~digitalearth.base.controls.CONTROL_POSITIONS are equal tuples — two objects, one vocabulary), so nothing is translated between them.

DEFAULT_KEY_ANCHOR
labels list | None

Explicit row labels, replacing the derived ones — for units, or for renaming categories. Ignored for a continuous ramp, which has no rows. Recorded on the layer beside its guide, so a key rebuilt after another layer is removed still carries them.

None
visible bool

False records the guide with show=False — the layer says outright that its colour is explained by nothing — and draws no key, so a caller passing a flag through does not have to branch. Every other argument is checked before this one is read, whether or not any layer has been keyed yet, so no argument is valid only half the time and none is valid only in a particular call order. The one refusal the flag does decide is "this map has nothing to describe", which is a fact about the map rather than about the call.

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when position is not one of the four legal MapLibre corners, when title is not a non-empty string, when layer_id names a layer that carries no classification, when no classified layer has been added at all — there is nothing to build a key from, and an empty box would be worse than an error — or when labels has a different number of entries from the classification. Only the "nothing classified" one waits on visible.

KeyError

when layer_id names no layer on this map.

TypeError

when labels is not a sequence.

Note

This tier draws one key, and the four tiers differ here. _panels holds one entry per kind, so a second legend replaces the first rather than stacking an identical box in the same corner. Layers may each carry a guide all the same, and when several do the topmost visible one wins — draw order decides, not call order. So keying a lower layer after a higher one leaves the higher one's key drawn; take the higher one's off with legend(layer_id=<higher>, visible=False) first. The static tier has no such limit (matplotlib takes any number of colorbars) and neither does the interactive tier (its guides are per-layer options); the 3-D tier has one scalar-bar slot per title.

A guide on a hidden layer is recorded and draws nothing until the layer is shown, which is the same rule stated from the other side: the key is drawn while the layer is.

Examples:

  • A choropleth and its key:
    >>> from digitalearth.web import WebMap                        # doctest: +SKIP
    >>> (                                                          # doctest: +SKIP
    ...     WebMap().basemap().choropleth(gdf, column="pop").legend()
    ... )
    
See Also

digitalearth.web.builders.vector.VectorMixin.choropleth: the builder whose classes this describes. digitalearth.web.decoration.decoration.refresh_legend_panel: derives the panel from the recorded guides.

Source code in src/digitalearth/web/legends/legend.py
def legend(
    self,
    *,
    layer_id: str | None = None,
    title: str | None = None,
    position: str = DEFAULT_KEY_ANCHOR,
    labels: list | None = None,
    visible: bool = True,
) -> Self:
    """Add a key for a classified layer (recipe W2).

    A thematic map is unreadable without one, and until this the tier drew the classes and left the
    caller to build a key out of band from ``last_breaks``. The classification records what it actually
    coloured with (:attr:`~digitalearth.web.core.base.WebMapBase.last_legend`), so the key shows the rendered
    colours rather than a second guess at them.

    The three shapes a classification can take are all handled: a **categorical** one gets a swatch per
    category, a **graduated** one a swatch per class with its range, and a **continuous** ramp a
    gradient bar with its end values.

    **The key belongs to the layer, not to the map** (DE-48, order 24). What this call records is a
    :class:`~digitalearth.base.spec.encoding.Guide` on the layer's ``color``
    :class:`~digitalearth.base.spec.encoding.Encoding` — ``show``, the heading, and the corner — and the
    panel is **derived** from the guides the live layers carry, every time the layers change. So the key
    moves, hides and disappears with the layer it describes: remove the layer and the key goes, hide it
    and the key goes, show it again and the key comes back. It also travels: a guide survives
    ``FigureSpec`` being written and read back, which a panel built once never did.

    Args:
        layer_id: Which layer's classes to describe. `None` takes the topmost **visible** layer that
            published a colour scale — a classified ``choropleth``/``points``, or a raster band's ramp,
            since a band carries a colour encoding of its own — and so the most recent one a viewer can
            see, since a key drawn for nothing on screen is the thing this call exists to avoid. It
            falls back to the topmost such layer of any visibility when none is visible. Under
            ``visible=False`` it instead takes the layer whose key is drawn, so "no key" takes off the
            key there is.
        title: Heading above the key. ``None`` uses the classified column's name, followed by the
            units in parentheses when :func:`~digitalearth.base.autostyle.auto_style` supplied them
            for the raster the classification came from. A title given here always wins, and a unit
            is never guessed: without one the heading is the bare column name, as it always was.
        position: One of the four MapLibre corners. Recorded as the guide's ``anchor``, which takes the
            same four spellings (:data:`~digitalearth.base.registry.FURNITURE_ANCHORS` and
            :data:`~digitalearth.base.controls.CONTROL_POSITIONS` are **equal** tuples — two objects,
            one vocabulary), so nothing is translated between them.
        labels: Explicit row labels, replacing the derived ones — for units, or for renaming
            categories. Ignored for a continuous ramp, which has no rows. Recorded on the layer beside
            its guide, so a key rebuilt after another layer is removed still carries them.
        visible: `False` records the guide with ``show=False`` — the layer says outright that its colour
            is explained by nothing — and draws no key, so a caller passing a flag through does not have
            to branch. **Every other argument is checked before this one is read**, whether or not any
            layer has been keyed yet, so no argument is valid only half the time and none is valid only
            in a particular call order. The one refusal the flag does decide is "this map has nothing to
            describe", which is a fact about the map rather than about the call.

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

    Raises:
        ValueError: when ``position`` is not one of the four legal MapLibre corners, when `title` is not
            a non-empty string, when `layer_id` names a layer that carries no classification, when no
            classified layer has been added at all — there is nothing to build a key from, and an empty
            box would be worse than an error — or when `labels` has a different number of entries from
            the classification. Only the "nothing classified" one waits on ``visible``.
        KeyError: when `layer_id` names no layer on this map.
        TypeError: when `labels` is not a sequence.

    Note:
        **This tier draws one key, and the four tiers differ here.** ``_panels`` holds one entry per
        kind, so a second legend replaces the first rather than stacking an identical box in the same
        corner. Layers may each carry a guide all the same, and when several do **the topmost visible
        one wins** — draw order decides, not call order. So keying a lower layer after a higher one
        leaves the higher one's key drawn; take the higher one's off with
        ``legend(layer_id=<higher>, visible=False)`` first. The static tier has no such limit
        (matplotlib takes any number of colorbars) and neither does the interactive tier (its guides are
        per-layer options); the 3-D tier has one scalar-bar slot per title.

        A guide on a **hidden** layer is recorded and draws nothing until the layer is shown, which is
        the same rule stated from the other side: the key is drawn while the layer is.

    Examples:
        - A choropleth and its key:
            ```python
            >>> from digitalearth.web import WebMap                        # doctest: +SKIP
            >>> (                                                          # doctest: +SKIP
            ...     WebMap().basemap().choropleth(gdf, column="pop").legend()
            ... )

            ```

    See Also:
        digitalearth.web.builders.vector.VectorMixin.choropleth: the builder whose classes this describes.
        digitalearth.web.decoration.decoration.refresh_legend_panel: derives the panel from the recorded guides.
    """
    return self._record_key(
        layer_id,
        title=title,
        position=position,
        labels=labels,
        visible=visible,
        caller="legend()",
    )

set_title(heading, *, position='top-left', subtitle=None) #

Put a title on the map itself, so a saved page carries its own heading.

An exported page travels alone: whatever context the notebook around it had is gone. The title is a control rather than a layer, so it sits above the map and moves with the corner it is pinned to.

Parameters:

Name Type Description Default
heading str

The title text.

required
position str

One of the four MapLibre corners.

'top-left'
subtitle str | None

A smaller second line — a date, a source, a unit.

None

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when position is not one of the four legal MapLibre corners.

Examples:

  • Title a saved map:
    >>> from digitalearth.web import WebMap                            # doctest: +SKIP
    >>> WebMap().basemap().set_title("Population, 2024")                   # doctest: +SKIP
    
Source code in src/digitalearth/web/decoration/decoration.py
def set_title(
    self,
    heading: str,
    *,
    position: str = "top-left",
    subtitle: str | None = None,
) -> Self:
    """Put a title on the map itself, so a saved page carries its own heading.

    An exported page travels alone: whatever context the notebook around it had is gone. The title is
    a control rather than a layer, so it sits above the map and moves with the corner it is pinned to.

    Args:
        heading: The title text.
        position: One of the four MapLibre corners.
        subtitle: A smaller second line — a date, a source, a unit.

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

    Raises:
        ValueError: when ``position`` is not one of the four legal MapLibre corners.

    Examples:
        - Title a saved map:
            ```python
            >>> from digitalearth.web import WebMap                            # doctest: +SKIP
            >>> WebMap().basemap().set_title("Population, 2024")                   # doctest: +SKIP

            ```
    """
    _require_maplibre()
    _check_position(position)
    body = f'<div style="font-weight:600;font-size:15px">{_text(heading)}</div>'
    if subtitle:
        body += f'<div style="opacity:.75;margin-top:2px">{_text(subtitle)}</div>'
    self._panels["title"] = (f"<div>{body}</div>", position)
    self._title = heading
    return self

text(lon, lat, s=None, *, crs=4326, text_size=14.0, color='#ffffff', halo_color='#000000', halo_width=1.0, name=None) #

Place a single line of text at a coordinate.

The "label this spot" case, which needed a whole GeoDataFrame before — :meth:~digitalearth.web.builders.vector.VectorMixin.labels is the data-driven counterpart.

Parameters:

Name Type Description Default
lon float

X of the anchor point, in crs — a longitude by default.

required
lat float

Y of the anchor point, in crs — a latitude by default.

required
s str | None

The string to draw. Named s as it is on the static and interactive tiers (#260), which follow matplotlib's own spelling.

None
crs Any

What lon/lat are measured in. EPSG:4326 by default; a point in another CRS is reprojected into the CRS this tier places data in, exactly as a feature is (#260).

4326
text_size float

Text size in pixels. Named for the text rather than size, which means the visual size of a marker everywhere else.

14.0
color str

Text colour.

'#ffffff'
halo_color str

Colour of the outline behind the glyphs, which keeps it legible over imagery.

'#000000'
halo_width float

Halo width in pixels; 0 disables it.

1.0
name str | None

What a layer switcher calls this annotation; None uses its generated id.

None

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
TypeError

when the string to draw is not given.

ValueError

when lon, lat, text_size or halo_width is not a finite number — refused at this call, because a figure holding NaN or infinity could not be written down.

Examples:

  • Mark a place:
    >>> from digitalearth.web import WebMap                     # doctest: +SKIP
    >>> WebMap().basemap().text(4.9, 52.4, "Amsterdam")         # doctest: +SKIP
    
See Also

digitalearth.web.builders.vector.VectorMixin.labels: label many features from a column.

Source code in src/digitalearth/web/decoration/decoration.py
def text(
    self,
    lon: float,
    lat: float,
    s: str | None = None,
    *,
    crs: Any = 4326,
    text_size: float = 14.0,
    color: str = "#ffffff",
    halo_color: str = "#000000",
    halo_width: float = 1.0,
    name: str | None = None,
) -> Self:
    """Place a single line of text at a coordinate.

    The "label this spot" case, which needed a whole GeoDataFrame before —
    :meth:`~digitalearth.web.builders.vector.VectorMixin.labels` is the data-driven counterpart.

    Args:
        lon: X of the anchor point, in `crs` — a longitude by default.
        lat: Y of the anchor point, in `crs` — a latitude by default.
        s: The string to draw. Named `s` as it is on the static and interactive tiers (#260), which
            follow matplotlib's own spelling.
        crs: What `lon`/`lat` are measured in. EPSG:4326 by default; a point in another CRS is
            reprojected into the CRS this tier places data in, exactly as a feature is (#260).
        text_size: Text size in pixels. Named for the text rather than ``size``, which means the
            visual size of a marker everywhere else.
        color: Text colour.
        halo_color: Colour of the outline behind the glyphs, which keeps it legible over imagery.
        halo_width: Halo width in pixels; ``0`` disables it.
        name: What a layer switcher calls this annotation; ``None`` uses its generated id.

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

    Raises:
        TypeError: when the string to draw is not given.
        ValueError: when ``lon``, ``lat``, ``text_size`` or ``halo_width`` is not a finite number —
            refused at this call, because a figure holding NaN or infinity could not be written
            down.

    Examples:
        - Mark a place:
            ```python
            >>> from digitalearth.web import WebMap                     # doctest: +SKIP
            >>> WebMap().basemap().text(4.9, 52.4, "Amsterdam")         # doctest: +SKIP

            ```

    See Also:
        digitalearth.web.builders.vector.VectorMixin.labels: label many features from a column.
    """
    #: This builder's own name, for the refusals below to quote back at the caller.
    call = "WebMap.text()"
    if s is None:
        raise TypeError(
            "text() needs the string to draw; pass it as the third argument"
        )
    lon, lat = self._as_display_point(
        as_finite(lon, "lon", call),
        as_finite(lat, "lat", call),
        crs,
    )
    _require_layer_api()
    text_size = as_finite(text_size, "text_size", call)
    halo_width = as_finite(halo_width, "halo_width", call)
    layer_id = self._layer_id("text", name)
    # An annotation is decoration, not data: it must not decide where the map looks. On its own it is
    # a zero-area extent (maximum zoom on a point); beside data it drags the extent to reach it.
    self._index_layer(
        layer_id,
        name,
        kind="text",
        symbology=Symbology(
            props={
                "lon": float(lon),
                "lat": float(lat),
                "s": s,
                "text_size": float(text_size),
                "color": color,
                "halo_color": halo_color,
                "halo_width": float(halo_width),
            }
        ),
    )
    return self

labels(features, column, *, text_size=DEFAULT_LABEL_TEXT_SIZE, color=UNSET, halo_color=DEFAULT_LABEL_HALO_COLOR, halo_width=DEFAULT_LABEL_HALO_WIDTH, offset=None, allow_overlap=False, crs=None, name=None, visible=True) #

Label features with the text in column (recipe W2).

Labels are how a map says what is on it, and MapLibre's symbol layer does the work — data-driven text, collision detection, halos and placement. None of it was reachable: the only symbol layer the tier built was the count inside cluster.

Parameters:

Name Type Description Default
features Any

A pyramids FeatureCollection or GeoDataFrame; points label at the point, lines and polygons at a placement MapLibre picks. A path or URL to one is taken too, and is the only input this layer can be written down with — a pyramids object does not know where it came from. The reference is opened at the display choke point (:meth:~digitalearth.web.core.base.WebMapBase._opened) and the caller's own path is what the figure records.

required
column str

The property to read the text from.

required
text_size float

Text size in pixels. Named for the text rather than size, which means the visual size of a marker everywhere else.

DEFAULT_LABEL_TEXT_SIZE
color Maybe[str]

Text colour; not passed leaves :data:~digitalearth.base.symbology.DEFAULT_LABEL_COLOR, the same constant the static tier's labels reads (#345).

UNSET
halo_color str

Colour of the outline drawn behind the glyphs, which is what keeps a label legible over imagery.

DEFAULT_LABEL_HALO_COLOR
halo_width float

Halo width in pixels; 0 disables it.

DEFAULT_LABEL_HALO_WIDTH
offset Any | None

(x, y) offset in ems, e.g. (0, -1.2) to lift a label off its point.

None
allow_overlap bool

Whether labels may overlap. False (the default) lets MapLibre drop labels that collide, which is what keeps a dense layer readable.

False
crs Any

The CRS the features are in when they carry none themselves — used to place a frame that has no CRS, which would otherwise be taken as lon/lat (EPSG:4326). None (the default) leaves a self-describing frame alone. Matches the static tier's labels(crs=) (#265).

None
name str | None

What a layer switcher calls this layer; None uses its generated id.

None
visible bool

Whether the layer starts visible, which is what a layer switcher toggles.

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
TypeError

when features is not a vector layer.

KeyError

when column is not one of its properties — a MapLibre expression reading a missing property renders nothing at all, with no error to explain the empty map — or when features is a URL with no resolver registered for its scheme.

ValueError

when text_size or halo_width is not a finite number, refused at this call because a figure holding NaN or infinity could not be written down.

FileNotFoundError

when features is a path that names nothing.

Examples:

  • Name each feature:
    >>> from digitalearth.web import WebMap                          # doctest: +SKIP
    >>> WebMap().basemap().polygons(gdf).labels(gdf, "name")         # doctest: +SKIP
    
See Also

digitalearth.web.decoration.decoration.DecorationMixin.text: a single annotation at a coordinate.

Source code in src/digitalearth/web/builders/vector.py
def labels(
    self,
    features: Any,
    column: str,
    *,
    text_size: float = DEFAULT_LABEL_TEXT_SIZE,
    color: Maybe[str] = UNSET,
    halo_color: str = DEFAULT_LABEL_HALO_COLOR,
    halo_width: float = DEFAULT_LABEL_HALO_WIDTH,
    offset: Any | None = None,
    allow_overlap: bool = False,
    crs: Any = None,
    name: str | None = None,
    visible: bool = True,
) -> Self:
    """Label features with the text in ``column`` (recipe W2).

    Labels are how a map says what is on it, and MapLibre's symbol layer does the work — data-driven
    text, collision detection, halos and placement. None of it was reachable: the only symbol layer the
    tier built was the count inside ``cluster``.

    Args:
        features: A pyramids ``FeatureCollection`` or GeoDataFrame; points label at the point, lines
            and polygons at a placement MapLibre picks. A path or URL to one is taken too, and is the
            only input this layer can be written down with — a pyramids object does not know where it
            came from. The reference is opened at the display choke point
            (:meth:`~digitalearth.web.core.base.WebMapBase._opened`) and the caller's own path is what the
            figure records.
        column: The property to read the text from.
        text_size: Text size in pixels. Named for the text rather than ``size``, which means the
            visual size of a marker everywhere else.
        color: Text colour; not passed leaves
            :data:`~digitalearth.base.symbology.DEFAULT_LABEL_COLOR`, the same constant the static
            tier's ``labels`` reads (#345).
        halo_color: Colour of the outline drawn behind the glyphs, which is what keeps a label legible
            over imagery.
        halo_width: Halo width in pixels; ``0`` disables it.
        offset: ``(x, y)`` offset in ems, e.g. ``(0, -1.2)`` to lift a label off its point.
        allow_overlap: Whether labels may overlap. ``False`` (the default) lets MapLibre drop labels
            that collide, which is what keeps a dense layer readable.
        crs: The CRS the features are in when they carry none themselves — used to place a frame that
            has no CRS, which would otherwise be taken as lon/lat (EPSG:4326). ``None`` (the default)
            leaves a self-describing frame alone. Matches the static tier's ``labels(crs=)`` (#265).
        name: What a layer switcher calls this layer; ``None`` uses its generated id.
        visible: Whether the layer starts visible, which is what a layer switcher toggles.

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

    Raises:
        TypeError: when ``features`` is not a vector layer.
        KeyError: when ``column`` is not one of its properties — a MapLibre expression reading a
            missing property renders nothing at all, with no error to explain the empty map — or when
            ``features`` is a URL with no resolver registered for its scheme.
        ValueError: when ``text_size`` or ``halo_width`` is not a finite number, refused at this call
            because a figure holding NaN or infinity could not be written down.
        FileNotFoundError: when ``features`` is a path that names nothing.

    Examples:
        - Name each feature:
            ```python
            >>> from digitalearth.web import WebMap                          # doctest: +SKIP
            >>> WebMap().basemap().polygons(gdf).labels(gdf, "name")         # doctest: +SKIP

            ```

    See Also:
        digitalearth.web.decoration.decoration.DecorationMixin.text: a single annotation at a coordinate.
    """
    #: This builder's own name, for the refusals below to quote back at the caller.
    call = "WebMap.labels()"
    _, layer_types = _require_layer_api()
    ask = Ask()
    text_size = as_finite(text_size, "text_size", call)
    halo_width = as_finite(halo_width, "halo_width", call)
    gdf = self._display_gdf(features, method="labels", crs=crs)
    if column not in getattr(gdf, "columns", []):
        raise KeyError(
            f"labels(column={column!r}) is not a property of these features; available: "
            f"{sorted(c for c in getattr(gdf, 'columns', []) if c != 'geometry')}"
        )
    layout: dict = {
        "text-field": ["get", column],
        "text-size": float(text_size),
        "text-allow-overlap": bool(allow_overlap),
    }
    if offset is not None:
        layout["text-offset"] = [float(value) for value in offset]
    paint = {
        "text-color": ask("text-color", color, DEFAULT_LABEL_COLOR),
        "text-halo-color": halo_color,
        "text-halo-width": float(halo_width),
    }
    return self._vector_layer(
        gdf,
        "label",
        layer_types.SYMBOL,
        paint,
        kind="labels",
        name=name,
        visible=visible,
        layout=layout,
        source=features,
        asked=ask.named,
    )

graticule(*, lon_step=None, lat_step=None, spacing=None, color='#888888', width=0.5, opacity=UNSET, labels=True, name=None, visible=True) #

Draw a lat/lon grid over the map.

A graticule is a property of the map, not of a tile service — no basemap provides one, so this tier had no way to show one at all. The lines are ordinary GeoJSON, so they embed in the page and a map saved with offline=True keeps its grid with no network.

Parameters:

Name Type Description Default
lon_step float | None

Degrees between meridians; 30 by default, as on the interactive tier (#263).

None
lat_step float | None

Degrees between parallels; 30 by default.

None
spacing float | None

One step for both, for a caller who wants a square grid; it overrides the two above. 30 gives a readable global grid. The grid is always global — it is not clipped to the view, because a web map is pannable and a grid that stopped at the opening extent would end mid-pan — so a tight spacing is expensive: 10 embeds ~43 KiB of GeoJSON, 1 embeds ~420 KiB and 521 labels. Prefer the coarsest spacing that reads.

None
color str

Line colour.

'#888888'
width float

Line width in pixels.

0.5
opacity Maybe[float]

Line opacity in [0, 1]; a graticule is reference, so it should sit under the data visually as well as in the stack.

UNSET
labels bool

Whether to label each line with its degree value at the map's edge. It also decides whether the "<id>-label" id its drawer would derive is reserved: a graticule without labels derives none, so a later layer may take that name (review L2).

True
name str | None

What a layer switcher calls this layer; None names it "Graticule", suffixed if that is taken.

None
visible bool

Whether the layer starts visible, which is what a layer switcher toggles.

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when lon_step, lat_step, width or opacity is not a finite number — checked first, because a figure holding NaN or infinity could not be written down — or when a step is not positive, or is wider than the 180° of latitude there is to divide, either of which produces a grid with no lines and no hint as to why.

Examples:

  • A 10° grid under the data:
    >>> from digitalearth.web import WebMap        # doctest: +SKIP
    >>> WebMap().basemap().graticule()             # doctest: +SKIP
    
Source code in src/digitalearth/web/decoration/decoration.py
def graticule(
    self,
    *,
    lon_step: float | None = None,
    lat_step: float | None = None,
    spacing: float | None = None,
    color: str = "#888888",
    width: float = 0.5,
    opacity: Maybe[float] = UNSET,
    labels: bool = True,
    name: str | None = None,
    visible: bool = True,
) -> Self:
    """Draw a lat/lon grid over the map.

    A graticule is a property of the map, not of a tile service — no basemap provides one, so this tier
    had no way to show one at all. The lines are ordinary GeoJSON, so they embed in the page and a map
    saved with ``offline=True`` keeps its grid with no network.

    Args:
        lon_step: Degrees between meridians; `30` by default, as on the interactive tier (#263).
        lat_step: Degrees between parallels; `30` by default.
        spacing: One step for both, for a caller who wants a square grid; it overrides the two above.
            ``30`` gives a readable global grid. The grid is always
            global — it is not clipped to the view, because a web map is pannable and a grid that
            stopped at the opening extent would end mid-pan — so a tight spacing is expensive:
            ``10`` embeds ~43 KiB of GeoJSON, ``1`` embeds ~420 KiB and 521 labels. Prefer the
            coarsest spacing that reads.
        color: Line colour.
        width: Line width in pixels.
        opacity: Line opacity in ``[0, 1]``; a graticule is reference, so it should sit under the data
            visually as well as in the stack.
        labels: Whether to label each line with its degree value at the map's edge. It also decides
            whether the ``"<id>-label"`` id its drawer would derive is reserved: a graticule without
            labels derives none, so a later layer may take that name (review L2).
        name: What a layer switcher calls this layer; ``None`` names it ``"Graticule"``, suffixed if
            that is taken.
        visible: Whether the layer starts visible, which is what a layer switcher toggles.

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

    Raises:
        ValueError: when ``lon_step``, ``lat_step``, ``width`` or ``opacity`` is not a finite number —
            checked first, because a figure holding NaN or infinity could not be written down — or
            when a step is not positive, or is wider than the 180° of latitude there is to divide,
            either of which produces a grid with no lines and no hint as to why.

    Examples:
        - A 10° grid under the data:
            ```python
            >>> from digitalearth.web import WebMap        # doctest: +SKIP
            >>> WebMap().basemap().graticule()             # doctest: +SKIP

            ```
    """
    #: This builder's own name, for the refusals below to quote back at the caller.
    call = "WebMap.graticule()"
    _require_layer_api()
    # One step for both is what `spacing=` meant, and it is still the shortest way to ask for a square
    # grid; the two steps are what every other tier takes, and what a reader of a world map usually wants
    # (#263). A tier default of 30 degrees matches the interactive tier's.
    lon_step = _DEFAULT_GRID_STEP if lon_step is None else lon_step
    lat_step = _DEFAULT_GRID_STEP if lat_step is None else lat_step
    if spacing is not None:
        lon_step = lat_step = spacing
    # Finite first: a NaN step passes the range check below (every comparison against NaN is false) and
    # was written into the description, where it made the whole figure unwritable (review L1).
    lon_step = as_finite(lon_step, "lon_step", call)
    lat_step = as_finite(lat_step, "lat_step", call)
    width = as_finite(width, "width", call)
    ask = Ask()
    opacity = as_finite(ask("opacity", opacity, GRATICULE_OPACITY), "opacity", call)
    for name_of, step in (("lon_step", lon_step), ("lat_step", lat_step)):
        if step <= 0 or step > 180:
            # 180 is the widest meaningful step: it still yields the prime meridian and the antimeridian,
            # while anything wider leaves a grid with a single line in it.
            raise ValueError(
                f"graticule({name_of}={step!r}) must be greater than 0 and at most 180 degrees"
            )
    # The degree labels are drawn under an id derived from this one, which the allocation reserves too,
    # so a caller's `name=` can no longer take it (review M5). Only when they are drawn, though: the
    # reservation table is keyed by kind, and whether a graticule labels itself is in its description.
    # Reserving unconditionally held an id nothing drew, and the caller who then asked for that name got
    # it silently suffixed — which is the string a layer switcher captions the row with (review L2).
    layer_id = self._layer_id(
        "graticule", name or "Graticule", kind="graticule" if labels else None
    )
    # What was asked for, as values. The lines themselves are built by `draw_graticule` from exactly
    # this, so the figure describes the grid rather than naming one that a closure drew elsewhere.
    self._index_layer(
        layer_id,
        layer_id,
        kind="graticule",
        visible=visible,
        symbology=Symbology(
            props={
                "lon_step": float(lon_step),
                "lat_step": float(lat_step),
                "color": color,
                "width": float(width),
                "opacity": float(opacity),
                "labels": bool(labels),
                **ask.record,
            }
        ),
    )
    # Reference geography says nothing about where to look, so it does not frame the map. Its band —
    # over the basemap, under the data — comes from the kind's registration, not from here.
    return self

contours(dataset, *, interval=None, levels=None, band=DEFAULT_BAND, filled=False, cmap=None, units=None, color=None, width=UNSET, opacity=UNSET, labels=False, name=None, visible=True) #

Trace iso-value contours from a raster band and draw them as vectors.

The GIS is pyramids' (Dataset.contour, the gdal_contour equivalent); this only draws what it returns. Contours are the one field type that maps cleanly onto MapLibre — the result is a FeatureCollection, which the tier already knows how to render — so it is the field renderer this tier can honestly offer. Vector fields and meshes have no native primitive here; see the static and interactive tiers for those.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset. A path or URL to one is taken too, and is the only input this layer can be written down with — a pyramids object does not know where it came from. The reference is opened at the display choke point (:meth:~digitalearth.web.core.base.WebMapBase._opened) and the caller's own path is what the figure records.

required
interval float | ContourInterval | None

Spacing between levels — a number for "one every N", or a :class:ContourInterval when the spacing has to be anchored somewhere other than zero. Give at most one of this or levels.

None
levels Any | None

Explicit levels to contour. Give at most one of this or interval. With neither, the levels come from :func:~digitalearth.base.autostyle.auto_style when the band's variable is one it recognises (mean sea-level pressure, 2-m temperature, …) — the levels that field is conventionally drawn with.

None
band int

1-based band to contour, matching :meth:~digitalearth.web.builders.raster.RasterMixin.field — pyramids counts bands from 0, and this converts, so the same number means the same band everywhere in this tier.

DEFAULT_BAND
filled bool

Draw filled bands between successive levels instead of lines.

False
cmap str | None

Colormap for colouring by level; None resolves the autostyle default for the band's variable.

None
units str | None

What the contoured values are measured in, which the key names in parentheses after the column — when this layer makes a key at all. An explicit color= colours every level alike, so there is no classification to key and the units are recorded nowhere the reader sees (review #314). None (the default) takes the variable's units from :func:~digitalearth.base.autostyle.auto_style, and leaves the heading bare when it carries none — a unit is never guessed. Pass one to correct a band the library mis-identifies, or to name the units of a variable it does not know.

None
color str | None

A single colour for every contour, overriding cmap. Use it when the levels are labelled rather than colour-coded.

None
width Maybe[float]

Line width in pixels; ignored when filled.

UNSET
opacity Maybe[float]

Layer opacity in [0, 1].

UNSET
labels bool

Whether to label each contour with its value — the level for a line, the band's lower edge when filled.

False
name str | None

What a layer switcher calls this layer; None uses its generated id.

None
visible bool

Whether the layer starts visible.

True

Returns:

Type Description
Self

The same map instance, so builder calls chain.

Raises:

Type Description
ValueError

when both interval and levels are given — pyramids takes exactly one, and saying so here names the argument the caller actually wrote — when neither is given and the variable is not one auto_style knows levels for, or when width or opacity is not a finite number, refused at this call because a figure holding NaN or infinity could not be written down.

TypeError

when interval is neither a number nor a :class:ContourInterval.

FileNotFoundError

when dataset is a path that names nothing, or KeyError when no resolver is registered for its URL scheme — from :meth:~digitalearth.web.core.base.WebMapBase._opened.

Examples:

  • Contour a DEM every 100 m:
    >>> from digitalearth.web import WebMap                        # doctest: +SKIP
    >>> WebMap().basemap().contours(dem, interval=100)             # doctest: +SKIP
    
See Also

digitalearth.web.builders.vector.VectorMixin.lines: what the traced contours are drawn as. digitalearth.base.autostyle.auto_style: supplies the levels, colormap and units.

Source code in src/digitalearth/web/builders/vector.py
def contours(
    self,
    dataset: Any,
    *,
    interval: float | ContourInterval | None = None,
    levels: Any | None = None,
    band: int = DEFAULT_BAND,
    filled: bool = False,
    cmap: str | None = None,
    units: str | None = None,
    color: str | None = None,
    width: Maybe[float] = UNSET,
    opacity: Maybe[float] = UNSET,
    labels: bool = False,
    name: str | None = None,
    visible: bool = True,
) -> Self:
    """Trace iso-value contours from a raster band and draw them as vectors.

    The GIS is pyramids' (``Dataset.contour``, the ``gdal_contour`` equivalent); this only draws what
    it returns. Contours are the one field type that maps cleanly onto MapLibre — the result is a
    ``FeatureCollection``, which the tier already knows how to render — so it is the field renderer
    this tier can honestly offer. Vector fields and meshes have no native primitive here; see the
    static and interactive tiers for those.

    Args:
        dataset: A pyramids ``Dataset``.
            A path or URL to one is taken too, and is the only input this layer can be
            written down with — a pyramids object does not know where it came from. The reference
            is opened at the display choke point
            (:meth:`~digitalearth.web.core.base.WebMapBase._opened`) and the caller's own path is what
            the figure records.
        interval: Spacing between levels — a number for "one every N", or a
            :class:`ContourInterval` when the spacing has to be anchored somewhere other than zero.
            Give at most one of this or ``levels``.
        levels: Explicit levels to contour. Give at most one of this or ``interval``. With neither,
            the levels come from :func:`~digitalearth.base.autostyle.auto_style` when the band's
            variable is one it recognises (mean sea-level pressure, 2-m temperature, …) — the levels
            that field is conventionally drawn with.
        band: 1-based band to contour, matching
            :meth:`~digitalearth.web.builders.raster.RasterMixin.field` — pyramids counts bands from 0, and
            this converts, so the same number means the same band everywhere in this tier.
        filled: Draw filled bands between successive levels instead of lines.
        cmap: Colormap for colouring by level; ``None`` resolves the autostyle default for the
            band's variable.
        units: What the contoured values are measured in, which the key names in parentheses after the
            column — when this layer makes a key at all. An explicit ``color=`` colours every level
            alike, so there is no classification to key and the units are recorded nowhere the reader
            sees (review #314). ``None`` (the default) takes the variable's units from
            :func:`~digitalearth.base.autostyle.auto_style`, and leaves the heading bare when it
            carries none — a unit is never guessed. Pass one to correct a band the library
            mis-identifies, or to name the units of a variable it does not know.
        color: A single colour for every contour, overriding ``cmap``. Use it when the levels are
            labelled rather than colour-coded.
        width: Line width in pixels; ignored when ``filled``.
        opacity: Layer opacity in ``[0, 1]``.
        labels: Whether to label each contour with its value — the level for a line, the band's lower
            edge when ``filled``.
        name: What a layer switcher calls this layer; ``None`` uses its generated id.
        visible: Whether the layer starts visible.

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

    Raises:
        ValueError: when both ``interval`` and ``levels`` are given — pyramids takes exactly one, and
            saying so here names the argument the caller actually wrote — when neither is given and
            the variable is not one ``auto_style`` knows levels for, or when ``width`` or ``opacity``
            is not a finite number, refused at this call because a figure holding NaN or infinity
            could not be written down.
        TypeError: when ``interval`` is neither a number nor a :class:`ContourInterval`.
        FileNotFoundError: when `dataset` is a path that names nothing, or KeyError when no resolver
            is registered for its URL scheme — from :meth:`~digitalearth.web.core.base.WebMapBase._opened`.

    Examples:
        - Contour a DEM every 100 m:
            ```python
            >>> from digitalearth.web import WebMap                        # doctest: +SKIP
            >>> WebMap().basemap().contours(dem, interval=100)             # doctest: +SKIP

            ```

    See Also:
        digitalearth.web.builders.vector.VectorMixin.lines: what the traced contours are drawn as.
        digitalearth.base.autostyle.auto_style: supplies the levels, colormap and units.
    """
    spacing = _as_interval(interval)
    ask = Ask()
    # Which key the opacity lands on is what `filled` decides, so the record is built here rather than
    # in the sub-builder. `width=` is recorded under the line key either way: a filled band has no line,
    # so a `width=` passed to one is an ask this layer cannot express, and the lift drops a recorded key
    # the paint holds no value under rather than inventing one for it.
    width = as_finite(
        ask("line-width", width, CONTOUR_WIDTH), "width", "WebMap.contours()"
    )
    opacity = as_finite(
        ask("fill-opacity" if filled else "line-opacity", opacity, CONTOUR_OPACITY),
        "opacity",
        "WebMap.contours()",
    )
    if color is not None:
        # `color=None` already spells "not passed" on this builder, so a colour here is the caller's
        # whichever it is — an unstyled trace is coloured by level, as an expression.
        ask.always("fill-color" if filled else "line-color")
    data = self._display_raster_or_skip(dataset, layer="contours")
    if data is None:
        return self
    source = self._to_display_source(data, band=band)
    cmap = self._auto_cmap(source, cmap)
    asked_for = _ContourLevels(
        spacing,
        self._contour_levels(source, interval=spacing, levels=levels),
        asked=interval,
    )
    # Recorded before the sub-builder runs, so the key it sets can say what the values are measured in.
    self.last_units = self._auto_units(source, units)
    features = asked_for.trace(data, band=band, polygonize=filled)
    if len(features) == 0:
        # No level fell inside the band's range. Passing this on raises "column 'level' not found",
        # because pyramids only writes the attribute when it writes a feature — which points at the
        # wrong thing entirely.
        self._skipped(
            "contours",
            "no level lies within the data, so nothing was traced — check that "
            f"{asked_for.asked_as} suits band {band}'s range",
        )
        return self
    # Lines carry `level`; filled bands carry `level_min`/`level_max` for the band's two edges, so
    # colour and label the lower edge — it is what orders the bands.
    attribute = "level_min" if filled else "level"
    column = None if color else attribute
    self._draw_contour_features(
        features,
        filled=filled,
        column=column,
        cmap=cmap,
        color=color,
        width=width,
        opacity=opacity,
        name=name,
        visible=visible,
        asked=ask.named,
    )
    # The units describe *this* layer's values, so they are written on *this* layer's key — looked up
    # by the id the sub-builder just drew under, not on `last_legend`. `last_legend` answers "the most
    # recent classification", so with an explicit `color=` (where `column` is `None` and this layer
    # classifies nothing) it still pointed at whichever layer classified before, and that layer's
    # classes ended up labelled in this raster's units (#314). Asking the layer also means a draw the
    # tier declined — which leaves no key behind — writes nothing at all.
    drawn_id = self._last_layer_id
    keyed = self._legends.get(drawn_id) if drawn_id is not None else None
    if self.last_units and keyed is not None:
        # Never guessed: `last_units` is only set when auto_style supplied one.
        keyed["units"] = self.last_units
    if labels:
        # Otherwise a hidden contour layer leaves its level numbers floating with nothing to annotate.
        return self.labels(features, attribute, visible=visible)
    return self

rgb_composite(dataset, bands=DEFAULT_COMPOSITE_BANDS, *, mask_nodata=True, limits=None, opacity=UNSET, visible=True, name=None, tiles=None) #

Overlay three bands as a true- or false-colour image (recipe W1).

Satellite imagery is a headline use of a web map, and the tier could only draw one band through a colormap. The stretch comes from :mod:digitalearth.base.stretch — the same engine-neutral code the static tier's rgb_composite uses — so the same three bands look the same on both tiers.

The three channels are read straight as red, green and blue; :meth:hsv_composite reads the same three as hue, saturation and value.

Parameters:

Name Type Description Default
dataset Any

A pyramids Dataset (or anything get_stack accepts). A path or URL to one is taken too, and is the only input this layer can be written down with — a pyramids object does not know where it came from. The reference is opened at the display choke point (:meth:~digitalearth.web.core.base.WebMapBase._opened) and the caller's own path is what the figure records.

required
bands Any

The three 1-based band numbers, in red-green-blue order.

DEFAULT_COMPOSITE_BANDS
mask_nodata bool

Whether NoData becomes NaN (and so transparent) rather than a real value.

True
limits Any | None

Per-channel (lo, hi) stretch limits in band order. None derives them from this image; pass a fixed set to keep a series comparable across frames.

None
opacity Maybe[float]

Raster layer opacity in [0, 1].

UNSET
visible bool

Whether the layer starts visible, which is what a layer switcher toggles.

True
name str | None

What a layer switcher calls this layer; None uses its generated id.

None
tiles TileRoute | None

How the pixels reach the page, as on :meth:field: None (the default) inlines them, and is refused above :data:_LARGE_RASTER_PIXELS cells; a :class:TileRoute writes them beside the page — TileRoute("xyz", path, zooms) a {z}/{x}/{y}.png pyramid, TileRoute("cog", path) one Cloud-Optimized GeoTIFF the page reads windows from. Either makes the output a folder rather than one file. A tiled composite is stretched on one set of bounds for the whole pyramid — limits when given, otherwise measured from a decimated read — because a tile stretched over its own percentiles disagrees with its neighbour across their shared edge.

None

Returns:

Type Description
Self

The same map instance, so builder calls chain. A composite that cannot be placed — off-limb

Self

in the display CRS, or with corners that will not express as lon/lat — is skipped with a

Self

warning instead, unless the map was built with strict=True.

Raises:

Type Description
ValueError

when bands is not exactly three, when limits does not match them, when the composite has no finite pixels to draw, or when opacity is not a finite number — refused at this call, because a figure holding NaN or infinity could not be written down.

FileNotFoundError

when dataset is a path that names nothing, or KeyError when no resolver is registered for its URL scheme — from :meth:~digitalearth.web.core.base.WebMapBase._opened.

TypeError

for a tiled route, when dataset is not a raster pyramids can read windows out of; see :meth:field, whose tiled route shares this one's writer.

Examples:

  • A true-colour composite from a Landsat-ordered dataset:
    >>> from digitalearth.web import WebMap                       # doctest: +SKIP
    >>> WebMap().basemap().rgb_composite(ds, bands=(4, 3, 2))     # doctest: +SKIP
    
See Also

digitalearth.web.builders.raster.RasterMixin.hsv_composite: the same three bands read as hue/sat/value. digitalearth.base.stretch.channel_limits: derives the limits this accepts. digitalearth.web.builders.raster.RasterMixin.field: the single-band, colormapped path.

Source code in src/digitalearth/web/builders/raster.py
def rgb_composite(
    self,
    dataset: Any,
    bands: Any = DEFAULT_COMPOSITE_BANDS,
    *,
    mask_nodata: bool = True,
    limits: Any | None = None,
    opacity: Maybe[float] = UNSET,
    visible: bool = True,
    name: str | None = None,
    tiles: TileRoute | None = None,
) -> Self:
    """Overlay three bands as a true- or false-colour image (recipe W1).

    Satellite imagery is a headline use of a web map, and the tier could only draw one band through a
    colormap. The stretch comes from :mod:`digitalearth.base.stretch` — the same engine-neutral code
    the static tier's ``rgb_composite`` uses — so the same three bands look the same on both tiers.

    The three channels are read straight as red, green and blue; :meth:`hsv_composite` reads the same
    three as hue, saturation and value.

    Args:
        dataset: A pyramids ``Dataset`` (or anything ``get_stack`` accepts).
            A path or URL to one is taken too, and is the only input this layer can be
            written down with — a pyramids object does not know where it came from. The reference
            is opened at the display choke point
            (:meth:`~digitalearth.web.core.base.WebMapBase._opened`) and the caller's own path is what
            the figure records.
        bands: The three 1-based band numbers, in red-green-blue order.
        mask_nodata: Whether NoData becomes NaN (and so transparent) rather than a real value.
        limits: Per-channel ``(lo, hi)`` stretch limits in band order. ``None`` derives them from this
            image; pass a fixed set to keep a series comparable across frames.
        opacity: Raster layer opacity in ``[0, 1]``.
        visible: Whether the layer starts visible, which is what a layer switcher toggles.
        name: What a layer switcher calls this layer; ``None`` uses its generated id.
        tiles: How the pixels reach the page, as on :meth:`field`: ``None`` (the default) inlines them,
            and is refused above :data:`_LARGE_RASTER_PIXELS` cells; a :class:`TileRoute` writes them
            beside the page — ``TileRoute("xyz", path, zooms)`` a ``{z}/{x}/{y}.png`` pyramid,
            ``TileRoute("cog", path)`` one Cloud-Optimized GeoTIFF the page reads windows from. Either makes
            the output a **folder** rather than one file. A tiled composite is stretched on one set of
            bounds for the whole pyramid — ``limits`` when given, otherwise measured from a decimated read —
            because a tile stretched over its own percentiles disagrees with its neighbour across their
            shared edge.

    Returns:
        The same map instance, so builder calls chain. A composite that cannot be placed — off-limb
        in the display CRS, or with corners that will not express as lon/lat — is skipped with a
        warning instead, unless the map was built with ``strict=True``.

    Raises:
        ValueError: when ``bands`` is not exactly three, when ``limits`` does not match them, when the
            composite has no finite pixels to draw, or when ``opacity`` is not a finite number —
            refused at this call, because a figure holding NaN or infinity could not be written down.
        FileNotFoundError: when `dataset` is a path that names nothing, or KeyError when no resolver
            is registered for its URL scheme — from :meth:`~digitalearth.web.core.base.WebMapBase._opened`.
        TypeError: for a tiled route, when `dataset` is not a raster pyramids can read windows out of;
            see :meth:`field`, whose tiled route shares this one's writer.

    Examples:
        - A true-colour composite from a Landsat-ordered dataset:
            ```python
            >>> from digitalearth.web import WebMap                       # doctest: +SKIP
            >>> WebMap().basemap().rgb_composite(ds, bands=(4, 3, 2))     # doctest: +SKIP

            ```

    See Also:
        digitalearth.web.builders.raster.RasterMixin.hsv_composite: the same three bands read as hue/sat/value.
        digitalearth.base.stretch.channel_limits: derives the ``limits`` this accepts.
        digitalearth.web.builders.raster.RasterMixin.field: the single-band, colormapped path.
    """
    return self._composite(
        _RGB_RECIPE,
        dataset,
        bands,
        mask_nodata=mask_nodata,
        limits=limits,
        opacity=opacity,
        visible=visible,
        name=name,
        tiles=tiles,
    )

save_animation(path, *, fps=DEFAULT_FPS, loop=0, title=DEFAULT_TITLE, format=None) #

Write a temporal map's steps as an animated GIF or an MP4 video (recipe W7).

A time series is the case where a moving image says most, and it is also the case a web page carries worst — a saved page shows a step picker, not an animation, and nothing could be pasted into a report. The other two tiers have had save_animation all along.

One frame is rendered per time step, by making that step the only visible one and screenshotting the page, so the frames are the same pixels the map draws. That frame pipeline is shared by both output kinds; only the encoder differs — a GIF is written by Pillow, an MP4 by ffmpeg (via imageio-ffmpeg).

Parameters:

Name Type Description Default
path str

Where to write the animation. The suffix picks the encoder when format is not given: .mp4 encodes a video, anything else (.gif by convention) a GIF.

required
fps float

Frames per second — the rate every tier's animation entry point takes, with the same default (:data:DEFAULT_FPS, 3.0, declared once in :mod:digitalearth.base.animation), so one number means one speed across the whole package. This entry point used to be spelled duration=0.8 (one frame held 0.8 s, i.e. 1.25 fps); a call that names no rate now renders faster, and fps=1.25 restores the previous speed.

DEFAULT_FPS
loop int

How many times to repeat; 0 loops forever. GIF only — an MP4 carries no loop field (a player or the HTML <video loop> attribute decides), so it is ignored for .mp4.

0
title str

HTML document title used while rendering.

DEFAULT_TITLE
format str | None

Force the encoder — "gif" or "mp4" — regardless of the path suffix; None infers it from the suffix.

None

Returns:

Name Type Description
The Path

class:pathlib.Path written.

Raises:

Type Description
ValueError

when the map has no time steps to animate, or fewer than two; when fps is not a finite positive number (a zero rate has no frame to hold, and a nan/inf one is no rate at all); or when format is neither "gif" nor "mp4".

ImportError

when no headless browser is installed — the same gated dependency the PNG snapshot needs, deliberately not part of digitalearth[web] — or, for an MP4, when imageio-ffmpeg is absent.

Examples:

  • Animate a raster stack to a GIF, or to an MP4 by changing the suffix:
    >>> from digitalearth.web import WebMap                           # doctest: +SKIP
    >>> from pyramids.dataset.collection import DatasetCollection   # doctest: +SKIP
    >>> stack = DatasetCollection.from_files(["jan.tif", "feb.tif"])  # doctest: +SKIP
    >>> WebMap().basemap().timeslider(stack).save_animation("out.gif")       # doctest: +SKIP
    >>> WebMap().basemap().timeslider(stack).save_animation("out.mp4")       # doctest: +SKIP
    
See Also

digitalearth.web.temporal.temporal.TemporalMixin.timeslider: builds the steps this animates.

Source code in src/digitalearth/web/output/export.py
def save_animation(
    self,
    path: str,
    *,
    fps: float = DEFAULT_FPS,
    loop: int = 0,
    title: str = DEFAULT_TITLE,
    format: str | None = None,
) -> pathlib.Path:
    """Write a temporal map's steps as an animated GIF or an MP4 video (recipe W7).

    A time series is the case where a moving image says most, and it is also the case a web page
    carries worst — a saved page shows a step picker, not an animation, and nothing could be pasted
    into a report. The other two tiers have had ``save_animation`` all along.

    One frame is rendered per time step, by making that step the only visible one and screenshotting
    the page, so the frames are the same pixels the map draws. That frame pipeline is shared by both
    output kinds; only the encoder differs — a GIF is written by Pillow, an MP4 by ffmpeg (via
    ``imageio-ffmpeg``).

    Args:
        path: Where to write the animation. The suffix picks the encoder when ``format`` is not given:
            ``.mp4`` encodes a video, anything else (``.gif`` by convention) a GIF.
        fps: Frames per second — the rate every tier's animation entry point takes, with the same
            default (:data:`DEFAULT_FPS`, ``3.0``, declared once in
            :mod:`digitalearth.base.animation`), so one number means one speed across the whole
            package. This entry point used to be spelled ``duration=0.8`` (one frame held 0.8 s, i.e.
            1.25 fps); a call that names no rate now renders faster, and ``fps=1.25`` restores the
            previous speed.
        loop: How many times to repeat; ``0`` loops forever. GIF only — an MP4 carries no loop field
            (a player or the HTML ``<video loop>`` attribute decides), so it is ignored for ``.mp4``.
        title: HTML document title used while rendering.
        format: Force the encoder — ``"gif"`` or ``"mp4"`` — regardless of the path suffix; ``None``
            infers it from the suffix.

    Returns:
        The :class:`pathlib.Path` written.

    Raises:
        ValueError: when the map has no time steps to animate, or fewer than two; when ``fps`` is not a
            finite positive number (a zero rate has no frame to hold, and a ``nan``/``inf`` one is no
            rate at all); or when ``format`` is neither ``"gif"`` nor ``"mp4"``.
        ImportError: when no headless browser is installed — the same gated dependency the PNG snapshot
            needs, deliberately not part of ``digitalearth[web]`` — or, for an MP4, when
            ``imageio-ffmpeg`` is absent.

    Examples:
        - Animate a raster stack to a GIF, or to an MP4 by changing the suffix:
            ```python
            >>> from digitalearth.web import WebMap                           # doctest: +SKIP
            >>> from pyramids.dataset.collection import DatasetCollection   # doctest: +SKIP
            >>> stack = DatasetCollection.from_files(["jan.tif", "feb.tif"])  # doctest: +SKIP
            >>> WebMap().basemap().timeslider(stack).save_animation("out.gif")       # doctest: +SKIP
            >>> WebMap().basemap().timeslider(stack).save_animation("out.mp4")       # doctest: +SKIP

            ```

    See Also:
        digitalearth.web.temporal.temporal.TemporalMixin.timeslider: builds the steps this animates.
    """
    if not math.isfinite(float(fps)):
        raise ValueError(f"fps= must be a finite rate; got {fps!r}")
    if float(fps) <= 0:
        raise ValueError(f"fps= must be positive; got {fps!r}")
    container = self._animation_format(path, format)
    if container == "mp4":
        # Probe the encoder before rendering a single frame — each render launches a headless browser, so
        # a missing encoder must not cost the whole (slow) render first. This matches the up-front format
        # validation above; `_write_mp4` imports it again at encode time, raising the same message (L1).
        _require_ffmpeg()
    frames = self._temporal_frames()
    with tempfile.TemporaryDirectory() as work:
        images = [
            self._frame_png(
                pathlib.Path(work) / f"frame{index}.png",
                frame,
                title,
                kind=container.upper(),
            )
            for index, frame in enumerate(frames)
        ]
        if container == "mp4":
            _write_mp4(images, path, fps=float(fps))
        else:
            _write_gif(images, path, duration=1.0 / float(fps), loop=loop)
    return pathlib.Path(path)