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/eoda-dev/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_map", height=600),
ui.div("Click on map to set a marker"),
)
def server(input, output, session):
@render_maplibregl
def maplibre_map():
return Map()
@reactive.Effect
@reactive.event(input.maplibre_map_clicked)
async def coords():
async with MapContext("maplibre_map") as m:
input_value = input.maplibre_map_clicked()
print(input_value)
lng_lat = tuple(input_value["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()