GeoLibre

Embed the full GeoLibre desktop-GIS app in a Shiny output, drive it from Python, and read its live state back.

GeoLibre is a full GIS application built on MapLibre: a layer panel, styling tools, drawing and measuring, search, and a basemap gallery. @render_geolibre embeds it in your app, and every layer you add from Python appears in its layer panel.

hero

A population-density dashboard: choropleth, table, chart, and PNG export, all from one GeoLibre map. Try the app.

Installation

pip install 'shinywidgets[geolibre]'

This pulls in geolibre>=3.6.0, the version floor with *_async() command-method variants, and requires Python 3.11 or later.

Quick start

from __future__ import annotations

from geolibre import Map
from shiny.express import ui

from shinywidgets import render_geolibre

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

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

with ui.card(full_screen=True):
    ui.card_header("The full GeoLibre app, as a Shiny output")

    @render_geolibre
    def map():
        m = Map(center=(-98.5, 39.8), zoom=4)
        m.add_geojson(US_STATES, name="US States", fillColor="#2a6fdb", fillOpacity=0.25)
        return m

quickstart

One add_geojson() call gives you the map and a layer panel entry with a visibility toggle, an opacity slider, a style editor, and a delete button – all of GeoLibre’s, none of yours.

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 geolibre.Map capability – nothing Shiny-specific yet; render_geolibre just embeds the app and keeps it synced.

Real layer types

Map has dozens of add_* methods for vector data (add_geojson(), add_vector(), add_gdf(), add_csv(), …), rasters (add_cog(), add_raster()), and point data (add_markers(), add_circle_markers(), add_heatmap(), add_choropleth(), …). Each adds its own entry to the layer panel, so a polygon layer and a point layer coexist with independent styling.

    @render_geolibre
    def map():
        m = Map(center=(-98.5, 39.8), zoom=3.5)
        m.add_geojson(US_STATES, name="US States", fillColor="#cbd5e0", fillOpacity=0.25)
        m.add_circle_markers(
            [(lng, lat) for _, lng, lat, _ in CITIES],
            name="Largest cities",
            radius=10,
            fillColor="#e3342f",
        )
        return m

vector and point layers

Styling and popups

layer.opacity = ... and layer.set_style(**paint_overrides) restyle a layer in place. set_popup() picks which fields show in a layer’s click popup, with per-field labels, number formatting, and more; set_identify() arms the Identify tool so a plain click opens that popup (normally a user turns this on from the Layers panel).

examples/03_styling_and_popups.pyexcerpt · 17 of 46 lines
    @render_geolibre
    def map():
        m = Map(center=(-98.5, 39.8), zoom=4)
        layer_id = m.add_choropleth(US_STATES, column="density", name="Population density")
        layer = m.get_layer(layer_id)
        # A click opens a popup with just these two fields, titled by name
        m.set_popup(
            layer,
            [
                {"field": "name", "label": "State"},
                {"field": "density", "label": "Density", "kind": "number", "decimals": 1},
            ],
            title="name",
            show_feature_id=False,
        )
        m.set_identify(layer)  # arm Identify so a click opens the popup
        return m

Export as an image

to_image() renders the current view to a PNG and returns the bytes. Its to_image_async() variant awaits the reply directly, which works here because a @render.download_button handler runs outside Shiny’s reactive flush.

examples/04_snapshot_export.pyexcerpt · 7 of 34 lines
        # to_image_async() awaits the app's reply, so it runs directly on
        # Shiny's event loop -- a download handler isn't part of the
        # reactive flush, so (unlike a reactive.effect) awaiting it here
        # doesn't block the reply from being delivered.
        @render.download_button(filename="map.png", label="Download PNG")
        async def snapshot():
            yield await map.widget.to_image_async()

snapshot export

Built-in toolset

add_legend() and show_control() reach into the app’s own Controls menu – bookmarks, search, a minimap, and the Measure panel (distance, area, and circle tools, with configurable units) – all built, styled, and already wired to the map.

examples/05_toolset_and_legend.pyexcerpt · 12 of 32 lines
    @render_geolibre
    def map():
        m = Map(center=(-98.5, 39.8), zoom=3.5)
        m.add_circle_markers(
            [(lng, lat) for _, lng, lat in CITIES],
            name="Major cities",
            radius=10,
            fillColor="#e3342f",
        )
        m.add_legend("Cities", legend_dict={"Population > 1M": "#e3342f"})
        m.show_control("measure", collapsed=False, distance_unit="miles")
        return m

toolset and legend

Reacting to interaction

GeoLibre has no reactive accessors – no map.clicked() method you call from a render function. Instead, event callbacks (on_click(), on_selection_change(), on_layer_change()) register a plain Python callback, called with an event dict whenever the user clicks the map, changes the selected feature, or adds/removes a layer. Register them inside the render function (they need the freshly created widget) and have the callback set a reactive.value, exactly like wiring up an ipywidgets trait observer.

Click for details

With set_identify() armed, a map click’s event dict carries a "features" list with each clicked feature’s properties and geometry – not just the lngLat you’d get otherwise – which is enough to build a detail card with no extra round trip.

examples/06_events_and_detail_card.pyexcerpt · 19 of 42 lines
        @render_geolibre
        def map():
            m = Map(center=(-98.5, 39.8), zoom=4)
            layer_id = m.add_choropleth(US_STATES, column="density", name="Population density")
            m.set_identify(layer_id)  # include feature properties in click events
            m.on_click(lambda e: last_click.set(e))
            return m

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

        @render.ui
        def detail():
            event = req(last_click())
            features = event.get("features") or []
            if not features:
                return core_ui.value_box("No state here", "click land to select one")
            props = features[0]["properties"]
            return core_ui.value_box(props["name"], f"{props['density']:.1f} people/sq mi")

on_click()’s event is {"lngLat": [lng, lat], "features": [...]} – features is only present (and only populated) for layers Identify is armed on; it’s [] for a click that misses every identifiable layer, never None. There’s no built-in rate limit on these callbacks: a reactive.value set from one fires the consuming output on every call.

Updating in place

GeoLibre’s API splits into two kinds of methods, and only one of them is safe to call directly from a Shiny reactive context. Project mutations – add_geojson()/add_vector()/add_cog()/etc., set_center()/set_zoom()/fit_project_bounds(), and layer styling (layer.opacity = ..., layer.set_style()) – edit the map’s synced project document and sync to the browser on the next flush: call them from a @reactive.effect like any other trait write. Command methods – fly_to(), fit_bounds(), zoom_to_layer(), identify(), get_center()/get_view()/get_bounds(), get_selected_features()/get_drawn_features(), run_algorithm(), and to_image() – send a command to the running app and wait for its reply; calling one directly inside a render function, reactive.calc, or reactive.effect would block the very event loop that must deliver that reply, so GeoLibre raises instead of hanging. Every one of these has an async *_async() counterpart that awaits the reply instead, which runs directly on Shiny’s event loop – but only from inside a reactive.extended_task; awaiting it from a plain reactive.effect hits the same deadlock, because the reply can’t be delivered until that effect finishes running. Where a project-mutation alternative exists – set_center() for fly_to(), fit_project_bounds() for fit_bounds(), the synced project trait for the query methods – it’s the cheaper, simpler option; reach for the extended_task + *_async() pattern for the methods that have none.

Camera from a dropdown

examples/08_driving_from_inputs.pyexcerpt · 6 of 32 lines
# set_center() mutates the project trait and syncs to the browser -- no
# re-render, so zoom, added layers, and styling are untouched.
@reactive.effect
def _():
    lng, lat = CITIES[input.city()]
    map.widget.set_center(lng, lat, zoom=9)

Flying with an extended task

An extended_task also can’t read reactive sources itself (input.x() inside its body raises) – read what you need before calling .invoke(), and pass it as an argument. fly_to()/fly_to_async() acknowledge at animation start, not animation end, so a get_center() issued right after can report a mid-flight position: pass an explicit duration and wait roughly that long before querying the camera.

examples/09_fly_to_async.pyexcerpt · 17 of 58 lines
# fly_to_async() awaits the app's reply instead of blocking a thread for it,
# so it runs directly on Shiny's event loop -- but only from inside an
# extended_task: awaiting it from a plain reactive.effect deadlocks, because
# the reply can't be delivered until that effect finishes. An extended_task
# can't read reactive sources itself (input.city() would raise) -- read it
# before invoking, and pass it in as an argument.
@extended_task
async def fly_to_city(lng: float, lat: float):
    await map.widget.fly_to_async(lng, lat, zoom=9, duration=800)
    await asyncio.sleep(1)  # let the animation finish before querying the camera
    return await map.widget.get_center_async()


@reactive.effect
@reactive.event(input.fly)
def _():
    fly_to_city.invoke(*CITIES[input.city()])

Camera from a table

A plain @render.data_frame row selection (table.cell_selection()["rows"]) is a clean source for set_center() – no GeoLibre-side accessor needed.

examples/11_table_to_map.pyexcerpt · 7 of 44 lines
@reactive.effect
def _():
    rows = table.cell_selection()["rows"]
    if not rows:
        return
    row = CITIES.iloc[rows[0]]
    map.widget.set_center(row["lng"], row["lat"], zoom=9)

Reading widget state

Event callbacks (above) handle clicks and selections. For everything else, map.read("project") gives you GeoLibre’s whole live document: the current view (project["mapView"]: center, zoom, bearing, pitch, and – once the browser’s first state sync has landed – bbox), every layer’s name and style, basemap settings, and more.

Trait Contents Notes
project The whole live document: view, layers, styling, basemap Invalidates on every pan and zoom
project["mapView"] center, zoom, bearing, pitch, bbox bbox is absent until the first browser sync lands – read it with .get()
project["layers"] Each layer’s name and style

The project trait

examples/07_reading_project_state.pyexcerpt · 19 of 48 lines
        @render.code
        def view_info():
            # Invalidates on every pan and zoom -- the whole project re-syncs,
            # not just the view, so keep downstream consumers cheap (see
            # "Rate limiting" below). "bbox" is filled in once the browser's
            # first sync lands (a moment after the app boots), so treat it as
            # optional rather than indexing it directly.
            project = map.read("project")
            view = project["mapView"]
            bbox = view.get("bbox")
            return json.dumps(
                {
                    "center": [round(c, 2) for c in view["center"]],
                    "zoom": round(view["zoom"], 2),
                    "bbox": [round(b, 2) for b in bbox] if bbox else None,
                    "layers": [layer["name"] for layer in project["layers"]],
                },
                indent=2,
            )

On the very first render, before the browser has echoed anything back, project["mapView"] has center/zoom/bearing/pitch but not yet bbox – read it with .get(), or req() it, rather than indexing it directly.

Viewport drives a chart

project["mapView"]["bbox"] is [west, south, east, north] for the current viewport. Filter any lng/lat-indexed data against it in a downstream @render.plot (or any other output) to show exactly what’s on screen.

examples/10_viewport_to_chart.pyexcerpt · 18 of 51 lines
        @render.plot
        def visible_cities():
            # "bbox" fills in once the browser's first sync lands, a moment
            # after the app boots -- req() cancels the output until then.
            bbox = map.read("project")["mapView"].get("bbox")
            west, south, east, north = req(bbox)
            shown = [
                (name, pop)
                for name, lng, lat, pop in CITIES
                if west <= lng <= east and south <= lat <= north
            ]
            fig = Figure(figsize=(5, 4), layout="tight")
            ax = fig.subplots()
            if shown:
                names, pops = zip(*sorted(shown, key=lambda c: c[1]))
                ax.barh(names, pops, color="#2a6fdb")
            ax.set_xlabel("Population (millions)")
            return fig

Rate limiting

There’s no rate_policy/rate_delay on render_geolibre (those only exist on renderers that declare accessors). map.read("project") is unthrottled, and because it invalidates on every pan/zoom frame-ish event with the entire project payload, a consumer that does real work – a chart recompute, a database query – can fall behind during a drag. Prefer the event callbacks for high-frequency interactions, and if you must react to project continuously, debounce it yourself (a small reactive.poll() or a manual timer) rather than assuming GeoLibre throttles it for you.

Large data

GeoLibre’s basemaps are MapLibre vector tiles, so they’re already “only send what’s visible.” But layers you add from Python (add_geojson() and friends) ship the whole feature collection to the browser once, the same as ipyleaflet – there’s no large-data mode specific to GeoLibre’s own layer API. add_cog()/add_raster() of a file on the server’s disk works deployed too: shinywidgets proxies GeoLibre’s loopback server, so these layers load the same way locally and on shinyapps.io/Posit Connect; basemap tiles and remote data URLs still need internet access from the browser, not the server. For a point cloud of millions, use lonboard (GPU-rendered); for code-driven deck.gl layers on a MapLibre basemap without the full GIS-app overhead, use maplibre directly. See the Large data & performance article for how these approaches fit together.

Layout and sizing

The embedded app reads its height trait once, when it loads, to size its <iframe> – changing map.widget.height after rendering does nothing (resize the output’s container instead). GeoLibre’s own default is "800px", which render_geolibre treats as “unset”: in a filling layout the map fills its container; give the Map an explicit height (e.g., Map(height="500px")) to opt out of filling, or size the output with render_geolibre(height=...) to fill a fixed-size container with a still-default-height map.

from __future__ import annotations

from geolibre import Map
from shiny.express import ui

from shinywidgets import render_geolibre

ui.page_opts(title="Layout and sizing", fillable=True)

with ui.layout_columns(col_widths=[4, 4, 4]):
    with ui.card(full_screen=True):
        ui.card_header("Default: fills the card")

        @render_geolibre
        def fills():
            return Map(center=(-98.5, 39.8), zoom=3)

    with ui.card(full_screen=True):
        ui.card_header('Map(height="300px"): opts out of filling')

        @render_geolibre
        def fixed():
            return Map(center=(-98.5, 39.8), zoom=3, height="300px")

    with ui.card(full_screen=True):
        ui.card_header('render_geolibre(height="250px"): sizes a default-height map')

        @render_geolibre(height="250px")
        def sized():
            return Map(center=(-98.5, 39.8), zoom=3)

layout and sizing

All three behave as documented: the default map fills the card, height="300px" holds to that fixed size, and render_geolibre(height="250px") sizes the output to that height with a still-default-height map.

Gotchas

  • Blocking command methods (fly_to(), get_center(), to_image(), and the rest) raise immediately if called from a render function, reactive.calc, or any reactive.effect. Their *_async() variants can run directly on the event loop, but only from inside a reactive.extended_task; awaiting one from a plain reactive.effect deadlocks the same way.
  • extended_task can’t read reactive sources from inside its own body: input.x() inside an @extended_task async def raises "You're not allowed to read reactive sources from inside a Extended Task". Read the value before calling .invoke() and pass it as an argument.
  • project["mapView"] has no "bbox" for a moment after the app starts. Read it with .get("bbox") and a req().
  • fly_to() returns when the flight starts, so an immediate get_center() can report a mid-flight position. Pass a duration and wait that long before reading the camera.

Learn more