---------------------------------------------------------------------- This is the API documentation for the basemapper library. ---------------------------------------------------------------------- ## Basemap views Create a view (`basemap()`), change it (`set_view`, `set_bounds`), read it (`get_bounds`, `get_center`, `get_zoom`, `get_size`) and render it (`render_png`, `render_svg`, `render_array`). The same functions and arguments exist in R. basemap(style: 'Union[StyleLike, Sequence[StyleLike]]', width: 'int' = 800, height: 'int' = 600, *, center: 'Optional[Tuple[float, float]]' = None, zoom: 'Optional[float]' = None, bounds: 'Optional[Any]' = None, crs: 'Optional[Any]' = None, pixel_ratio: 'float' = 1.0, layers: 'Optional[List[str]]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None, auth_token: 'Optional[str]' = None, tile_timeout_ms: 'int' = 10000, max_tiles: 'int' = 256, tile_concurrency: 'int' = 16, fail_on_tile_error: 'bool' = False) -> 'Basemap' Create a basemap view. The view is a centre and MapLibre zoom (512 px tiles; fractional zooms are rendered natively, not resampled), or bounds to fit. ``width`` and ``height`` are CSS pixels; images are ``pixel_ratio`` times larger with the same view and label layout (MapLibre's ``devicePixelRatio``): ``pixel_ratio=2`` gives a sharp 2x image, ``pixel_ratio=dpi / 96`` matches a print resolution. The same function exists in R (``basemap()``) and Rust (``Basemap::new()``), with the same arguments. Args: style: A MapLibre GL style URL or JSON string (e.g. from :func:`basemap_provider`), or a list of those stacked bottom to top (e.g. a basemap published as separate hillshade, base and label services). width: View width in CSS pixels. height: View height in CSS pixels. center: ``(longitude, latitude)`` of the view centre. zoom: MapLibre zoom (0-22, fractional allowed). bounds: Bounds to fit instead of ``center``/``zoom``: a ``[xmin, ymin, xmax, ymax]`` sequence (in ``crs``, default EPSG:4326), a dict, or a GeoDataFrame / GeoSeries. crs: CRS of ``bounds`` (anything ``pyproj.CRS`` accepts). pixel_ratio: Device pixels per CSS pixel. layers: Optional layer filter applied to every style: plain IDs keep only those layers, ``-`` prefixed IDs drop them; ``*`` and ``?`` are wildcards (``"-label_*"``). See :func:`list_layers`. labels: ``True`` keeps every layer, ``False`` drops the labels (text and icons), ``"only"`` keeps only the labels on a transparent background, to stack over another map. Catalogue raster basemaps switch to their label-free or label-only tiles. features: Optional feature filter applied to every style: plain names keep those features, ``-`` prefixed names drop them, e.g. ``["water", "roads"]`` or ``["-buildings"]``. Features: background, water, landcover, parks, buildings, roads, rail, boundaries, places, poi, terrain, other (see the ``feature`` of :func:`list_layers`). auth_token: Optional access token for the tile service. tile_timeout_ms: Per-tile HTTP timeout in milliseconds. max_tiles: Maximum tiles fetched per style. tile_concurrency: Parallel tile downloads. fail_on_tile_error: Abort on a failed tile instead of leaving it empty. Returns: A :class:`Basemap`. Example: >>> import basemapper >>> # UGRC's Lite basemap: its hillshade, base and labels services >>> m = basemapper.basemap( ... "UGRC.Lite", 800, 600, center=(-111.8887, 40.7556), zoom=12.4, pixel_ratio=2, ... ) >>> m.render_png("slc.png") # 1600 x 1200 >>> m.render_svg("slc.svg") # vector Basemap(style: 'Union[StyleLike, Sequence[StyleLike]]', width: 'int' = 800, height: 'int' = 600, *, center: 'Optional[Tuple[float, float]]' = None, zoom: 'Optional[float]' = None, bounds: 'Optional[Any]' = None, crs: 'Optional[Any]' = None, pixel_ratio: 'float' = 1.0, layers: 'Optional[List[str]]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None, auth_token: 'Optional[str]' = None, tile_timeout_ms: 'int' = 10000, max_tiles: 'int' = 256, tile_concurrency: 'int' = 16, fail_on_tile_error: 'bool' = False) -> 'None' A map view rendered headlessly: one style, or several stacked. Create one with :func:`basemap`; see there for the arguments. Change the view with :meth:`set_view` / :meth:`set_bounds` (which return the view, so calls chain), read it with the ``get_*`` methods, and render it with :meth:`render_png`, :meth:`render_svg` or :meth:`render_array`. ## Basemap Methods Methods for the Basemap class set_view(self, center: 'Optional[Tuple[float, float]]' = None, zoom: 'Optional[float]' = None) -> "'Basemap'" Set the centre ``(longitude, latitude)`` and/or the MapLibre zoom (0-22, fractional allowed); ``None`` keeps the current value. set_bounds(self, bounds: 'Any', crs: 'Optional[Any]' = None) -> "'Basemap'" Fit the view to ``bounds`` (in ``crs``, default EPSG:4326), keeping the view's size. get_bounds(self, lonlat: 'bool' = False) -> 'Tuple[float, float, float, float]' The view's ``(xmin, ymin, xmax, ymax)`` in EPSG:3857 metres, or in degrees with ``lonlat=True``. get_center(self) -> 'Tuple[float, float]' ``(longitude, latitude)`` of the view centre. get_zoom(self) -> 'float' The MapLibre zoom of the view. get_size(self) -> 'Tuple[int, int]' ``(width, height)`` of rendered images in device pixels. get_attribution(self) -> 'str' The attribution text the view's styles ask maps to show (see :func:`get_attribution`), e.g. for a caption. __repr__(self) -> 'str' render_array(self) -> 'np.ndarray' Render to a ``(height, width, 4)`` uint8 RGBA array (device pixels). render_png(self, path: 'Optional[str]' = None) -> 'bytes' Render a PNG, written to ``path`` when given. Returns the PNG bytes. render_svg(self, path: 'Optional[str]' = None, text: 'str' = 'editable', embed_fonts: 'str' = 'subset', font_dirs: 'Optional[List[str]]' = None) -> 'str' Render an SVG (``width`` x ``height`` user units; ``pixel_ratio`` does not apply), written to ``path`` when given: vector layers as paths and text, raster tiles (raster basemaps, hillshade) as embedded images. Returns the SVG text. Args: path: Output file, or None. text: ``"editable"``: labels are ```` elements (editable, selectable) at MapLibre's glyph positions, halos as strokes, with the style's fonts embedded; labels whose font file is not available fall back to ``"bitmap"``. ``"bitmap"``: every label drawn from the style's own glyph bitmaps, thresholded by SVG filters as MapLibre's shader does (MapLibre's look at any zoom; not editable). ``"paths"``: glyph outlines traced from those bitmaps (plain paths, no filters). embed_fonts: ``"subset"`` (only the glyphs used), ``"full"`` (whole fonts, for retyping labels) or ``"none"`` (fonts by name only). Fonts come from ``font_dirs``, the ``BASEMAPPER_FONT_DIRS`` folders, a local cache, then Google Fonts for open fonts; others are referenced by name. font_dirs: Folders of .ttf / .otf files to use first. ## One-shot rendering Render bounds to an RGBA array in one call. render_basemap_raw(bounds: 'Any', width: 'int', height: 'int', style: 'Any', crs: 'Optional[Any]' = None, pixel_ratio: 'float' = 1.0, tile_zoom: 'Optional[int]' = None, layers: 'Optional[List[str]]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None, auth_token: 'Optional[str]' = None, tile_timeout_ms: 'int' = 10000, max_tiles: 'int' = 256, tile_concurrency: 'int' = 16, fail_on_tile_error: 'bool' = False) -> 'np.ndarray' Render a basemap for bounds in one call. A one-shot render: fit ``bounds`` into a ``width`` x ``height`` CSS-pixel view and return the pixels. :func:`basemap` with :meth:`Basemap.render_array` gives the same result with a reusable view. The same function exists in R (``render_basemap_raw()``). Args: bounds: Bounding box: a ``[xmin, ymin, xmax, ymax]`` sequence in ``crs`` (default EPSG:4326, with a warning when the values look projected), a dict with ``xmin``/``ymin``/``xmax``/``ymax`` (and optionally ``crs``) keys, or a GeoDataFrame / GeoSeries (CRS read from it). width: View width in CSS pixels. height: View height in CSS pixels. style: A MapLibre GL style URL or JSON string (e.g. from :func:`basemap_provider`), or a list of those stacked bottom to top. crs: CRS of ``bounds`` (anything ``pyproj.CRS`` accepts). pixel_ratio: Device pixels per CSS pixel; the image is ``width * pixel_ratio`` by ``height * pixel_ratio``. tile_zoom: Tile detail override: the tile zoom on the 256 px grid (vector sources use one less, their tiles being 512 px), or ``None`` to pick tiles as MapLibre does for the view. layers: Optional layer filter: plain IDs keep only those layers, ``-`` prefixed IDs drop them; ``*`` and ``?`` are wildcards (``"-label_*"``). labels: ``True`` keeps every layer, ``False`` drops the labels (text and icons), ``"only"`` keeps only the labels on a transparent background, to stack over another map. Catalogue raster basemaps switch to their label-free or label-only tiles. features: Optional feature filter applied to every style: plain names keep those features, ``-`` prefixed names drop them, e.g. ``["water", "roads"]`` or ``["-buildings"]``. Features: background, water, landcover, parks, buildings, roads, rail, boundaries, places, poi, terrain, other (see the ``feature`` of :func:`list_layers`). auth_token: Optional access token for the tile service. tile_timeout_ms: Per-tile HTTP timeout in milliseconds. max_tiles: Maximum tiles fetched per style. tile_concurrency: Parallel tile downloads. fail_on_tile_error: Abort on a failed tile instead of leaving it empty. Returns: numpy.ndarray: ``(height * pixel_ratio, width * pixel_ratio, 4)`` uint8 RGBA pixels. Raises: BasemapError: On any rendering or network failure. ## Plot integrations Drop a basemap layer into an existing plot, rendered at the output resolution. `geom_basemap` takes the same arguments in plotnine and ggplot2 (R). add_basemap(ax: "'matplotlib.axes.Axes'", style: 'Union[str, Any, Sequence[Any]]', tile_zoom: 'Optional[int]' = None, alpha: 'float' = 1.0, layers: 'Optional[List[str]]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None, pixel_ratio: 'Optional[float]' = None, auth_token: 'Optional[str]' = None, tile_timeout_ms: 'int' = 10000, max_tiles: 'int' = 256, attribution: 'Union[bool, str]' = True, crs: 'Optional[object]' = None) -> "'xr.DataArray'" Render a basemap beneath existing axes content. The basemap is an artist that renders when the figure is drawn, at the output resolution: on screen at the canvas dpi, and natively at the requested resolution in ``savefig(dpi=...)`` or PDF / SVG output. Takes the same arguments as :class:`geom_basemap` (and R's ``geom_basemap()``). Args: ax: An existing matplotlib Axes. style: A MapLibre GL style URL or JSON string (e.g. from :func:`basemap_provider`), or a list of those stacked bottom to top. tile_zoom: Tile detail override: the tile zoom on the 256 px grid (vector sources use one less), or None to pick tiles as MapLibre does for the view. alpha: Opacity of the basemap layer (0.0–1.0). layers: Optional layer filter. Plain IDs keep only those layers; minus-prefixed IDs drop those layers; ``*`` and ``?`` are wildcards. labels: ``True`` keeps every layer, ``False`` drops the labels (text and icons), ``"only"`` keeps only the labels on a transparent background, to stack over another map. Catalogue raster basemaps switch to their label-free or label-only tiles. features: Optional feature filter applied to every style: plain names keep those features, ``-`` prefixed names drop them, e.g. ``["water", "roads"]`` or ``["-buildings"]``. Features: background, water, landcover, parks, buildings, roads, rail, boundaries, places, poi, terrain, other (see the ``feature`` of :func:`list_layers`). pixel_ratio: Device pixels per CSS pixel (MapLibre's devicePixelRatio). Default: output dpi / 96, so lines and labels keep their physical size at any dpi. Larger values draw map symbols smaller. auth_token: Optional access token for the tile service. tile_timeout_ms: Per-tile HTTP timeout in milliseconds. max_tiles: Maximum tile downloads per style. attribution: The credit line the basemap's providers ask for, drawn small in the bottom-right corner over the plot: ``True`` (the default) for the styles' own (see :func:`get_attribution`), ``False`` for none, or your own text. crs: CRS of the axes data coordinates (anything ``pyproj.CRS`` accepts, e.g. ``"EPSG:4326"``, ``gdf.crs``). Required for plain matplotlib axes and GeoDataFrame plots, whose axes carry no CRS; detected automatically for cartopy axes when omitted. Returns: xarray.DataArray of shape (height, width, 4) holding the first render (at the figure's current dpi), with spatial bounds and CRS in ``.attrs``. The live artist is ``ax.images[-1]``. Raises: BasemapError: If CRS detection fails, the render fails, or the network is unreachable. geom_basemap(style: 'Any', tile_zoom: 'Optional[int]' = None, alpha: 'float' = 1.0, layers: 'Optional[List[str]]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None, pixel_ratio: 'Optional[float]' = None, auth_token: 'Optional[str]' = None, tile_timeout_ms: 'int' = 10000, max_tiles: 'int' = 256, attribution: 'Union[bool, str]' = True, crs: 'object' = 'EPSG:4326', **kwargs: 'object') -> 'None' Render a styled basemap beneath plotnine spatial layers. Defers all tile fetching to draw time so that the plot's coordinate system has been established. Uses the same injection logic as :func:`add_basemap`. The basemap renders when the plot is drawn, at the output resolution (natively at ``save(dpi=...)``), like :func:`add_basemap`. The same layer exists in R (ggplot2 ``geom_basemap()``), with the same arguments. Args: style: A MapLibre GL style URL or JSON string (e.g. from :func:`basemap_provider`), or a list of those stacked bottom to top. tile_zoom: Tile detail override: the tile zoom on the 256 px grid (vector sources use one less), or None to pick tiles as MapLibre does for the view. alpha: Opacity of the basemap layer (0.0–1.0). layers: Optional layer filter list — plain IDs keep only those layers; minus-prefixed IDs drop those layers; ``*`` and ``?`` are wildcards. labels: ``True`` keeps every layer, ``False`` drops the labels (text and icons), ``"only"`` keeps only the labels on a transparent background, to stack over another map. Catalogue raster basemaps switch to their label-free or label-only tiles. features: Optional feature filter applied to every style: plain names keep those features, ``-`` prefixed names drop them, e.g. ``["water", "roads"]`` or ``["-buildings"]``. Features: background, water, landcover, parks, buildings, roads, rail, boundaries, places, poi, terrain, other (see the ``feature`` of :func:`list_layers`). pixel_ratio: Device pixels per CSS pixel; default output dpi / 96. auth_token: Optional access token for the tile service. tile_timeout_ms: Per-tile HTTP timeout in milliseconds. max_tiles: Maximum tile downloads per style. attribution: The credit line the basemap's providers ask for, drawn small in the bottom-right corner over the plot: ``True`` (the default) for the styles' own (see :func:`get_attribution`), ``False`` for none, or your own text. crs: CRS of the plot's x/y data (anything ``pyproj.CRS`` accepts). plotnine has no spatial coordinate system to read it from, so it defaults to ``"EPSG:4326"`` (longitude/latitude). Pass e.g. ``crs=gdf.crs`` or ``crs="EPSG:3857"`` for projected data. Example: >>> import pandas as pd >>> from plotnine import ggplot, aes, geom_point >>> from basemapper import basemap_provider, geom_basemap >>> df = pd.DataFrame({"lon": [-111.95, -111.80], "lat": [40.68, 40.80]}) >>> (ggplot(df, aes("lon", "lat")) ... + geom_basemap("OpenFreeMap.Positron") ... + geom_point()) ## Styles Named basemaps (leaflet-providers names, usable as `style`), styles for your own tile data, and OGC services. Tile data (tile URLs, TileJSON, PMTiles, ArcGIS services) also works as `style` directly. basemap_provider(name: 'str', type: 'Optional[str]' = None, api_key: 'Optional[str]' = None, tiles: 'Optional[str]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None) -> 'Union[str, List[str]]' A named basemap's style (styles, for a basemap of stacked services). Names follow leaflet-providers (``"CartoDB.Positron"``, ``"Esri.WorldImagery"``, ``"OpenStreetMap.HOT"``); see :func:`list_providers` or the :data:`providers` object. A name also works as ``style`` directly; this function picks the form, passes a key, or swaps in your own tiles. Args: name: Basemap name (case-insensitive). type: ``"vector"`` (a MapLibre style) or ``"raster"`` (tiles). By default the vector form when there is one, else raster. Asking for a form a basemap lacks is an error, never a silent fallback. api_key: API key for CARTO, MapTiler and Stadia, or the quad word for UGRC Discover's basemaps (``"UGRC.Terrain"``, ``"UGRC.Topo"``, ``"UGRC.Hillshade"``, ``"UGRC.Imagery"``, ...); by default read from ``CARTO_API_KEY``, ``MAPTILER_API_KEY``, ``STADIA_API_KEY`` or ``UGRC_QUAD_WORD``. The keys are free for moderate use (UGRC's for Utah's government and partners); :func:`list_providers` shows which basemaps need one. tiles: Your own tile data to draw with this basemap's style: a ``.pmtiles`` archive (URL or path), tile URL or TileJSON. It must use the same schema as the provider's tiles (OpenMapTiles for OpenFreeMap and Stadia). labels: ``True`` keeps every layer, ``False`` drops the labels, ``"only"`` keeps only the labels, to stack this basemap's labels over another map. Raster tiles switch to the provider's label-free or label-only tiles (an error when it has none). features: Vector form: features to keep (``["water", "roads"]``) or drop (``["-buildings"]``); see :func:`list_layers`. Returns: A style URL, or inline style JSON (the raster form, or with ``tiles``, ``labels`` or ``features``). A basemap published as separate services (``"UGRC.Lite"``: hillshade, base and labels) returns a list of styles, bottom to top, which :func:`basemap` and the plot layers take as a stack; ``labels`` and ``features`` apply to the stack as one basemap, leaving out a style they empty. Raises: ValidationError: For an unknown name (with suggestions), a form the basemap lacks, or a missing API key. list_providers(type: 'Optional[str]' = None) -> 'List[Dict[str, object]]' The basemaps :func:`basemap_provider` knows. Args: type: ``"vector"`` or ``"raster"`` to list only basemaps with that form; None lists all. Returns: One dict per basemap: ``name``, ``vector`` and ``raster`` (the forms it has), ``api_key_env`` (the environment variable its key is read from, or None when it needs none) and ``attribution``. providers Basemap names of one provider, as attributes. tile_style(source: 'str', type: 'Optional[str]' = None, tile_size: 'Optional[int]' = None, scheme: 'Optional[str]' = None, minzoom: 'Optional[int]' = None, maxzoom: 'Optional[int]' = None, attribution: 'Optional[str]' = None, source_layers: 'Optional[List[str]]' = None, paint: 'Optional[Dict[str, object]]' = None, auth_token: 'Optional[str]' = None) -> 'str' A style for tile data, with overrides. ``source`` is what you could pass as ``style`` directly; use this function to override what is detected, or to get the style JSON to edit: * a tile URL template (``{z}/{x}/{y}``, ``{quadkey}``, ``{bbox-epsg-3857}``, WMTS ``{TileMatrix}/{TileRow}/{TileCol}``); * a TileJSON URL or file; * a PMTiles archive: URL, local path or ``pmtiles://`` URL; * an ArcGIS ``.../MapServer`` (raster tiles) or ``.../VectorTileServer`` (its published style); * a style URL or file (returned with relative URLs made absolute). Raster tiles get one raster layer. Vector tiles get a default style drawing every source layer (polygons as translucent fills, lines and outlines, points as circles, a colour per source layer) over a transparent background. Args: source: The tile data, as above. type: ``"raster"`` or ``"vector"``; detected when None (from the archive header, the TileJSON, the URL's extension, or one fetched tile). tile_size: Raster tile size in px (default 256 for tile URLs and archives). scheme: ``"xyz"`` or ``"tms"`` (rows counted from the south). minzoom: Minimum zoom of the tiles. maxzoom: Maximum zoom of the tiles (overzoomed beyond). attribution: Attribution text for the source. source_layers: Vector tiles: the source layers to draw (default all). paint: Vector tiles: paint properties for the generated ``fill-*``, ``line-*`` and ``circle-*`` layers, e.g. ``{"fill-color": "#ccc"}``. Others are dropped with a warning. auth_token: Optional access token for the tile service. Returns: The style JSON. Raises: ValidationError: If the type cannot be detected or does not match the data, or ``source`` is not found. wms_style(url: 'str', layers: 'str', styles: 'str' = '', version: 'str' = '1.3.0', format: 'str' = 'image/png', transparent: 'bool' = False, extra_params: 'Optional[str]' = None) -> 'str' Style for an OGC WMS GetMap endpoint, as 256 px tiles in EPSG:3857. Args: url: Base service URL without query parameters. layers: ``LAYERS`` parameter. styles: ``STYLES`` parameter. version: Service version (1.1.x sends ``SRS``, 1.3.0 ``CRS``). format: Image MIME type. transparent: Request transparent images. extra_params: Additional query parameters appended verbatim. wmts_style(url: 'str', layer: 'str', tilematrixset: 'str' = 'GoogleMapsCompatible', format: 'str' = 'image/png', style: 'str' = 'default', version: 'str' = '1.0.0', extra_params: 'Optional[str]' = None) -> 'str' Style for an OGC WMTS GetTile (KVP) endpoint. A RESTful WMTS template (``{TileMatrix}/{TileRow}/{TileCol}``) needs no builder: pass it as ``style``. Args: url: Base service URL without query parameters. layer: ``LAYER`` parameter. tilematrixset: Tile matrix set (a Web Mercator one). format: Image MIME type. style: ``STYLE`` parameter. version: Service version. extra_params: Additional query parameters appended verbatim. ## Style layers and attribution A style's layers with their features, for the `layers` and `features` filters, and the attribution text it asks maps to show. list_layers(style: 'Any', auth_token: 'Optional[str]' = None, layers: 'Optional[List[str]]' = None, labels: 'Union[bool, str]' = True, features: 'Optional[List[str]]' = None) -> 'List[Dict[str, Optional[str]]]' List a style's layers, or preview a filter. The layers of a style in drawing order: their ``id`` (what ``layers`` matches), ``type`` (``symbol`` layers are the labels ``labels`` keeps or drops), ``source_layer`` (the vector tile layer drawn, None for background and raster layers) and ``feature`` (what ``features`` matches). With ``layers``, ``labels`` or ``features``, the layers a render with those filters draws; an empty list when they leave nothing. The same function exists in R (``list_layers()``, returning a data frame). A layer's feature comes from its source layer, with tables for the OpenMapTiles (OpenFreeMap, Stadia, MapTiler), Protomaps (CARTO) and Shortbread (VersaTiles) schemas, and keywords for others (Esri's descriptive names, layer ids). It is a convenience: check it here, and use ``layers`` for exact control. Args: style: A style (anything :func:`basemap` takes). auth_token: Optional access token for the style URL. layers: Layer filter to preview: plain IDs keep, ``-`` prefixed IDs drop; ``*`` and ``?`` are wildcards. labels: ``True``, ``False`` or ``"only"``, as the renderers take it. features: Feature filter to preview, as the renderers take it. Returns: A list of ``{"id", "type", "source_layer", "feature"}`` dicts (``pandas.DataFrame(...)`` turns it into a table). Raises: BasemapError: If the style cannot be fetched or parsed, or a filter is invalid. get_attribution(style: 'Any', auth_token: 'Optional[str]' = None) -> 'str' The attribution text a style asks maps to show. Every source the style's layers draw from contributes its attribution (from the style, the source's TileJSON or PMTiles metadata), as MapLibre's attribution control collects it, as plain text without duplicates, joined with ``" | "``. Use it for a caption or a credit line, e.g. ``ax.annotate(get_attribution(style), ...)``. :meth:`Basemap.get_attribution` gives a view's. The same function exists in R (``get_attribution()``). Args: style: A style (anything :func:`basemap` takes), or a list of styles stacked bottom to top. auth_token: Optional access token for the tile service. Returns: The attribution; an empty string when the styles give none. ## Tile cache tile_cache(dir: 'Optional[str]' = None, clear: 'bool' = False, max_size: 'Optional[float]' = None) -> 'Optional[str]' The disk cache for map tiles. Tiles are kept as long as the server's caching headers allow (a day when they say nothing), so repeated renders of an area do not download them again. The cache starts in ``BASEMAPPER_CACHE_DIR`` when set (``off`` disables it), else in the platform cache directory (``%LOCALAPPDATA%\basemapper``, ``~/Library/Caches/basemapper`` or ``~/.cache/basemapper``). Set ``BASEMAPPER_CACHE_DIR`` in your shell profile or environment to keep a folder for good, or to share one cache with R. The cache is kept small: expired tiles are deleted, and past its size limit (250 MB, or ``BASEMAPPER_CACHE_MAX_SIZE`` in MB) the least recently used tiles go first, in the background as tiles are stored. Args: dir: Move the cache to this directory; ``False`` or ``""`` turns it off. None leaves it as it is. clear: Delete every cached tile. max_size: The cache's size limit in megabytes; None leaves it as it is. Returns: The cache directory, or None when the cache is off. ## Exceptions BasemapError(message: str) -> None Base exception for all basemapper errors. ValidationError(message: str) -> None Raised for invalid bbox, dimensions, zoom, or layer filter. Subclasses both :class:`BasemapError` and :class:`ValueError` so that callers that catch the built-in ``ValueError`` continue to work unchanged. StyleError(message: str) -> None Raised when a style cannot be fetched or parsed. NetworkError(message: str) -> None Raised when tile or style network requests fail. ---------------------------------------------------------------------- This is the User Guide documentation for the package. ---------------------------------------------------------------------- ### Get started > **R or Rust?** The same functions and arguments exist in > [R](../../r/index.html) (`verb(m, ...)` for Python's `m.verb(...)`) and > [Rust](../../rust/basemapper_core/index.html). 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 ```sh 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](../index.html) for conda. ## Choose a style Every function takes a `style`. The simplest is a named basemap, a [leaflet-providers](https://leaflet-extras.github.io/leaflet-providers/preview/) name; `list_providers()` lists them, with the API key some need: ```{python} 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']}") ``` 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](05-own-data.qmd)). ## 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: ```{python} 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: ```{python} print(repr(m)) print(m.get_bounds(lonlat=True)) print(m.get_attribution()) ``` `set_view()` and `set_bounds()` change the view. Here it fits North Carolina's counties (a GeoDataFrame, from [geodatasets](https://geodatasets.readthedocs.io)): ```{python} 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. ```{python} 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") ``` ```{python} #| echo: false # Show the four files written above. import base64 from IPython.display import HTML def uri(f): mime = "image/svg+xml" if f.endswith(".svg") else "image/png" return f"data:{mime};base64," + base64.b64encode(open(os.path.join(out, f), "rb").read()).decode() HTML(f"""
PNGSVG
Raster
OpenStreetMap
Vector
OpenFreeMap Bright
""") ``` `render_array()` returns the pixels, for your own compositing, and `get_bounds()` their extent in Web Mercator: ```{python} a = vector.render_array() a.shape, a.dtype, vector.get_bounds() ``` `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: ```{python} 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()`: ```{python} 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](03-plotting.qmd) 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. ```{python} bm.tile_cache() # where the tiles are kept ``` ```{python} #| eval: false 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): ```sh 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. ### Basemap gallery Every basemap in the catalogue that needs no API key, rendered for the same view of the San Francisco Bay Area (the Utah basemaps [below](#utah), over Salt Lake City). The names work as `style` anywhere: in `basemap()`, `add_basemap()`, `geom_basemap()` and in R and Rust. ```{python} import basemapper as bm providers = bm.list_providers() keyless = [p for p in providers if p["api_key_env"] is None] utah = [p for p in keyless if p["name"].startswith("UGRC.")] world = [p for p in keyless if p not in utah] print(len(world), "basemaps") images = {} for p in world: m = bm.basemap(p["name"], 340, 220, center=(-122.25, 37.75), zoom=9) images[p["name"]] = m.render_png() ``` ```{python} #| echo: false # Lay out rendered images, with each one's name and form. import base64 from IPython.display import HTML def gallery(entries): cells = [] for p in entries: src = "data:image/png;base64," + base64.b64encode(images[p["name"]]).decode() form = "vector" if p["vector"] else "raster" cells.append(f'
{p[' f'
{p["name"]} {form}
') return HTML('") gallery(world) ``` The vector basemaps (OpenFreeMap, and Esri's vector styles) are drawn from vector tiles by basemapper's port of MapLibre GL JS; the raster ones are tile images. Esri's names have both forms; `basemap_provider(name, type="raster")` picks the other one. ## Utah {#utah} The Utah Geospatial Resource Center's vector basemaps cover Utah. Each is published as separate services (a hillshade, a base map and labels, or imagery and an overlay), and its name stands for the whole stack: `basemap_provider("UGRC.Lite")` returns the three styles, and `labels` and `features` treat them as one basemap. ```{python} print([p["name"] for p in utah]) for p in utah: m = bm.basemap(p["name"], 340, 220, center=(-111.89, 40.70), zoom=10) images[p["name"]] = m.render_png() ``` ```{python} #| echo: false gallery(utah) ``` ## With an API key CARTO, Stadia Maps and MapTiler need a free API key, and UGRC Discover's raster basemaps of Utah (terrain, topographic, hillshade and imagery, with UGRC's road and label overlay as their labels) its quad word. Each is read from the environment variable in `api_key_env` (or given as `api_key=` to `basemap_provider()`): ```{python} for p in providers: if p["api_key_env"]: print(f"{p['name']:<26} {p['api_key_env']}") ``` ### Plots with matplotlib and plotnine `add_basemap()` (matplotlib) and `geom_basemap()` (plotnine) add a basemap under your data. They render when the figure is drawn, for the axes' extent and at the output resolution: on screen, in this page, or in `savefig(dpi=300)` and `save(dpi=300)`, labels stay sharp and the right size. Both take the arguments of `basemap()`'s renderers (`labels`, `features`, `layers`, `alpha`, ...) and credit the provider in the corner. ```{python} import warnings warnings.filterwarnings("ignore", message=".*centroid.*") import basemapper as bm import geodatasets import geopandas as gpd import matplotlib.pyplot as plt nc = gpd.read_file(geodatasets.get_path("geoda.sids")) ``` ## matplotlib `add_basemap()` draws under what the axes already show. Give it the data's CRS with `crs=`: ```{python} fig, ax = plt.subplots(figsize=(8, 3.6)) nc.assign(rate=nc.SID79 / nc.BIR79 * 1000).plot( ax=ax, column="rate", cmap="OrRd", alpha=0.8, edgecolor="white", linewidth=0.2, legend=True, legend_kwds={"label": "SIDS per 1,000 births, 1979", "shrink": 0.7}, ) bm.add_basemap(ax, "OpenFreeMap.Positron", crs=nc.crs) ax.set_axis_off() ``` ### Projected data The basemap is rendered in Web Mercator and warped to the axes' CRS, so data in any CRS works. Here North Carolina's state plane (EPSG:32119), with the counties' centroids sized by births: ```{python} nc_sp = nc.to_crs(32119) fig, ax = plt.subplots(figsize=(8, 3.6)) nc_sp.boundary.plot(ax=ax, color="0.15", linewidth=0.3) nc_sp.centroid.plot(ax=ax, markersize=nc_sp.BIR74 / 300, color="#D96E34", alpha=0.7) bm.add_basemap(ax, "Esri.WorldTopoMap", crs=nc_sp.crs) ax.set_axis_off() ``` ### A quieter basemap For a data map, a basemap often reads better without its labels, faded, or with only some of its features (see [Stacking, labels and features](04-layers.qmd)): ```{python} fig, ax = plt.subplots(figsize=(8, 3.6)) nc.assign(share=nc.NWBIR74 / nc.BIR74).plot( ax=ax, column="share", cmap="viridis", edgecolor="white", linewidth=0.2, legend=True, legend_kwds={"label": "Share of births, non-white, 1974", "shrink": 0.7}, ) bm.add_basemap(ax, "OpenFreeMap.Liberty", labels=False, features=["-roads", "-rail"], alpha=0.6, crs=nc.crs) ax.set_axis_off() ``` ### Zooming in The basemap follows the axes, so setting their limits zooms it in, with detail to match: ```{python} fig, ax = plt.subplots(figsize=(8, 5.2)) nc.boundary.plot(ax=ax, color="yellow", linewidth=1) for _, row in nc.iterrows(): p = row.geometry.representative_point() if -76.9 < p.x < -75.4 and 35.0 < p.y < 36.0: ax.annotate(row.NAME, (p.x, p.y), color="white", fontsize=9, fontweight="bold", ha="center") ax.set_xlim(-76.9, -75.4) ax.set_ylim(35.0, 36.0) bm.add_basemap(ax, "Esri.WorldImagery", crs=nc.crs) ax.set_axis_off() ``` ### Credits The credit line is on by default. `attribution=False` turns it off; `get_attribution()` returns the text, for a caption: ```{python} fig, ax = plt.subplots(figsize=(8, 3.6)) nc.boundary.plot(ax=ax, color="steelblue", linewidth=0.4) bm.add_basemap(ax, "Esri.WorldGrayCanvas", attribution=False, crs=nc.crs) ax.set_axis_off() fig.text(0.98, 0.02, bm.get_attribution("Esri.WorldGrayCanvas"), ha="right", fontsize=6, color="0.4") ``` ## plotnine `geom_basemap()` is a plotnine layer with the arguments of R's `geom_basemap()`: ```{python} from plotnine import aes, geom_map, ggplot, labs, scale_fill_distiller, theme, theme_void ( ggplot(nc) + bm.geom_basemap("OpenFreeMap.Positron") + geom_map(aes(fill="BIR79"), alpha=0.75, color="white", size=0.2) + scale_fill_distiller(type="seq", palette="Blues", direction=1, name="Births, 1979") + theme_void() + theme(figure_size=(8, 3.6)) ) ``` Raster and vector basemaps, stacks, labels and features work the same way; here shaded relief under a vector basemap's labels: ```{python} from plotnine import geom_point, scale_size_area relief = ["Esri.WorldShadedRelief", bm.basemap_provider("OpenFreeMap.Liberty", labels="only")] centroids = nc.assign(x=nc.centroid.x, y=nc.centroid.y) ( ggplot(centroids) + bm.geom_basemap(relief) + geom_map(fill=None, color="#333333", size=0.25) + geom_point(aes("x", "y", size="BIR74"), color="#D96E34", alpha=0.7) + scale_size_area(max_size=6, name="Births, 1974") + theme_void() + theme(figure_size=(8, 3.6)) ) ``` ### Stacking, labels and features A style is a stack of layers: background, water, roads, labels and so on. basemapper can draw only some of them, and can stack several styles into one map. ```{python} import basemapper as bm slc = (-111.8887, 40.7556) def view(style, **kw): return bm.basemap(style, 720, 405, center=slc, zoom=12.4, **kw) ``` ## What a style draws `list_layers()` lists a style's layers in drawing order, with the vector tile layer each one draws (`source_layer`) and the *feature* it shows: ```{python} from collections import Counter layers = bm.list_layers("OpenFreeMap.Liberty") print(len(layers), "layers") for l in layers[:10]: print(f"{l['id']:<22} {l['type']:<10} {str(l['source_layer']):<14} {l['feature']}") print(Counter(l["feature"] for l in layers)) ``` ## Labels `labels=False` draws a style without its labels (text and icons): ```{python} view("OpenFreeMap.Liberty", labels=False) ``` `labels="only"` draws just the labels, on a transparent background, to go over another map. ## Stacking A list of styles is drawn bottom to top. To filter one style of a stack, give the filter to `basemap_provider()`; this puts satellite imagery under a vector basemap's labels: ```{python} hybrid = ["Esri.WorldImagery", bm.basemap_provider("OpenFreeMap.Liberty", labels="only")] view(hybrid) ``` ArcGIS basemaps are often published as separate services, drawn in order. The Utah Geospatial Resource Center's *Lite* basemap is a hillshade, a base map and labels; its catalogue name stands for the three: ```{python} for style in bm.basemap_provider("UGRC.Lite"): print(style) bm.basemap("UGRC.Lite", 720, 405, center=(-111.75, 40.62), zoom=10.5) ``` Filters treat a stack as one basemap: a service they leave nothing of is skipped. Without labels, the labels service drops out, and the base map's own labels go too: ```{python} bm.basemap("UGRC.Lite", 720, 405, center=(-111.75, 40.62), zoom=10.5, labels=False) ``` ## Features `features` keeps or drops parts of the map by what they show: background, water, landcover, parks, buildings, roads, rail, boundaries, places, poi and terrain. Plain names keep, `"-name"` drops. ```{python} view("OpenFreeMap.Liberty", labels=False, features=["background", "water", "parks", "roads"]) ``` ```{python} view("OpenFreeMap.Liberty", features=["-roads", "-rail", "-poi"]) ``` `list_layers()` takes the same filters and lists what a render with them draws, to check a filter before rendering: ```{python} for l in bm.list_layers("OpenFreeMap.Liberty", labels=False, features=["water", "parks"]): print(f"{l['id']:<22} {l['type']:<6} {l['feature']}") ``` ## Layers Features are sorted from each layer's source layer, as a convenience. For exact control, `layers` keeps layers by id, or drops them with `"-"`; `*` and `?` are wildcards: ```{python} view("OpenFreeMap.Liberty", layers=["-road_*", "-bridge_*", "-tunnel_*"]) ``` A name that matches no layer warns, so a typo does not go unnoticed: ```{python} m = view("OpenFreeMap.Liberty", layers=["-lable_village"]) _ = m.render_array() ``` ## In plots The plot layers take the same arguments: ```{python} import geodatasets import geopandas as gpd from plotnine import geom_map, ggplot, theme, theme_void nc = gpd.read_file(geodatasets.get_path("geoda.sids")) water = bm.basemap_provider("OpenFreeMap.Liberty", features=["water"], labels=False) ( ggplot(nc) + bm.geom_basemap(["Esri.WorldShadedRelief", water]) + geom_map(fill=None, color="#262626", size=0.25) + theme_void() + theme(figure_size=(8, 3.6)) ) ``` ### Your own tiles and services Besides named basemaps and MapLibre styles, `style` takes tile data: a tile URL template, TileJSON, a PMTiles archive (URL or local file), or an ArcGIS service. basemapper detects whether the tiles are raster or vector and builds a style for them; `tile_style()` builds one with your overrides. OGC services (WMS, WMTS) have their own style builders. ```{python} import basemapper as bm ``` ## A tile URL An XYZ template, as raster tiles: ```{python} bm.basemap("https://tile.opentopomap.org/{z}/{x}/{y}.png", 720, 405, center=(-111.65, 40.60), zoom=11) ``` ## PMTiles A [PMTiles](https://docs.protomaps.com/pmtiles/) archive is read with HTTP range requests, or from a local file. Raster archives draw as they are; here a USGS topographic map of Mount Whitney, fitted to the archive's extent: ```{python} bm.basemap("https://pmtiles.io/usgs-mt-whitney-8-15-webp-512.pmtiles", 720, 405, bounds=[-118.3198, 36.5611, -118.2607, 36.5930]) ``` Vector archives get a default style over every source layer: ```{python} firenze = "https://pmtiles.io/protomaps(vector)ODbL_firenze.pmtiles" bm.basemap(firenze, 720, 405, center=(11.255, 43.773), zoom=13.5) ``` `tile_style()` sets which source layers it draws, and its paint: ```{python} print(sorted({l["source_layer"] for l in bm.list_layers(firenze)})) styled = bm.tile_style( firenze, source_layers=["earth", "water", "landuse", "roads", "buildings"], paint={"fill-color": "#f2efe9", "line-color": "#8a8a8a"}, ) bm.basemap(styled, 720, 405, center=(11.255, 43.773), zoom=13.5) ``` ### With a basemap style A vector archive can also be drawn with a full basemap style whose source points at it. [protomaps-light.json](../../styles/protomaps-light.json) and [protomaps-dark.json](../../styles/protomaps-dark.json) are the [Protomaps](https://github.com/protomaps/basemaps) basemap styles with the Florence archive as their source (`"url": "pmtiles://https://pmtiles.io/protomaps(vector)ODbL_firenze.pmtiles"`), and a style file's path works as `style`: ```{python} bm.basemap("styles/protomaps-light.json", 720, 405, center=(11.2551, 43.7710), zoom=15.2) ``` ```{python} bm.basemap("styles/protomaps-dark.json", 720, 405, center=(11.2551, 43.7710), zoom=15.2) ``` For your own Protomaps archive, change the source's `url` to `pmtiles://` and the archive's URL or path. These styles are for Protomaps tiles v3; archives built from late 2024 on use tiles v4, with the styles of `@protomaps/basemaps` 5 ([how the styles were made](../../styles/README.md)). ## TileJSON A TileJSON URL works the same way; this is OpenFreeMap's planet tileset, with the default vector style: ```{python} bm.basemap("https://tiles.openfreemap.org/planet", 720, 405, center=(-111.8887, 40.7556), zoom=12) ``` ## Your tiles in a basemap's style `basemap_provider(name, tiles=)` keeps a basemap's style and swaps in your own tiles, which must use the same schema (OpenFreeMap's styles use OpenMapTiles): self-hosted tiles, or an extract for offline use. ```{python} style = bm.basemap_provider("OpenFreeMap.Positron", tiles="https://tiles.openfreemap.org/planet") bm.basemap(style, 720, 405, center=(-111.8887, 40.7556), zoom=12) ``` ## OGC services `wms_style()` and `wmts_style()` build styles for OGC services. NASA's Blue Marble, from GIBS: ```{python} gibs = bm.wms_style("https://gibs.earthdata.nasa.gov/wms/epsg3857/best/wms.cgi", layers="BlueMarble_ShadedRelief_Bathymetry", format="image/jpeg") bm.basemap(gibs, 720, 360, center=(0, 20), zoom=0.6) ``` ## In plots Any of these goes in `add_basemap()` and `geom_basemap()`: ```{python} import geodatasets import geopandas as gpd import matplotlib.pyplot as plt nc = gpd.read_file(geodatasets.get_path("geoda.sids")) fig, ax = plt.subplots(figsize=(8, 4.4)) nc.boundary.plot(ax=ax, color="black", linewidth=0.4) ax.set_xlim(-84.4, -81.2) ax.set_ylim(34.9, 36.6) bm.add_basemap(ax, "https://tile.opentopomap.org/{z}/{x}/{y}.png", alpha=0.8, crs=nc.crs) ax.set_axis_off() ``` ## Tile cache Tiles are cached on disk, for as long as the servers' caching headers allow. `tile_cache()` shows where; `tile_cache(clear=True)` empties it, and `tile_cache(False)` turns it off for the session.