ipyleaflet

A fully interactive Leaflet map in Shiny – draw shapes, click features, and drag markers, all wired back to Python.

ipyleaflet brings Leaflet to Python: basemaps, markers and clustering, GeoJSON and choropleths, drawing tools, split-screen comparison, and more. With @render_ipyleaflet, the map is also a reactive input: pans, zooms, clicks, and drawn shapes come back to your app as ordinary Shiny values.

hero

Draw a shape to filter and highlight the carshare pods inside it. Try the app.

Installation

pip install 'shinywidgets[ipyleaflet]'

Quick start

import ipywidgets
import ipyleaflet as L
from shiny.express import ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="ipyleaflet quickstart", fillable=True)

with ui.card():

    @render_ipyleaflet
    def map():
        m = L.Map(center=(40.73, -73.99), zoom=15)
        marker = L.Marker(location=(40.735, -73.991))
        marker.popup = ipywidgets.HTML("<b>Union Square</b><br>14th St &amp; Broadway")
        m.add(marker)
        return m

quickstart

A map is just an ipyleaflet.Map with layers added to it – here a marker with a popup. Return any ipyleaflet.Map (or subclass) and it fills its output; no height settings needed.

Overview

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

ipyleaflet’s own layer API – basemaps, marker clustering, GeoJSON choropleths, split-screen comparison – works the same as it does in Jupyter; see the ipyleaflet documentation for the full catalog of layers and controls.

Reacting to interaction

Every @render_ipyleaflet output has methods, called accessors, that report what the user did: map.clicked(), map.drawn_features(), and more. Call one from any reactive context, the same way you’d call input.my_slider(), and that context re-runs whenever the user does it again.

Click for the nearest pod

clicked() plus a one-line distance calculation gives a “nearest neighbor” detail card – useful any time a dataset has too many points to label individually:

import plotly.express as px
import ipyleaflet as L
from shiny.express import render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Click for the nearest pod", fillable=True)

# plotly's carshare dataset: 249 real car2go pod locations around Montreal
pods = px.data.carshare()

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

        @render_ipyleaflet
        def map():
            m = L.Map(center=(45.52, -73.59), zoom=11)
            markers = [L.Marker(location=(r.centroid_lat, r.centroid_lon)) for r in pods.itertuples()]
            m.add(L.MarkerCluster(markers=markers))
            return m

    with ui.card():
        ui.card_header("Nearest pod to your last click")

        @render.ui
        def nearest():
            c = map.clicked()
            if c is None:
                return "Click the map."
            lat, lng = c["coordinates"]
            d2 = (pods["centroid_lat"] - lat) ** 2 + (pods["centroid_lon"] - lng) ** 2
            row = pods.loc[d2.idxmin()]
            return ui.div(ui.h5(f"Pod #{row.name}"), f"{row['car_hours']:.0f} car-hours")

Draw a shape to filter a table

drawn_features() returns GeoJSON; a few lines of shapely turn that into a spatial filter over any point dataset:

import ipyleaflet as L
import plotly.express as px
from shapely.geometry import Point, shape
from shiny.express import render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Draw a shape, filter the table", fillable=True)

# plotly's carshare dataset: 249 real car2go pod locations around Montreal
pods = px.data.carshare()

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

        @render_ipyleaflet
        def map():
            m = L.Map(center=(45.52, -73.59), zoom=11)
            # rectangle={}: an empty dict disables the tool; give it a
            # (possibly empty) shapeOptions to enable it, like the other tools
            m.add(
                L.DrawControl(
                    polygon={"shapeOptions": {"color": "#2a7fff"}},
                    rectangle={"shapeOptions": {}},
                )
            )
            return m

    with ui.card(full_screen=True):
        ui.card_header("Pods inside the drawn shape(s)")

        @render.data_frame
        def inside():
            feats = map.drawn_features()  # [] until something is drawn
            if not feats:
                return pods.iloc[0:0]
            polys = [shape(f["geometry"]) for f in feats]
            mask = [
                any(poly.contains(Point(lon, lat)) for poly in polys)
                for lat, lon in zip(pods["centroid_lat"], pods["centroid_lon"])
            ]
            return render.DataGrid(pods[mask].reset_index(drop=True))

Updating in place

To toggle a layer, restyle it, or swap a basemap, change map.widget’s layers and traits from a @reactive.effect instead of re-rendering: the map keeps its pan, zoom, and any shapes the user has drawn. This example toggles a layer’s visibility, restyles it, and swaps the basemap, all in place:

import ipyleaflet as L
from shiny import reactive
from shiny.express import input, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="In-place layer updates", fillable=True)

OUTLINE = {
    "type": "Feature",
    "properties": {},
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [[-74.00, 40.72], [-73.98, 40.72], [-73.98, 40.74], [-74.00, 40.74], [-74.00, 40.72]]
        ],
    },
}

with ui.sidebar():
    ui.input_checkbox("show_outline", "Show outline", True)
    ui.input_radio_buttons("color", "Outline color", ["blue", "red", "green"])
    ui.input_checkbox("satellite", "Satellite basemap", False)

with ui.card():

    @render_ipyleaflet
    def map():
        m = L.Map(center=(40.73, -73.99), zoom=13)
        m.add(L.GeoJSON(data=OUTLINE, style={"color": "blue", "fillOpacity": 0.1}, name="outline"))
        return m


def outline():
    return next(lyr for lyr in map.widget.layers if lyr.name == "outline")


# Each effect mutates a trait on the already-rendered map, so the browser
# patches the one layer that changed instead of rebuilding the whole map --
# the pan/zoom the user has done is never disturbed.
@reactive.effect
def _toggle_outline():
    outline().visible = input.show_outline()


@reactive.effect
def _restyle_outline():
    outline().style = {**outline().style, "color": input.color()}


@reactive.effect
def _swap_basemap():
    m = map.widget
    old = next(lyr for lyr in m.layers if lyr.base)
    basemap = L.basemaps.Esri.WorldImagery if input.satellite() else L.basemaps.OpenStreetMap.Mapnik
    new = L.basemap_to_tiles(basemap)
    new.base = True
    m.substitute(old, new)

basemap_to_tiles() doesn’t set base=True on its result. Set new.base = True on the replacement, as the example does, or the next swap won’t find the current basemap and the session ends with an error.

Toggling visible is cheap, but restyling a GeoJSON layer re-sends all of its features. For frequent style changes on a large GeoJSON layer, re-rendering costs about the same. Re-render, too, when the layers themselves change (a new dataset, a different set of markers); see Updating in place for the general pattern.

Linking widgets

Put the camera and clicks together and one map can drive another output.

Viewport drives a chart

bounds() makes “what’s on screen” a reactive value. Pairing it with a @render_plotly chart gives a live summary of the visible points as the user pans and zooms:

import pandas as pd
import plotly.express as px
import ipyleaflet as L
from shiny.express import ui
from shinywidgets import render_ipyleaflet, render_plotly

ui.page_opts(title="What's in view", fillable=True)

# plotly's carshare dataset: 249 real car2go pod locations around Montreal,
# labeled with when each pod sees its heaviest use
pods = px.data.carshare()
pods["period"] = pd.cut(
    pods["peak_hour"], bins=[-1, 5, 11, 17, 23], labels=["night", "morning", "afternoon", "evening"]
)

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

        @render_ipyleaflet
        def map():
            m = L.Map(center=(45.52, -73.59), zoom=11)
            markers = [L.Marker(location=(r.centroid_lat, r.centroid_lon)) for r in pods.itertuples()]
            m.add(L.MarkerCluster(markers=markers))
            return m

    with ui.card():
        ui.card_header("Pods in the current viewport, by peak period")

        @render_plotly
        def in_view():
            (south, west), (north, east) = map.bounds()  # pairs with: plotly
            visible = pods[pods.centroid_lat.between(south, north) & pods.centroid_lon.between(west, east)]
            counts = visible["period"].value_counts().reindex(["night", "morning", "afternoon", "evening"]).reset_index()
            counts.columns = ["period", "count"]
            return px.bar(counts, x="period", y="count")

One map drives another

A second, smaller “overview” map stays synced to a detail map’s camera – a classic locator-map pattern. Reading center()/bounds() on the detail map and assigning to the overview’s own trait is enough; there’s no feedback loop because setting a trait to the value it already holds doesn’t re-publish:

import ipyleaflet as L
from shiny import reactive
from shiny.express import ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Overview map stays in sync", fillable=True)

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

        @render_ipyleaflet
        def main():
            return L.Map(center=(40.73, -73.99), zoom=14)

    with ui.card():

        @render_ipyleaflet
        def overview():
            m = L.Map(center=(40.73, -73.99), zoom=10)
            m.add(L.Rectangle(bounds=((40.72, -74.0), (40.74, -73.98)), name="extent"))
            return m


# The overview map never re-renders: panning or zooming the main map just
# moves its center and resizes its rectangle, so the overview keeps its own
# zoom level and any layers a user added to it.
@reactive.effect
def _sync_overview_center():
    overview.widget.center = main.center()


@reactive.effect
def _sync_extent_rectangle():
    extent = next(lyr for lyr in overview.widget.layers if lyr.name == "extent")
    extent.bounds = main.bounds()

The overview’s center and its extent rectangle both follow the main map, while the overview keeps its own, more zoomed-out, view.

Accessor reference

Accessor Returns Before any interaction Across a re-render Default rate policy
bounds() ((south, west), (north, east)), [lat, lng] order Cancels (like an unrendered output) until the browser’s first report Re-seeded; cancels again until the new map reports none
zoom() float Seeded (the map’s own .zoom) Re-seeded from the new map none
center() [lat, lng] Seeded (the map’s own .center) Re-seeded from the new map none
clicked() dict with coordinates: [lat, lng] (and other native on_interaction kwargs) None until the first click Kept until the user clicks the new map none
drawn_features() List[dict] of GeoJSON Features [] until something is drawn Re-seeded ([] for a fresh DrawControl) none

None of the five declares a default rate limit – see Rate limiting for why, and for when you’d add one yourself. Coordinates throughout are [lat, lng], as ipyleaflet reports them; lonboard and maplibre are (lng, lat).

bounds(), zoom(), center()

These three track the map’s viewport. Until the map first reports its viewport, reading bounds() cancels quietly, like an output that hasn’t rendered yet, so no req() guard is needed. This example also shows two-way sync: a slider sets .zoom on the widget, and zoom() (which also fires on that Python-side set) mirrors it back, without a feedback loop – update_slider() to a value the slider already holds doesn’t re-fire the input:

import ipyleaflet as L
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Camera accessors", fillable=True)

with ui.sidebar():
    ui.input_slider("zoom", "Zoom", value=12, min=4, max=18)

with ui.card():

    @render_ipyleaflet
    def map():
        return L.Map(center=(40.73, -73.99), zoom=12)


@reactive.effect
def _slider_to_map():
    map.widget.zoom = input.zoom()


@reactive.effect
def _map_to_slider():
    # zoom() also fires when Python sets .zoom (the line above), but the
    # slider ignores an update to the value it already holds, so this
    # doesn't loop
    ui.update_slider("zoom", value=map.zoom())


with ui.card(fill=False):

    @render.code
    def status():
        b = map.bounds()  # cancels (no output) until the browser first reports it
        return (
            f"zoom:   {map.zoom()}\n"
            f"center: {[round(c, 3) for c in map.center()]}\n"
            f"bounds: south={b[0][0]:.3f} west={b[0][1]:.3f} "
            f"north={b[1][0]:.3f} east={b[1][1]:.3f}"
        )

camera state

clicked()

import ipyleaflet as L
from shiny.express import render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Map clicks", fillable=True)

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

        @render_ipyleaflet
        def map():
            return L.Map(center=(40.73, -73.99), zoom=13)

    with ui.card():
        ui.card_header("map.clicked()")

        @render.code
        def click():
            c = map.clicked()
            if c is None:
                return "Click the map to see its coordinates."
            lat, lng = c["coordinates"]
            return f"lat={lat:.4f}\nlng={lng:.4f}"

A double-click updates clicked() once. Clicks on markers don’t reach clicked(); use the layer’s own on_click (e.g. GeoJSON.on_click) for those.

drawn_features()

ipyleaflet.DrawControl adds a toolbar for drawing polygons, rectangles, circles, and markers directly on the map:

import ipyleaflet as L
from shiny.express import render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Draw on the map", fillable=True)

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

        @render_ipyleaflet
        def map():
            m = L.Map(center=(40.73, -73.99), zoom=13)
            m.add(L.DrawControl(polygon={"shapeOptions": {"color": "#2a7fff"}}))
            return m

    with ui.card():
        ui.card_header("map.drawn_features()")

        @render.code
        def features():
            feats = map.drawn_features()
            kinds = [f["geometry"]["type"] for f in feats]
            return f"{len(feats)} shape(s)\n" + "\n".join(kinds)

drawn_features() returns [] until something is drawn, then a list of GeoJSON Feature dicts that updates as shapes are added, edited, or deleted. If the map has no ipyleaflet.DrawControl, reading it raises TypeError (add one with m.add(DrawControl())).

Across re-renders

bounds(), zoom(), center(), and drawn_features() describe the map, so a re-render resets them from the new map: zoom() and center() take its initial view, bounds() cancels until the new map reports, and drawn_features() is [] again. clicked() describes what the user did, so it keeps the last click until the user clicks the new map.

Tuning accessors

Reading on demand

A button, download handler, or chat tool can read any accessor when it runs, even if nothing else in the app reads it. This “Save view” button captures the camera and drawn shapes only when clicked:

import ipyleaflet as L
from shiny import reactive
from shiny.express import input, render, ui
from shinywidgets import render_ipyleaflet

ui.page_opts(title="Save the current view on demand", fillable=True)

# Every accessor attaches when the map renders, so nothing needs to keep
# reading bounds()/drawn_features() for this button's reads to see the
# user's latest pan or shape -- they're there the moment the button is
# clicked, with no warm-up read required first.
saved = reactive.value([])

with ui.layout_columns(col_widths=[8, 4]):
    with ui.card():
        ui.input_action_button("save", "Save current view", class_="mb-2")

        @render_ipyleaflet
        def map():
            m = L.Map(center=(40.73, -73.99), zoom=13)
            m.add(L.DrawControl(polygon={"shapeOptions": {"color": "#2a7fff"}}))
            return m

    with ui.card():
        ui.card_header("Saved views")

        @render.ui
        def views():
            if not saved():
                return "Pan the map, maybe draw a shape, then click Save."
            items = [
                ui.tags.li(f"center={c} zoom={z:.0f} shapes={n}") for c, z, n in saved()
            ]
            return ui.tags.ol(*items)


@reactive.effect
@reactive.event(input.save)
def _save_view():
    saved.set([*saved(), (map.center(), map.zoom(), len(map.drawn_features()))])

Beyond the accessors: reactive_read()

The accessors cover the map itself. For state on individual layers and controls – a draggable marker’s position, a GeoJSON layer’s hover state, anything not in the accessor table – use reactive_read() on the layer or control itself:

import ipyleaflet as L
from shiny import req
from shiny.express import render, ui
from shinywidgets import reactive_read, render_ipyleaflet

ui.page_opts(title="Draggable marker (reactive_read)", fillable=True)

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

        @render_ipyleaflet
        def map():
            m = L.Map(center=(40.73, -73.99), zoom=14)
            m.add(L.Marker(location=(40.73, -73.99), draggable=True, name="me"))
            return m

    with ui.card():
        ui.card_header("Drag the marker")

        @render.code
        def location():
            req(map.widget)
            marker = next(lyr for lyr in map.widget.layers if lyr.name == "me")
            lat, lng = reactive_read(marker, "location")
            return f"lat={lat:.4f}\nlng={lng:.4f}"

A DrawControl’s last_action and last_draw are also useful to read this way, for more detail than drawn_features() gives.

Rate limiting

ipyleaflet’s accessors fire once per gesture (a pan, a click, an edit), so they have no default rate limit. Rate limiting matters for reactive_read() on a trait that streams during a gesture, like a dragged marker’s location:

import ipyleaflet as L
from shiny import reactive, req
from shiny.express import render, ui
from shinywidgets import reactive_read, render_ipyleaflet

ui.page_opts(title="Rate-limited reactive_read", fillable=True)

# ipyleaflet's own accessors (bounds/zoom/center/clicked/drawn_features) only
# ever fire once per gesture, so rate_policy/rate_delay has nothing to smooth
# there. It matters for reactive_read() on a trait that streams many updates
# per gesture, like a dragged marker's "location".
with ui.layout_columns(col_widths=[8, 4]):
    with ui.card():

        @render_ipyleaflet(rate_policy="throttle", rate_delay=0.5)
        def map():
            m = L.Map(center=(40.73, -73.99), zoom=14)
            m.add(L.Marker(location=(40.73, -73.99), draggable=True, name="me"))
            return m

    with ui.card():
        ui.card_header("Drag updates seen by Python (throttled to 2/s)")
        count = reactive.value(0)

        @reactive.effect
        def _count():
            req(map.widget)
            marker = next(lyr for lyr in map.widget.layers if lyr.name == "me")
            reactive_read(marker, "location")
            # isolate(): count() is both read and set here, so without
            # isolating the read this effect would depend on its own output
            # and loop forever instead of running once per throttled update
            with reactive.isolate():
                count.set(count() + 1)

        @render.code
        def n():
            return str(count())

rate limiting

The throttle caps how many times the effect runs during a drag. The reactive.isolate() around count.set(count() + 1) matters: without it the effect depends on its own output and re-runs forever, freezing the session.

.read()

map.read("bounds") reads an accessor by name, the same value as map.bounds(); it’s meant for code that handles outputs generically.

Large data

Every marker and GeoJSON feature is sent to the browser in full, so marker clustering helps only into the low thousands of points. For tens of thousands of points or more, use lonboard, which draws them on the GPU. For large raster files, add them with localtileserver, which sends only the tiles in view, like a basemap. See the Large data & performance article for how these approaches compare in general.

Layout and sizing

  • The map fills its container in a filling layout (card, fillable=True page) unless it has its own height, either via output_widget(height=...) or Layout(height=...) on the Map. A subclass’s own default height (e.g., leafmap’s 600px) is treated as unset – see the leafmap guide for that renderer’s specifics.
  • Use output_widget(height="300px") (or @render_ipyleaflet(height=...) in Express) for a fixed size; "auto" and "fit-content" work too.
  • In a full_screen=True card, the map fills the expanded card.
  • A map in a hidden tab has the right size when the tab is shown.

Gotchas

  • With several base=True layers and a LayersControl, the one added last shows first. Add your default basemap last.
  • CARTO basemaps (CartoDB.Positron, etc.) need an API key and show “API KEY REQUIRED” tiles without one; Esri’s WorldImagery and OpenTopoMap don’t.

Learn more