"""Add an OpenStreetMap basemap to a matplotlib Axes.""" from __future__ import annotations from pathlib import Path def add_basemap_osm( ax: "Axes", zoom: int = 9, cache_dir: "str | Path | None" = None, ) -> None: """Add an OpenStreetMap Mapnik basemap to a matplotlib Axes. Uses contextily to fetch and render map tiles. Network errors and tile fetch failures are silently captured — the map will render without a basemap rather than raising. Args: ax: matplotlib Axes with a projected extent (CRS must match tile CRS, typically EPSG:3857). The caller is responsible for ensuring the Axes limits are set before calling this function. zoom: Tile zoom level (1–19). Higher values fetch more tiles and produce a sharper basemap at the cost of more network requests. cache_dir: Optional directory for caching downloaded tiles. If None, contextily uses its default cache location. """ try: import contextily as ctx # type: ignore except ImportError: return try: if cache_dir is not None: ctx.set_cache_dir(str(cache_dir)) ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik, zoom=zoom) except Exception: # noqa: BLE001 pass