R or Rust? The same functions and arguments exist in R (verb(m, ...) for Python’s m.verb(...)) and Rust.
basemapper renders MapLibre GL basemaps headlessly with a Rust core: no browser, display server, GPU or GDAL. Vector styles are drawn by a software port of MapLibre GL JS’s renderer, so maps look as they do in MapLibre. Everything on this page was run when the page was built; the maps are the output of the code above them.
Installation
pip install "basemapper @ git+https://github.com/ar-puuk/basemapper@v0.1.1#subdirectory=py-basemapper"
# or: uv add "basemapper @ git+https://github.com/ar-puuk/basemapper@v0.1.1#subdirectory=py-basemapper"
See the home page for conda.
Choose a style
Every function takes a style. The simplest is a named basemap, a leaflet-providers name; list_providers() lists them, with the API key some need:
import basemapper as bm
for p in bm.list_providers()[:12]:
print(f"{p['name']:<24} vector={p['vector']!s:<5} raster={p['raster']!s:<5} key={p['api_key_env']}")
OpenStreetMap.Mapnik vector=False raster=True key=None
OpenStreetMap.DE vector=False raster=True key=None
OpenStreetMap.France vector=False raster=True key=None
OpenStreetMap.HOT vector=False raster=True key=None
OpenTopoMap vector=False raster=True key=None
CyclOSM vector=False raster=True key=None
OpenFreeMap.Liberty vector=True raster=False key=None
OpenFreeMap.Bright vector=True raster=False key=None
OpenFreeMap.Positron vector=True raster=False key=None
OpenFreeMap.Dark vector=True raster=False key=None
OpenFreeMap.Fiord vector=True raster=False key=None
CartoDB.Positron vector=True raster=True key=CARTO_API_KEY
A MapLibre style URL or JSON works too, and so does tile data: a tile URL, TileJSON, PMTiles archive or ArcGIS service (see Your own tiles and services).
A map on its own
basemap() creates a view: a centre and MapLibre zoom (or bounds to fit), and a size in CSS pixels. In a notebook, a view shows the map:
m = bm.basemap("OpenFreeMap.Positron", 720, 405, center=(-111.8887, 40.7556), zoom=12.4)
m
repr() describes it, and the get_*() methods read it:
print(repr(m))
print(m.get_bounds(lonlat=True))
print(m.get_attribution())
<Basemap 1 style, 720 x 405 @ 1x (720 x 405 px), center (-111.88870, 40.75560), zoom 12.400>
(-111.93553419871802, 40.73564121457686, -111.841865801282, 40.77555279531684)
OpenFreeMap © OpenMapTiles Data from OpenStreetMap
set_view() and set_bounds() change the view. Here it fits North Carolina’s counties (a GeoDataFrame, from geodatasets):
import geopandas as gpd
import geodatasets
nc = gpd.read_file(geodatasets.get_path("geoda.sids"))
bm.basemap("OpenFreeMap.Liberty", 720, 300, bounds=nc)
Raster and vector, PNG and SVG
Basemaps come as raster tiles (images, like OpenStreetMap’s) or vector tiles (geometry styled on the fly, like OpenFreeMap’s). Either renders to a PNG with render_png() or an SVG with render_svg(). In an SVG, vector layers are paths and the labels editable text with the style’s fonts embedded; raster tiles are embedded as images.
import os, tempfile
slc = (-111.8910, 40.7608)
raster = bm.basemap("OpenStreetMap.Mapnik", 480, 300, center=slc, zoom=11.5)
vector = bm.basemap("OpenFreeMap.Bright", 480, 300, center=slc, zoom=11.5)
out = tempfile.mkdtemp()
for name, m in [("raster", raster), ("vector", vector)]:
m.render_png(os.path.join(out, f"{name}.png"))
m.render_svg(os.path.join(out, f"{name}.svg"))
for f in sorted(os.listdir(out)):
print(f"{f:<12} {os.path.getsize(os.path.join(out, f)) // 1024} KB")
raster.png 228 KB
raster.svg 305 KB
vector.png 81 KB
vector.svg 429 KB
| PNG | SVG |
Raster OpenStreetMap |  |  |
Vector OpenFreeMap Bright |  |  |
|---|
render_array() returns the pixels, for your own compositing, and get_bounds() their extent in Web Mercator:
a = vector.render_array()
a.shape, a.dtype, vector.get_bounds()
((300, 480, 4),
dtype('uint8'),
(-12462135.04127428,
4973069.79762207,
-12449163.247426074,
4981177.168777199))
pixel_ratio makes images larger with the same view and label layout: pixel_ratio=2 for a sharp 2x image, dpi / 96 for print.
In a plot
add_basemap() adds a basemap under a matplotlib axes’ content. It renders when the figure is drawn, for the axes’ extent and at the output resolution, and credits the provider in the corner:
import matplotlib.pyplot as plt
nc_3857 = nc.to_crs(3857)
fig, ax = plt.subplots(figsize=(8, 3.6))
nc_3857.plot(ax=ax, column="BIR74", cmap="viridis", alpha=0.75, edgecolor="white", linewidth=0.3, legend=True)
bm.add_basemap(ax, "OpenFreeMap.Positron", crs=3857)
ax.set_axis_off()
geom_basemap() does the same in plotnine, with the arguments of R’s geom_basemap():
from plotnine import aes, geom_map, ggplot, scale_fill_cmap, theme_void, theme
(
ggplot(nc)
+ bm.geom_basemap("Esri.WorldGrayCanvas")
+ geom_map(aes(fill="SID74"), alpha=0.7, color="white", size=0.2)
+ scale_fill_cmap("Blues", name="SIDS, 1974")
+ theme_void()
+ theme(figure_size=(8, 3.6))
)
Plots with matplotlib and plotnine has more.
The tile cache
Tiles are cached on disk, so drawing an area again does not download its tiles again. They are kept for as long as each server allows (a day when it says nothing), and the cache looks after itself: expired tiles are deleted, and past 250 MB the least recently used tiles go first.
bm.tile_cache() # where the tiles are kept
'/home/runner/.cache/basemapper'
bm.tile_cache(max_size=500) # a 500 MB limit
bm.tile_cache("D:/basemap-tiles") # another folder, for this session
bm.tile_cache(False) # no cache, for this session
bm.tile_cache(clear=True) # delete the cached tiles
To keep a folder or limit for good, set environment variables before Python starts, for example in your shell profile (or a project’s .env, if you load one):
export BASEMAPPER_CACHE_DIR=~/basemap-tiles # Windows: setx BASEMAPPER_CACHE_DIR D:\basemap-tiles
export BASEMAPPER_CACHE_MAX_SIZE=500
R reads the same variables, so one folder can serve both languages. Without them, Python keeps its tiles in the platform’s cache folder: %LOCALAPPDATA%\basemapper on Windows, ~/Library/Caches/basemapper on macOS and ~/.cache/basemapper on Linux.