Tiles Module — Web-tile Basemaps#
The cleopatra.tiles module adds an optional, pure-Python web-tile basemap helper:
add_tiles fetches XYZ map tiles covering an axes' current extent, stitches them with
Pillow, and renders the composite underneath your data. No GDAL is required.
It is gated behind the cleopatra[tiles] optional extra (mercantile, pillow,
pyproj, xyzservices):
If the extra is not installed, the functions raise a clear ImportError with the install
hint.
Usage#
import matplotlib
matplotlib.use("Agg") # any backend; Agg shown for headless rendering
import matplotlib.pyplot as plt
from cleopatra.tiles import add_tiles
fig, ax = plt.subplots()
# plot something in Web Mercator (EPSG:3857) coordinates ...
ax.plot([1_000_000.0, 1_200_000.0], [6_000_000.0, 6_200_000.0])
# ... and drop an OpenStreetMap basemap underneath it
add_tiles(ax, crs=3857)
# a different provider, a fixed zoom, a custom User-Agent (recommended in production):
add_tiles(
ax,
source="CartoDB.Positron",
crs="EPSG:4326",
zoom=8,
user_agent="my-app/1.0 (+https://example.org)",
)
fig.savefig("map.png")
Note
add_tiles reads the axes' current xlim/ylim, so plot your data first. When the
data CRS is Web Mercator the tiles are placed in-place; for any other crs= the
bitmap is placed using the data's densified bounds and matplotlib stretches it — fine
for small extents, but for large areas or pixel-accurate results reproject the source
data to EPSG:3857 before plotting. The number of tiles fetched is capped by
max_tiles (default MAX_TILES = 256); the zoom is stepped down if a level would
need more.
Module Documentation#
cleopatra.tiles
#
Web-tile basemap helper for matplotlib axes.
Provides add_tiles -- a single entry point that fetches XYZ web
tiles for the current axes extent, stitches them into a composite image
with Pillow, and renders the image underneath the existing data layer.
The implementation is a pure-Python port of the pyramids.basemap
module (basemap.py + tiles.py). It supports any XYZ provider listed in
xyzservices. CRS handling is done with pyproj -- there is
no GDAL dependency, so the module is safe to use in environments that
only have matplotlib + numpy installed.
Notes
For data in projected CRSes other than Web Mercator (EPSG:3857) the stitched tile image is placed in the target CRS using the data's densified bounds. Matplotlib stretches the image to fit, which is visually acceptable for small extents (e.g. local maps in EPSG:4326) but may show projection distortion over very large areas. If pixel-accurate warping is required, reproject the source data to Web Mercator (EPSG:3857) before plotting.
Examples:
Add a default OpenStreetMap basemap to an axes that already has data plotted in Web Mercator coordinates:
>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> _ = ax.plot([1000000.0, 1200000.0], [6000000.0, 6200000.0])
>>> _ = add_tiles(ax, source=None, crs=3857)
add_tiles(ax, source=None, crs=None, zoom='auto', alpha=1.0, attribution=True, zorder=-1, interpolation='bilinear', timeout=10, retries=2, user_agent=None, max_tiles=MAX_TILES)
#
Overlay a web-tile basemap on a matplotlib axes.
Fetches XYZ web tiles that cover the axes' current extent, stitches them into a single composite image, and renders the image below the existing data layer. When the data is already in Web Mercator (EPSG:3857) the tiles are placed in-place; for any other CRS the image is placed in the target CRS using the data's densified bounds -- matplotlib stretches the bitmap to fit, which is visually acceptable for small extents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Any
|
Matplotlib |
required |
source
|
Any | None
|
Tile provider. |
None
|
crs
|
int | str | None
|
CRS of the data on |
None
|
zoom
|
int | str
|
Tile zoom level. |
'auto'
|
alpha
|
float
|
Opacity of the basemap ( |
1.0
|
attribution
|
str | bool
|
|
True
|
zorder
|
int
|
Matplotlib zorder for the basemap ( |
-1
|
interpolation
|
str
|
Interpolation method passed to |
'bilinear'
|
timeout
|
int
|
Per-tile HTTP timeout in seconds. |
10
|
retries
|
int
|
Per-tile retry count. |
2
|
user_agent
|
str | None
|
|
None
|
max_tiles
|
int
|
Cap on how many tiles to fetch. If the chosen |
MAX_TILES
|
Returns:
| Type | Description |
|---|---|
Any
|
matplotlib.axes.Axes: The same axes, for chaining. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the |
TypeError
|
If |
ValueError
|
If the axes have no data extent or |
ConnectionError
|
If tiles cannot be fetched from the provider. |
Examples:
Add a default OpenStreetMap basemap to an existing plot:
>>> import matplotlib
>>> matplotlib.use("Agg")
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> _ = ax.plot([1000000.0, 1200000.0], [6000000.0, 6200000.0])
>>> _ = add_tiles(ax, crs=3857)
Source code in src/cleopatra/tiles.py
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 | |
auto_zoom(bounds_4326)
#
Compute a default zoom level for the given bounds in EPSG:4326.
Uses the formula
zoom = ceil(log2(360 / max(lon_extent, lat_extent))) clamped to
the range 0--19.
This is a coarse heuristic that treats degrees of longitude and
latitude as interchangeable; it does not account for Web
Mercator's latitude distortion, so the result tends to be
conservative (under-zoomed) for extents far from the equator. For
high-latitude data, pass an explicit zoom= to add_tiles
rather than relying on the auto value. The MAX_TILES cap in
add_tiles will still step the zoom back down if the chosen
level would require too many tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bounds_4326
|
tuple[float, float, float, float]
|
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Zoom level between 0 and 19. |
Examples:
- Worldwide extent maps to zoom 0:
- A 0.6 by 0.2 degree window over Berlin yields zoom 10:
- Tiny extents are clamped to the maximum zoom (19):
Source code in src/cleopatra/tiles.py
fetch_single_tile(tile, provider, timeout, retries, user_agent=USER_AGENT)
#
Fetch a single tile, retrying on transient failures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile
|
Any
|
Tile to fetch (has |
required |
provider
|
Any
|
|
required |
timeout
|
int
|
HTTP request timeout in seconds. |
required |
retries
|
int
|
Number of retry attempts on failure. |
required |
user_agent
|
str
|
|
USER_AGENT
|
Returns:
| Type | Description |
|---|---|
tuple[Any, bytes]
|
tuple[Any, bytes]: The original tile and its PNG/JPEG bytes. |
Raises:
| Type | Description |
|---|---|
ConnectionError
|
If the tile cannot be fetched after all retries are exhausted. |
Examples:
- Fetch a single OpenStreetMap tile (network-dependent, hence
skipped under doctest):
>>> import mercantile >>> from cleopatra.tiles import fetch_single_tile, get_provider >>> tile = mercantile.Tile(0, 0, 0) >>> provider = get_provider("OpenStreetMap.Mapnik") >>> tile_obj, data = fetch_single_tile( # doctest: +SKIP ... tile, provider, timeout=10, retries=2 ... ) >>> from cleopatra.tiles import _looks_like_image >>> _looks_like_image(data) # doctest: +SKIP True - Tile failures raise
ConnectionErrorafter retries are exhausted:>>> import mercantile >>> from cleopatra.tiles import fetch_single_tile >>> from xyzservices import TileProvider >>> bad = TileProvider( ... name="bad", ... url="http://127.0.0.1:1/{z}/{x}/{y}.png", ... attribution="", ... ) >>> fetch_single_tile( # doctest: +SKIP ... mercantile.Tile(0, 0, 0), bad, timeout=1, retries=0 ... ) Traceback (most recent call last): ... ConnectionError: Failed to fetch tile z=0/x=0/y=0 ...
Source code in src/cleopatra/tiles.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
fetch_tiles(tiles, provider, max_workers=8, timeout=10, retries=2, user_agent=USER_AGENT)
#
Fetch tile images in parallel over HTTP.
Uses concurrent.futures.ThreadPoolExecutor for parallel
downloads. Each tile URL is constructed via the provider's
build_url(). A User-Agent header (cleopatra/<version> (+repo-url)
by default) is sent on every request so tile providers can attribute
the traffic — OpenStreetMap's usage policy requires an identifiable
agent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tiles
|
list
|
Tiles to fetch (each has |
required |
provider
|
Any
|
|
required |
max_workers
|
int
|
Maximum concurrent HTTP connections. |
8
|
timeout
|
int
|
Per-tile HTTP request timeout in seconds. |
10
|
retries
|
int
|
Per-tile retry count on failure. |
2
|
user_agent
|
str
|
|
USER_AGENT
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Mapping of Tile to PNG/JPEG bytes. |
Raises:
| Type | Description |
|---|---|
ConnectionError
|
If any tile cannot be fetched after all retries. |
Examples:
- Fetch a small tile grid in parallel (network-dependent, hence
skipped under doctest):
>>> import mercantile >>> from cleopatra.tiles import fetch_tiles, get_provider >>> tiles = list(mercantile.tiles(13.0, 52.4, 13.6, 52.6, zooms=10)) >>> provider = get_provider("OpenStreetMap.Mapnik") >>> data = fetch_tiles(tiles, provider, max_workers=4) # doctest: +SKIP >>> len(data) == len(tiles) # doctest: +SKIP True - Pass an empty list to short-circuit and get an empty dict:
Source code in src/cleopatra/tiles.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
get_provider(name=None)
#
Resolve an XYZ tile provider by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Dot-separated provider name (e.g. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
xyzservices.TileProvider: The resolved tile provider with |
Any
|
|
Raises:
| Type | Description |
|---|---|
ImportError
|
If the |
ValueError
|
If the provider name cannot be resolved. |
Examples:
- Resolve the default OpenStreetMap provider and inspect its URL template:
- Resolve a named provider via dot-path syntax:
- Invalid provider names raise
ValueError:
Source code in src/cleopatra/tiles.py
stitch_tiles(tile_data, tiles, zoom)
#
Stitch tile images into a single RGBA array.
Arranges tiles in a grid based on their x, y positions. The
tile size is read from the first decoded image (typically 256 or
512 px). Computes the geographic extent of the stitched image in
EPSG:3857 using mercantile.xy_bounds on the corner tiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tile_data
|
dict
|
Mapping of Tile to PNG bytes (from
|
required |
tiles
|
list
|
All tiles in the grid, defining grid dimensions. |
required |
zoom
|
int
|
Zoom level of the tiles. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
tuple[numpy.ndarray, tuple[float, float, float, float]]: The |
tuple[float, float, float, float]
|
stitched RGBA image with shape |
tuple[ndarray, tuple[float, float, float, float]]
|
|
tuple[ndarray, tuple[float, float, float, float]]
|
meters. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any tile bytes cannot be decoded as an image. |
Examples:
- Stitch a single synthetic tile into a 256x256 RGBA image:
>>> import io >>> import mercantile >>> from PIL import Image >>> from cleopatra.tiles import stitch_tiles >>> buf = io.BytesIO() >>> Image.new("RGBA", (256, 256), (255, 0, 0, 255)).save(buf, "PNG") >>> tile = mercantile.Tile(0, 0, 0) >>> image, extent = stitch_tiles({tile: buf.getvalue()}, [tile], 0) >>> image.shape (256, 256, 4) >>> image.dtype.name 'uint8' - The returned EPSG:3857 extent comes from
mercantile.xy_boundson the corner tiles:>>> import io >>> import mercantile >>> from PIL import Image >>> from cleopatra.tiles import stitch_tiles >>> buf = io.BytesIO() >>> Image.new("RGBA", (256, 256), (0, 255, 0, 255)).save(buf, "PNG") >>> tile = mercantile.Tile(0, 0, 0) >>> _, (w, s, e, n) = stitch_tiles({tile: buf.getvalue()}, [tile], 0) >>> w < e and s < n True - Invalid tile bytes raise
ValueError:
Source code in src/cleopatra/tiles.py
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 | |