MapLibre

Styled vector-tile maps with 3D extrusions, live restyling, and deck.gl layers, all driven from Python.

MapLibre draws smooth vector-tile maps with a declarative style language and native 3D: pitch, bearing, extrusions, and a globe. With the maplibre package and @render_maplibre, clicks, drawn shapes, and the view reach your app as reactive values.

hero

A 3D choropleth of US population density, colored and extruded from one GeoJSON source. Try the app.

Installation

pip install 'shinywidgets[maplibre]'

This installs maplibre[anywidget]. To render pydeck.Layer objects on a MapLibre map, also install pydeck.

Quick start

A Map fills its card by default. The default style (Carto.DARK_MATTER) needs no API key.

from maplibre import Map, MapOptions
from maplibre.basemaps import Carto
from shiny.express import ui
from shinywidgets import render_maplibre

ui.page_opts(fillable=True)

with ui.card(full_screen=True):

    @render_maplibre
    def city():
        return Map(
            MapOptions(style=Carto.DARK_MATTER, center=(2.3522, 48.8566), zoom=11)
        )

quickstart

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Map features

Each of the following is a plain maplibre/MapLibre GL JS capability – nothing Shiny-specific yet; render_maplibre just displays whatever Map you build.

Vector-tile basemaps

maplibre.basemaps ships ready-to-use style URLs for Carto (dark matter, positron, voyager) and OpenFreeMap (liberty, positron, bright) – all free, keyless vector tiles. Switch styles in place with add_call("setStyle", url); it’s a MapLibre GL JS method with no dedicated Python wrapper, so add_call() reaches it directly.

from maplibre import Map, MapOptions
from maplibre.basemaps import Basemap, Carto, OpenFreeMap
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_maplibre

STYLES = {
    "Carto Dark Matter": Basemap.carto_url(Carto.DARK_MATTER),
    "Carto Positron": Basemap.carto_url(Carto.POSITRON),
    "OpenFreeMap Liberty": Basemap.openfreemap_url(OpenFreeMap.LIBERTY),
}

ui.page_opts(fillable=True)
ui.input_radio_buttons("style", "Basemap style", list(STYLES), inline=True)

with ui.card(full_screen=True):

    @render_maplibre
    def city():
        return Map(MapOptions(style=STYLES["Carto Dark Matter"], center=(2.3522, 48.8566), zoom=11))


@reactive.effect
def _set_style():
    # setStyle is a MapLibre GL JS method with no dedicated Python wrapper;
    # add_call() reaches it directly. It swaps the basemap without re-rendering
    # the widget, so the camera position is kept.
    city.widget.add_call("setStyle", STYLES[input.style()])

setStyle replaces the whole style, including any custom sources and layers you’ve added – re-add them after switching if you need to keep them.

GeoJSON choropleth

Point a GeoJSONSource at the data (a dict, or a URL the browser fetches directly) and use a MapLibre paint expression to color each feature from a property. The expression runs in the browser, so pan and zoom never touch Python.

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny.express import ui
from shinywidgets import render_maplibre

STATES = requests.get(
    "https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json"
).json()

# A data-driven paint expression: color interpolates on each feature's
# `density` property (people per square mile), evaluated entirely in the
# browser -- no Python round trip as the map pans or zooms.
DENSITY_COLOR = [
    "interpolate", ["linear"], ["get", "density"],
    0, "#FFEDA0", 10, "#FED976", 20, "#FEB24C", 50, "#FD8D3C",
    100, "#FC4E2A", 200, "#E31A1C", 500, "#BD0026", 1000, "#800026",
]  # fmt: skip

ui.page_opts(fillable=True)

with ui.card(full_screen=True):

    @render_maplibre
    def choropleth():
        m = Map(MapOptions(style=Carto.POSITRON, center=(-98.5, 39.8), zoom=3.3))
        m.add_source("states", GeoJSONSource(data=STATES))
        m.add_layer(
            Layer(
                id="states-fill",
                type=LayerType.FILL,
                source="states",
                paint={"fill-color": DENSITY_COLOR, "fill-opacity": 0.8},
            )
        )
        m.add_layer(
            Layer(
                id="states-outline",
                type=LayerType.LINE,
                source="states",
                paint={"line-color": "#ffffff", "line-width": 0.5},
            )
        )
        return m

choropleth

3D with fill-extrusion

The same fill-extrusion layer type and a pitch/bearing camera turn a GeoJSON polygon layer into a skyline – no separate 3D library needed. fill-extrusion-height is just another paint expression. Same data as the choropleth above, plus a height expression and a pitched camera:

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny.express import ui
from shinywidgets import render_maplibre

STATES = requests.get(
    "https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json"
).json()

DENSITY_COLOR = [
    "interpolate", ["linear"], ["get", "density"],
    0, "#FFEDA0", 10, "#FED976", 20, "#FEB24C", 50, "#FD8D3C",
    100, "#FC4E2A", 200, "#E31A1C", 500, "#BD0026", 1000, "#800026",
]  # fmt: skip
# Same property drives extrusion height (meters), exaggerated for visibility
DENSITY_HEIGHT = [
    "interpolate", ["linear"], ["get", "density"],
    0, 0, 10, 20000, 100, 120000, 1000, 600000,
]  # fmt: skip

ui.page_opts(fillable=True)

with ui.card(full_screen=True):

    @render_maplibre
    def extrusion():
        m = Map(
            MapOptions(
                style=Carto.DARK_MATTER,
                center=(-98.5, 39.8),
                zoom=3.3,
                pitch=55,
                bearing=-10,
            )
        )
        m.add_source("states", GeoJSONSource(data=STATES))
        m.add_layer(
            Layer(
                id="states-extrude",
                type=LayerType.FILL_EXTRUSION,
                source="states",
                paint={
                    "fill-extrusion-color": DENSITY_COLOR,
                    "fill-extrusion-height": DENSITY_HEIGHT,
                    "fill-extrusion-opacity": 0.9,
                },
            )
        )
        return m

3D extrusion

Heatmaps

A type="heatmap" layer renders density straight from point data, with weight, radius, and color all as expressions (here, weighted and colored by earthquake magnitude).

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny.express import ui
from shinywidgets import render_maplibre

# ~6,100 earthquakes (magnitude and location), maplibre's own heatmap-tutorial dataset
EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()

ui.page_opts(fillable=True)

with ui.card(full_screen=True):

    @render_maplibre
    def heatmap():
        m = Map(MapOptions(style=Carto.DARK_MATTER, center=(0, 20), zoom=1.3))
        m.add_source("quakes", GeoJSONSource(data=EARTHQUAKES))
        m.add_layer(
            Layer(
                id="quakes-heat",
                type=LayerType.HEATMAP,
                source="quakes",
                paint={
                    "heatmap-weight": ["interpolate", ["linear"], ["get", "mag"], 0, 0, 8, 1],
                    "heatmap-intensity": ["interpolate", ["linear"], ["zoom"], 0, 1, 9, 3],
                    "heatmap-color": [
                        "interpolate", ["linear"], ["heatmap-density"],
                        0, "rgba(33,102,172,0)", 0.2, "#67a9cf", 0.4, "#d1e5f0",
                        0.6, "#fddbc7", 0.8, "#ef8a62", 1, "#b2182b",
                    ],  # fmt: skip
                    "heatmap-radius": ["interpolate", ["linear"], ["zoom"], 0, 2, 9, 25],
                },
            )
        )
        return m

heatmap

Popups and tooltips

add_tooltip() (hover) and add_popup() (click) render a mustache template – or a single property, or every property – from the clicked/hovered feature, entirely in the browser.

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny.express import ui
from shinywidgets import render_maplibre

EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()

ui.page_opts(fillable=True)

with ui.card(full_screen=True):

    @render_maplibre
    def quakes():
        # Centered on the 2017 Chiapas (Mexico) M8.1 earthquake, so there's a
        # large circle right away to click and hover
        m = Map(MapOptions(style=Carto.DARK_MATTER, center=(-93.9067, 15.0356), zoom=5))
        m.add_source("quakes", GeoJSONSource(data=EARTHQUAKES))
        m.add_layer(
            Layer(
                id="quakes-circle",
                type=LayerType.CIRCLE,
                source="quakes",
                # Only the strongest quakes, to keep the map readable
                filter=[">=", ["get", "mag"], 5],
                paint={
                    "circle-radius": ["interpolate", ["linear"], ["get", "mag"], 5, 4, 8, 16],
                    "circle-color": ["interpolate", ["linear"], ["get", "mag"], 5, "#fed976", 8, "#b10026"],
                    "circle-stroke-color": "white",
                    "circle-stroke-width": 1,
                },
            )
        )
        # Hover: client-side tooltip, no Python round trip
        m.add_tooltip("quakes-circle", template="Magnitude {{mag}}")
        # Click: client-side popup with the clicked feature's properties
        m.add_popup("quakes-circle", template="<b>M{{mag}}</b> earthquake")
        return m

Globe projection

Map.set_projection("vertical-perspective") switches to a 3D globe. Add a GlobeControl() to let users toggle it themselves.

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.controls import GlobeControl
from maplibre.sources import GeoJSONSource
from shiny.express import ui
from shinywidgets import render_maplibre

EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()

ui.page_opts(fillable=True)

with ui.card(full_screen=True):

    @render_maplibre
    def globe():
        m = Map(
            MapOptions(style=Carto.DARK_MATTER, center=(0, 20), zoom=1.2),
            controls=[GlobeControl()],  # lets the user toggle globe <-> flat map
        )
        # MapLibre's 3D globe projection is named "vertical-perspective"; pass
        # the string, not maplibre.projection.ProjectionType.GLOBE -- that
        # enum member isn't JSON-serializable and silently drops every other
        # queued call for this map (see the guide's Gotchas section)
        m.set_projection("vertical-perspective")
        m.add_source("quakes", GeoJSONSource(data=EARTHQUAKES))
        m.add_layer(
            Layer(
                id="quakes-circle",
                type=LayerType.CIRCLE,
                source="quakes",
                filter=[">=", ["get", "mag"], 5],
                paint={"circle-radius": 4, "circle-color": "#fd8d3c"},
            )
        )
        return m

globe

Deck.GL layers

pydeck.Layer objects pass straight to add_deck_layers() / set_deck_layers(). This is the supported replacement for @render_pydeck, which pydeck 0.9 broke by removing pydeck’s own Jupyter widget. Updating the layer list restyles in place and keeps the camera where it is, but each update sends the layer’s data again.

import pydeck as pdk
import requests
from maplibre import Map, MapOptions
from maplibre.basemaps import Carto
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_maplibre

EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()
POINTS = [f["geometry"]["coordinates"][:2] for f in EARTHQUAKES["features"]]

ui.page_opts(fillable=True)
ui.input_slider("radius", "Hexagon radius (km)", 50, 500, 200, step=50)

with ui.card(full_screen=True):

    @render_maplibre
    def deck():
        m = Map(MapOptions(style=Carto.DARK_MATTER, center=(0, 20), zoom=1.2))
        # pydeck.Layer objects pass straight to a maplibre Map -- this is the
        # migration path for @render_pydeck, which pydeck 0.9 removed support for.
        m.add_deck_layers([hexagon_layer()])
        return m


@reactive.effect
def _restyle():
    # set_deck_layers() restyles in place, keeping the camera where it is; each
    # call sends the layer's data again.
    deck.widget.set_deck_layers([hexagon_layer()])


def hexagon_layer() -> pdk.Layer:
    return pdk.Layer(
        "HexagonLayer",
        POINTS,
        id="quakes-hex",
        get_position="-",
        radius=input.radius() * 1000,
        extruded=True,
        elevation_scale=2000,
        pickable=True,
    )

Reacting to interaction

Read an accessor in a reactive function (a @render.* function, @reactive.calc, or @reactive.effect) and the function re-runs whenever the user gestures, much like input.my_slider() reads an input.

Click for feature detail

clicked() only gives a lng/lat, not a feature – MapLibre doesn’t report which feature was clicked, only where. Find the nearest feature in Python and render its details:

import numpy as np
import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny.express import render, ui
from shinywidgets import render_maplibre

EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()
QUAKES = [f for f in EARTHQUAKES["features"] if f["properties"]["mag"] >= 5]
LNG = np.array([f["geometry"]["coordinates"][0] for f in QUAKES])
LAT = np.array([f["geometry"]["coordinates"][1] for f in QUAKES])

ui.page_opts(fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_maplibre
        def quakes():
            # Centered on the 2017 Chiapas (Mexico) M8.1 earthquake
            m = Map(MapOptions(style=Carto.DARK_MATTER, center=(-93.9067, 15.0356), zoom=5))
            m.add_source("quakes", GeoJSONSource(data=EARTHQUAKES))
            m.add_layer(
                Layer(
                    id="quakes-circle",
                    type=LayerType.CIRCLE,
                    source="quakes",
                    filter=[">=", ["get", "mag"], 5],
                    paint={"circle-radius": 6, "circle-color": "#fd8d3c"},
                )
            )
            return m

    with ui.card():
        ui.card_header("Clicked earthquake")

        @render.ui
        def detail():
            # `clicked()` is a bare lng/lat -- maplibre doesn't report which
            # feature was clicked, so find the nearest one in Python.
            ll = quakes.clicked()
            if ll is None:
                return "Click a dot on the map."
            i = int(np.argmin((LNG - ll["lng"]) ** 2 + (LAT - ll["lat"]) ** 2))
            f = QUAKES[i]
            return ui.tags.ul(
                ui.tags.li(f"Magnitude: {f['properties']['mag']}"),
                ui.tags.li(f"Location: {LAT[i]:.2f}, {LNG[i]:.2f}"),
            )

Drawing shapes with MapboxDraw

m.add_mapbox_draw() adds drawing controls (point, line, polygon, trash); drawn_features() reports the current shapes on every create/update/delete:

from maplibre import Map, MapOptions
from maplibre.basemaps import Carto
from shiny.express import render, ui
from shinywidgets import render_maplibre

ui.page_opts(fillable=True)

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card(full_screen=True):

        @render_maplibre
        def city():
            m = Map(MapOptions(style=Carto.POSITRON, center=(2.3522, 48.8566), zoom=11))
            m.add_mapbox_draw()
            return m

    with ui.card():
        ui.card_header("Drawn features")

        @render.code
        def drawn():
            feats = city.drawn_features()
            return f"{len(feats)} feature(s) drawn\n\n{feats}"

Updating in place

Treat the render function as one-time setup and restyle the live map from effects. Re-rendering rebuilds the map from scratch – the user’s pan, zoom, and any selection state resets – while .widget method calls (set_paint_property, set_filter, set_data, add_layer, fit_bounds, add_call) are sent as commands to the existing map and never touch the camera unless you ask them to.

Restyling a choropleth

A color-ramp dropdown and a density-filter slider both restyle the same rendered choropleth. The render function reads the initial ramp under reactive.isolate(), so changing the dropdown later never re-triggers it:

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_maplibre

STATES = requests.get(
    "https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json"
).json()
RAMPS = {
    "Sequential (orange-red)": ["interpolate", ["linear"], ["get", "density"], 0, "#ffffb2", 200, "#fd8d3c", 1000, "#bd0026"],
    "Diverging (blue-red)": ["interpolate", ["linear"], ["get", "density"], 0, "#2166ac", 200, "#f7f7f7", 1000, "#b2182b"],
}  # fmt: skip

ui.page_opts(fillable=True)
ui.input_select("ramp", "Color ramp", list(RAMPS))
ui.input_slider("min_density", "Minimum density shown", 0, 500, 0, step=25)

with ui.card(full_screen=True):

    @render_maplibre
    def choropleth():
        # Read once: the slider and dropdown restyle the existing map below,
        # so this function never needs to run again as the user adjusts them --
        # which also means the camera (pan/zoom) is never reset.
        with reactive.isolate():
            ramp = RAMPS[input.ramp()]
        m = Map(MapOptions(style=Carto.POSITRON, center=(-98.5, 39.8), zoom=3.3))
        m.add_source("states", GeoJSONSource(data=STATES))
        m.add_layer(
            Layer(id="states-fill", type=LayerType.FILL, source="states", paint={"fill-color": ramp})
        )
        return m


@reactive.effect
def _recolor():
    choropleth.widget.set_paint_property("states-fill", "fill-color", RAMPS[input.ramp()])


@reactive.effect
def _refilter():
    choropleth.widget.set_filter("states-fill", [">=", ["get", "density"], input.min_density()])

The map was panned and zoomed to the Northeast before either control was touched. Switching the ramp and raising the filter restyles the same view, camera untouched:

Filtering without losing the viewport

The same set_filter() call works from any input. Here a magnitude-threshold slider drives the filter on a different map than the one above, to show the viewport survives untouched:

import requests
from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.basemaps import Carto
from maplibre.sources import GeoJSONSource
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_maplibre

EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()

ui.page_opts(fillable=True)
ui.input_slider("min_mag", "Minimum magnitude", 0, 8, 0, step=0.5)

with ui.card(full_screen=True):

    @render_maplibre
    def quakes():
        m = Map(MapOptions(style=Carto.DARK_MATTER, center=(0, 20), zoom=1.2))
        m.add_source("quakes", GeoJSONSource(data=EARTHQUAKES))
        m.add_layer(
            Layer(
                id="quakes-circle",
                type=LayerType.CIRCLE,
                source="quakes",
                paint={"circle-radius": 3, "circle-color": "#fd8d3c", "circle-opacity": 0.7},
            )
        )
        return m


@reactive.effect
def _filter():
    # set_filter() restyles the existing layer; it never rebuilds the map, so
    # wherever the user has panned and zoomed to stays exactly where it was.
    quakes.widget.set_filter("quakes-circle", [">=", ["get", "mag"], input.min_mag()])

Flying to a table selection

For camera moves you do want, add_call("flyTo", {...}) (or "easeTo", "jumpTo") animates the view from Python. A plain Shiny @render.data_frame drives it here: clicking a row flies the map to that earthquake.

import pandas as pd
import requests
from maplibre import Map, MapOptions
from maplibre.basemaps import Carto
from shiny import reactive, render
from shiny.express import ui
from shinywidgets import render_maplibre

EARTHQUAKES = requests.get(
    "https://maplibre.org/maplibre-gl-js/docs/assets/earthquakes.geojson"
).json()
TOP10 = (
    pd.DataFrame(
        {
            "mag": [f["properties"]["mag"] for f in EARTHQUAKES["features"]],
            "lng": [f["geometry"]["coordinates"][0] for f in EARTHQUAKES["features"]],
            "lat": [f["geometry"]["coordinates"][1] for f in EARTHQUAKES["features"]],
        }
    )
    .nlargest(10, "mag")
    .reset_index(drop=True)
)

ui.page_opts(fillable=True)

with ui.layout_columns(col_widths=[5, 7]):
    with ui.card():
        ui.card_header("10 strongest earthquakes")

        @render.data_frame
        def table():
            return render.DataGrid(TOP10[["mag"]], selection_mode="row")

    with ui.card(full_screen=True):

        @render_maplibre
        def quakes():
            return Map(MapOptions(style=Carto.DARK_MATTER, center=(0, 20), zoom=1.2))


@reactive.effect
def _fly_to():
    rows = table.cell_selection()["rows"]
    if not rows:
        return
    row = TOP10.iloc[rows[0]]
    quakes.widget.add_call("flyTo", {"center": [row["lng"], row["lat"]], "zoom": 5})

Accessor reference

accessor returns before any interaction across re-render default rate policy
view_state() {center, zoom, bounds, bearing, pitch} cancels (req(False)) until the browser’s first report kept until the new map reports, then re-seeded none
clicked() {lng, lat} of the last click None kept until the user clicks the new map none
drawn_features() list of drawn GeoJSON features [] re-seeded to the new map’s own (empty) set none

The remaining MapboxDraw event traits have no accessor; read them with .read() (see the reacting to widgets article for how .read() reaches a bare trait):

Trait Returns Fires when
draw_features_selected list of selected GeoJSON features MapboxDraw draw.selectionchange
draw_features_created / _updated / _deleted list of GeoJSON features the matching MapboxDraw event

view_state()

Gives the center, zoom, bounds, bearing, and pitch together, updated on every drag, scroll-zoom, and click:

import json

from maplibre import Map, MapOptions
from maplibre.basemaps import Carto
from shiny.express import render, ui
from shinywidgets import render_maplibre

ui.page_opts(fillable=True)

with ui.layout_columns(col_widths=[7, 5]):
    with ui.card(full_screen=True):

        @render_maplibre
        def city():
            return Map(MapOptions(style=Carto.DARK_MATTER, center=(2.3522, 48.8566), zoom=11))

    with ui.card():
        ui.card_header("Map state (accessors)")

        @render.code
        def state():
            vs = city.view_state()
            clicked = city.clicked()
            return (
                f"view_state:\n{json.dumps(vs, indent=2)}\n\n"
                f"clicked:\n{json.dumps(clicked) if clicked else '(nothing clicked yet)'}"
            )

view_state()["bounds"] gives the visible viewport as {_sw: {lng, lat}, _ne: {lng, lat}} (note the underscores – that’s MapLibre GL JS’s own LngLatBounds field naming). clicked() is the same bare lng/lat described under Click for feature detail above.

Tuning accessors

Rate limiting

Every render_* decorator accepts rate_policy ("debounce" or "throttle") and rate_delay (seconds), which rate-limit reactive_read() on that output’s widget. They don’t apply to the view_state() accessor, which fires once per gesture rather than continuously, and .read("view_state") resolves to the accessor, so it isn’t rate-limited either. To debounce view-state reads, call reactive_read(map.widget, "view_state") instead – reach for this when rapid programmatic camera moves would otherwise invalidate a reactive context faster than you need.

The example below counts how many times an effect depending on view_state runs, with and without a debounce, while the same burst of rapid view changes is applied to both maps:

from maplibre import Map, MapOptions
from maplibre.basemaps import Carto
from shiny import reactive
from shiny.express import render, ui
from shinywidgets import reactive_read, render_maplibre

ui.page_opts(fillable=True)

with ui.layout_columns():
    with ui.card():
        ui.card_header("Default: every view_state change")

        @render_maplibre
        def fast():
            return Map(MapOptions(style=Carto.DARK_MATTER, center=(2.3522, 48.8566), zoom=11))

        @render.text
        def fast_count():
            return f"{n_fast.get()} reads"

    with ui.card():
        ui.card_header("rate_delay=1 (debounced)")

        @render_maplibre(rate_policy="debounce", rate_delay=1)
        def slow():
            return Map(MapOptions(style=Carto.DARK_MATTER, center=(2.3522, 48.8566), zoom=11))

        @render.text
        def slow_count():
            return f"{n_slow.get()} reads"


n_fast = reactive.value(0)
n_slow = reactive.value(0)


@reactive.effect
def _count_fast():
    reactive_read(fast.widget, "view_state")
    # isolate(): reading n_fast here must not make this effect depend on
    # itself -- that would make .set() below re-trigger it forever
    with reactive.isolate():
        n_fast.set(n_fast.get() + 1)


@reactive.effect
def _count_slow():
    reactive_read(slow.widget, "view_state")
    with reactive.isolate():
        n_slow.set(n_slow.get() + 1)

The default map’s counter climbs with every change; the debounced map collapses the whole burst into a couple of publishes. Reach for rate_delay when a view_state-driven computation (a viewport filter, a network request) is too expensive to run on every report.

Large data

MapLibre’s basemap is already “only send what’s visible”: vector- and raster-tile sources page in only the tiles the current viewport needs, however large the source data is. For your own point or polygon data at scale, add_deck_layers() hands rendering to deck.gl’s WebGL pipeline instead – the GPU-in-browser approach. The hexagon-bin showcase above renders UK road accidents this way: it pans, zooms, and restyles smoothly, and restyling never re-sends the underlying point data. GeoJSON sources added directly, not through deck.gl, have no large-data mode of their own and ship the whole feature collection to the browser once, the same as ipyleaflet. See the Large data & performance article for how these approaches compare.

Layout and sizing

A map fills its card by default, including following it into and out of full_screen. Give the renderer an explicit height – @render_maplibre(height="250px"), or output_widget("id", height="250px") in core Shiny – and it keeps that height instead of growing. Both paths are exercised in examples/17_layout_sizing.py:

layout sizing

This matches MapWidget(height=...) semantics too: an explicit widget height is respected inside a filling card, and the default is treated as unset so the map still fills.

Gotchas

  • m.set_projection() with no argument leaves the map showing only its basemap. Always pass a string: "vertical-perspective" for the globe, "mercator" for flat.
  • Hover is client-only: add_tooltip() works entirely in the browser, with no hovered trait to read in Python.
  • add_popup()/add_tooltip() show property values as raw HTML unless you pass a template=, which escapes them. Use template= if properties can contain user-supplied text.
  • Assigning traits after render does nothing: widget.map_options = ... or widget.height = ... once the map has rendered has no effect. Use .widget methods for anything after that.
  • Shapes drawn with MapboxDraw show their fill but not their outline.

Learn more