Mercantile
Mercantile is a Python library (current version 1.2.1) providing utilities for working with Web Mercator XYZ tiles. It offers functions to convert between geographic coordinates (longitude, latitude) and tile coordinates (x, y, z), calculate tile bounds, and traverse the tile hierarchy (parent, children, neighbors). Releases occur periodically, with significant updates every 1-2 years.
Warnings
- breaking Mercantile 2.0 (future release) will drop support for Python versions older than 3.0. Running on Python 2.x will issue a `UserWarning` in current versions.
- breaking In Mercantile 2.0 (future release), the `Tile` constructor will enforce stricter validation: `x` and `y` tile indexes must be integers and within the valid range (0 to 2 ** zoom). Current versions issue a `FutureWarning` if these conditions are not met.
- breaking The command line interface (CLI) underwent changes in version 1.2.0 (specifically 1.2a1). The `--bounding-tile` and `--with-bounds` options of the `mercantile tiles` command were removed. A new `mercantile bounding-tile` command was introduced to replace this functionality.
- gotcha In Mercantile versions prior to 1.2.1, a missing comma in the `__all__` list could prevent `neighbors` and `parent` functions from appearing in module documentation (e.g., `help(mercantile)`). The functions were callable but discoverability was hampered. This was fixed in 1.2.1.
Install
-
pip install mercantile
Imports
- mercantile
import mercantile
- tile
mercantile.tile(lng, lat, zoom)
- bounds
mercantile.bounds(x, y, z)
- ul
mercantile.ul(x, y, z)
- children
mercantile.children(tile, zoom=None)
- Tile
mercantile.Tile(x, y, z)
- LngLat
mercantile.LngLat(lng, lat)
Quickstart
import mercantile
# Get the tile containing a specific longitude, latitude, and zoom level
tile = mercantile.tile(-105.0, 40.0, 10)
print(f"Tile: {tile}")
# Get the geographic (longitude and latitude) bounds of a tile
bbox = mercantile.bounds(tile.x, tile.y, tile.z)
print(f"Bounding Box: {bbox}")
# Get the upper-left corner (longitude, latitude) of a tile
ul_corner = mercantile.ul(tile.x, tile.y, tile.z)
print(f"Upper-Left Corner: {ul_corner}")
# Find children tiles at a deeper zoom level
children_tiles = mercantile.children(tile, zoom=11)
print(f"Children tiles (first 2): {children_tiles[:2]}")