0
# Contextily
1
2
A Python library for retrieving tile maps from the internet and adding them as basemaps to matplotlib figures or writing tile maps to disk as geospatial raster files. Contextily enables seamless integration of web-based map tiles with geospatial data visualization, supporting coordinate transformations between WGS84 (EPSG:4326) and Spherical Mercator (EPSG:3857) projections.
3
4
## Package Information
5
6
- **Package Name**: contextily
7
- **Language**: Python
8
- **Installation**: `pip install contextily` or `conda install contextily`
9
- **Requirements**: Python 3.9+
10
11
## Core Imports
12
13
```python
14
import contextily as ctx
15
```
16
17
For specific functionality:
18
19
```python
20
from contextily import add_basemap, bounds2img, Place
21
```
22
23
## Basic Usage
24
25
```python
26
import contextily as ctx
27
import matplotlib.pyplot as plt
28
import numpy as np
29
30
# Add a basemap to an existing matplotlib plot
31
fig, ax = plt.subplots(figsize=(10, 8))
32
33
# Example: plot some geographic data (in Web Mercator projection)
34
x = [-8239310, -8238310, -8237310] # Web Mercator X coordinates
35
y = [4969450, 4970450, 4971450] # Web Mercator Y coordinates
36
ax.scatter(x, y, s=100, c='red', alpha=0.8)
37
38
# Add contextily basemap
39
ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.HOT)
40
ax.set_xlim(min(x)-1000, max(x)+1000)
41
ax.set_ylim(min(y)-1000, max(y)+1000)
42
plt.show()
43
44
# Download and save map tiles as a raster file
45
west, south, east, north = -74.1, 40.7, -73.9, 40.8 # NYC bounds (lon/lat)
46
img, extent = ctx.bounds2raster(west, south, east, north,
47
'nyc_basemap.tiff', zoom=12, ll=True)
48
49
# Geocode a place and get its map
50
place = ctx.Place("Times Square, New York", zoom=15)
51
place.plot()
52
plt.show()
53
```
54
55
## Architecture
56
57
Contextily is organized around three main functional areas:
58
59
- **Tile Operations**: Core functionality for downloading, caching, and processing map tiles from web services
60
- **Plotting Integration**: matplotlib integration for adding basemaps to existing plots with proper coordinate handling
61
- **Place-based Mapping**: Geocoding and mapping functionality for location-based visualizations
62
63
The library integrates with the broader Python geospatial ecosystem through dependencies on rasterio (geospatial data), matplotlib (visualization), mercantile (tile math), and xyzservices (provider definitions).
64
65
## Capabilities
66
67
### Basemap Integration
68
69
Add web or local basemaps to existing matplotlib axes with automatic coordinate handling, provider support, and custom styling options.
70
71
```python { .api }
72
def add_basemap(ax, zoom='auto', source=None, interpolation='bilinear',
73
attribution=None, attribution_size=8, reset_extent=True,
74
crs=None, resampling=Resampling.bilinear, zoom_adjust=None,
75
**extra_imshow_args):
76
"""Add a basemap to matplotlib axes."""
77
78
def add_attribution(ax, text, font_size=8, **kwargs):
79
"""Add attribution text to matplotlib axes."""
80
```
81
82
[Basemap Integration](./basemap-integration.md)
83
84
### Tile Operations
85
86
Download map tiles for specified geographic bounds, with support for various zoom levels, tile providers, caching, and output formats.
87
88
```python { .api }
89
def bounds2img(w, s, e, n, zoom='auto', source=None, ll=False,
90
wait=0, max_retries=2, n_connections=1, use_cache=True,
91
zoom_adjust=None):
92
"""Download tiles and return as image array with extent."""
93
94
def bounds2raster(w, s, e, n, path, zoom='auto', source=None, ll=False,
95
wait=0, max_retries=2, n_connections=1, use_cache=True):
96
"""Download tiles and write to raster file."""
97
98
def howmany(w, s, e, n, zoom, verbose=True, ll=False):
99
"""Calculate number of tiles required for bounding box and zoom."""
100
101
def set_cache_dir(path):
102
"""Set custom cache directory for tile downloads."""
103
```
104
105
[Tile Operations](./tile-operations.md)
106
107
### Coordinate Transformation
108
109
Reproject and transform map tiles and images between different coordinate reference systems with support for various resampling methods.
110
111
```python { .api }
112
def warp_tiles(img, extent, t_crs='EPSG:4326', resampling=Resampling.bilinear):
113
"""Reproject Web Mercator basemap into any CRS."""
114
115
def warp_img_transform(img, transform, s_crs, t_crs, resampling=Resampling.bilinear):
116
"""Reproject image with given transform and CRS."""
117
```
118
119
[Coordinate Transformation](./coordinate-transformation.md)
120
121
### Place-based Mapping
122
123
Geocode locations by name and retrieve corresponding map tiles with integrated plotting capabilities for location-based visualizations.
124
125
```python { .api }
126
class Place:
127
"""Geocode a place by name and get its map."""
128
def __init__(self, search, zoom=None, path=None, zoom_adjust=None,
129
source=None, geocoder=None): ...
130
def plot(self, ax=None, zoom='auto', interpolation='bilinear',
131
attribution=None): ...
132
133
def plot_map(place, bbox=None, title=None, ax=None, axis_off=True,
134
latlon=True, attribution=None):
135
"""Plot map of given place (deprecated)."""
136
```
137
138
[Place-based Mapping](./place-mapping.md)
139
140
## Tile Providers
141
142
Contextily integrates with xyzservices to provide access to numerous tile providers:
143
144
```python { .api }
145
# Access via contextily.providers (re-exported from xyzservices.providers)
146
ctx.providers.OpenStreetMap.HOT # OpenStreetMap Humanitarian tiles
147
ctx.providers.Stamen.Toner # Stamen Toner tiles
148
ctx.providers.CartoDB.Positron # CartoDB light tiles
149
ctx.providers.ESRI.WorldImagery # ESRI satellite imagery
150
151
# Alternative direct import
152
from contextily import providers
153
providers.OpenStreetMap.HOT
154
```
155
156
Custom tile providers can be specified as URLs or TileProvider objects with `{x}`, `{y}`, `{z}` placeholders for tile coordinates.
157
158
## Common Types
159
160
```python { .api }
161
# From rasterio.enums
162
class Resampling(Enum):
163
"""Resampling algorithms for warping operations."""
164
bilinear = 'bilinear'
165
nearest = 'nearest'
166
cubic = 'cubic'
167
# ... other resampling methods
168
169
# From xyzservices
170
class TileProvider:
171
"""Tile provider configuration."""
172
def __init__(self, url: str, attribution: str = '', name: str = ''): ...
173
def build_url(self, x: int, y: int, z: int) -> str: ...
174
175
# Standard return types
176
ImageArray = numpy.ndarray # 3D array (height, width, bands) of image data
177
Extent = tuple[float, float, float, float] # (minX, maxX, minY, maxY) bounding box
178
```