Skip to content

MapLibre for Python

MapLibre for Python provides Python bindings for MapLibre GL JS.

It integrates seamlessly into Shiny for Python and Jupyter.

Installation

# Stable
pip install maplibre

pip install "maplibre[all]"

# Dev
pip install git+https://github.com/eodaGmbH/py-maplibregl@dev

Basic usage

Standalone

import webbrowser

from maplibre import Layer, LayerType, Map, MapOptions
from maplibre.sources import GeoJSONSource

vancouver_blocks = GeoJSONSource(
    data="https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/geojson/vancouver-blocks.json",
)

map_options = MapOptions(
    center=(-123.1256, 49.24658),
    zoom=12,
    hash=True,
    pitch=35,
)

m = Map(map_options)
m.add_layer(
    Layer(
        type=LayerType.LINE,
        source=vancouver_blocks,
        paint={"line-color": "white"},
    )
)

temp_file = "/tmp/pymaplibregl.html"

with open(temp_file, "w") as f:
    f.write(m.to_html(style="height: 800px;"))

webbrowser.open(temp_file)

Shiny integration

from maplibre import Map, MapContext, output_maplibregl, render_maplibregl
from maplibre.controls import Marker
from shiny import App, reactive, ui

app_ui = ui.page_fluid(
    output_maplibregl("maplibre", height=600),
    ui.div("Click on map to set a marker"),
)


def server(input, output, session):
    @render_maplibregl
    def maplibre():
        m = Map()
        return m

    @reactive.Effect
    @reactive.event(input.maplibre)
    async def coords():
        async with MapContext("maplibre") as m:
            print(input.maplibre())
            lng_lat = tuple(input.maplibre()["coords"].values())
            marker = Marker(lng_lat=lng_lat)
            m.add_marker(marker)
            m.add_call("flyTo", {"center": lng_lat})


app = App(app_ui, server)

if __name__ == "__main__":
    app.run()

Jupyter widget

from maplibre.ipywidget import MapWidget as Map

m = Map()
m