Keyed basemaps#
Most basemaps in digitalearth need nothing from you — Map().basemap(), WebMap().basemap("CartoDark") and
InteractiveMap().tiles("CartoLight") all draw token-free public tiles. A keyed basemap is one the service
will not serve without a credential, so it needs two things you have to know in advance: an environment variable
to set, and the preset's own keywords.
Planet NICFI#
Planet's NICFI basemaps are ~4.77 m monthly mosaics of the tropics, free for non-commercial use under the NICFI terms. They are the first keyed preset.
from digitalearth import Map
m = Map(domain=(-60, -5, -55, 0)) # somewhere in the Amazon
m.basemap("Planet.NICFI", preset={"date": "2024-01"})
Every tier takes the preset the same way — as a preset dict, because on the static tier **kwargs belongs
to cleopatra and on the interactive tier it belongs to HoloViews' style options:
from digitalearth.web import WebMap
from digitalearth.interactive import InteractiveMap
WebMap().basemap("Planet.NICFI", preset={"date": "2024-01"})
InteractiveMap().tiles("Planet.NICFI", preset={"date": "2024-01"})
Keywords#
date(required) — the mosaic month,YYYY-MM. The monthly series starts at 2020-09; earlier periods are biannual and need an explicitmosaic.flavour—"analytic"(default, surface reflectance) or"visual". These are different Planet products, not a styling flag.mosaic— an explicit Planet mosaic id, overriding the one derived fromdateandflavour.
Write them in the preset dict, not loose: basemap("Planet.NICFI", date="2024-01") is refused with a
message pointing at the right form.
api_key= overrides the environment variable for one call. Passing it to a basemap that needs no credential
is an error rather than a no-op, so a call that looks authenticated always is.
Coverage#
NICFI publishes roughly 30°N–30°S. The static tier checks the extent it is about to draw against that band and refuses a basemap that would render blank after a round of failed fetches — it renders one fixed extent, so an uncovered basemap is a dead end. The web and interactive tiers do not check: their maps are pannable, so the opening view is not where the viewer stays.
Treat a saved map as a secret#
The credential is part of the tile URL. That is how an XYZ service authenticates a browser, so it is inherent rather than a bug — but it has consequences:
- A saved web map contains the key.
WebMap.basemap("Planet.NICFI").save("map.html")writes the tile URL, key and all, into the HTML. So does a rendered interactive map, which means a committed notebook with saved output carries it too. Do not commit, publish, or paste such a file. - The static tier does not have this exposure. It fetches tiles at plot time and embeds only the resulting image. It also silences the one cleopatra log record that would carry the URL.
- Do not run tile fetches at
DEBUGinto shared logs.
OGC services: WMS and WMTS#
The static tier tiles an OGC service through cleopatra's provider objects, passed to basemap() as they are.
WMSProvider requests one GetMap per Web Mercator tile; WMTSProvider requests GetTile on the service's
tile matrix set, by key-value parameters or by filling a RESTful URL template.
from cleopatra.basemap.ogc import WMSProvider, WMTSProvider
from digitalearth import Map
m = Map(crs=3857)
m.set_domain((3.3, 50.7, 7.3, 53.6)) # tiles cover what the axes shows
m.basemap(WMSProvider("https://example.org/geoserver/wms", "topp:states"))
m.basemap(WMTSProvider("https://example.org/wmts/{TileMatrix}/{TileRow}/{TileCol}.png", "basemap"))
A credential the service needs goes in the provider's extra_params — not in the service URL's query
string, which a figure does not record (see below).
What a figure records of an OGC basemap#
The provider object is held beside the layer — it is an engine object, and it carries whatever is in
extra_params. What the figure's description carries is the provider's own fields, every one of them except
extra_params, and url reduced to its scheme, host and path:
m.figure_spec.layers.get("bm").symbology.props["source"]
# {'ogc': 'wms', 'url': 'https://example.org/geoserver/wms', 'layers': 'topp:states',
# 'styles': '', 'version': '1.3.0', 'image_format': 'image/png', 'transparent': True,
# 'tile_size': 256, 'attribution': ''}
That is enough to rebuild the provider, so a figure saved to JSON and drawn again on this tier — through
Map.from_figure, or to_backend(spec, "matplotlib") — asks the same service for the same layer. Before
this was recorded, such a figure named no service at all and quietly drew the shared default basemap in its
place.
Replaying it on another tier is a separate matter and does not work today: WebMap.from_figure refuses a
static basemap layer outright — layer <id> (basemap) cannot be drawn by the web tier: its symbology records
none of ['opacity'] — and it does so whether the source was an OGC provider or a plain provider name. That is
the cross-tier basemap gap, not an OGC one.
extra_params deliberately does not travel, for the same reason an xyzservices apikey does not: a figure
is written to JSON and read back, and a token written into one leaks with it. So a replayed figure asks the
service without a credential. If the service needs one, it answers with its own error — which is the
honest outcome; pass the provider again, with its extra_params, to draw it authenticated.
A query string on the service URL does not travel either, whatever it holds. ?token=, ?api_key= and
?SERVICE_KEY= are ordinary ways for an OGC service to authenticate, and nothing in this tier can tell such a
parameter from a harmless one — so the whole query is dropped and only the base URL is recorded. The drop is
warned about by name, because the replayed figure will not carry it:
m.basemap(WMSProvider("https://example.org/geoserver/wms?token=s3cret", "topp:states"))
# UserWarning: the figure records this OGC service as 'https://example.org/geoserver/wms': its query string
# is dropped because a parameter there may be a credential, and a figure is written to JSON and read back.
# Dropped parameters: ['token']. Pass what the service needs through extra_params=, which is held beside the
# layer and never recorded.
So the two paths a credential can take into a provider — extra_params and the URL's query — both stay on
the object, and every field a figure records names the service. This is the same value _quiet_tile_urls
keeps out of the logs for keyed XYZ tiles, and it is now treated as a secret in both places.
Adding a preset#
Presets live in digitalearth.base.basemaps — engine-neutral definitions (URL
template, credential variable, attribution, coverage) that every backend resolves by name. A new one is a
factory returning a KeyedTileSource, registered in KEYED_BASEMAPS with its display spelling in
KEYED_BASEMAP_NAMES. The backends pick up its keywords automatically.
digitalearth.base.basemaps
#
Keyed-XYZ basemap definitions — the provider half of a tile basemap, with no renderer in sight.
Every backend can already render a tile source it is handed: the static tier passes an
xyzservices.TileProvider to cleopatra's GeoMixin.add_tiles glyph method (through its own
decoration.add_tiles wrapper), the web tier emits a MapLibre raster
source from a URL, and the interactive tier builds a GeoViews WMTS from either. What none of them owns is
the definition of a keyed service — one that needs a credential, resolves a time-varying dataset id, and
covers only part of the world. That definition is pure data, so it lives here and every backend reads the same
one.
A :class:KeyedTileSource carries a URL template, the environment variable its credential comes from, the
attribution to display, and an optional lon/lat bounding box. It hands out a resolved URL (tile_url) with
{z}/{x}/{y} left intact for whichever engine substitutes them, so nothing here imports a tile library —
the static backend is the only place an xyzservices.TileProvider is constructed.
Every backend names a preset the same way, and passes its keywords as a preset dict — loose keywords would
collide with cleopatra's on the static tier and with HoloViews' style options on the interactive one::
Map(domain=(-60, -5, -55, 0)).basemap("Planet.NICFI", preset={"date": "2024-01"})
WebMap().basemap("Planet.NICFI", preset={"date": "2024-01"})
InteractiveMap().basemap("Planet.NICFI", preset={"date": "2024-01"})
:func:get_keyed_basemap — the resolver the backends call — takes those keywords loose, since it has no
engine keywords of its own to collide with.
The unkeyed half of a basemap is a single constant: :data:DEFAULT_BASEMAP_PROVIDER, the provider a
backend uses when the caller named none. It lives here rather than in each tier so that a map drawn with no
explicit basemap looks the same whichever backend rendered it.
Planet NICFI is the first preset (:func:planet_nicfi): ~4.77 m monthly mosaics of the tropics, free for
non-commercial use under NICFI terms. Two things about it are worth knowing before you rely on it:
-
The credential ends up in the tile URL, and therefore in anything that records that URL. That is how an XYZ service authenticates a browser, so it is inherent rather than a bug — but it has consequences worth stating plainly:
-
A saved web map contains the key.
WebMap.basemap("Planet.NICFI").save("map.html")writes the tile URL, key and all, into the HTML. So does a rendered interactive map, which means a committed notebook with saved output carries it too. Treat such a file as a secret: do not commit it, publish it, or paste it into an issue. The static tier does not have this exposure — it fetches tiles at plot time and embeds only the resulting image. - A failed fetch can log it.
cleopatra.basemap.tileslogs the built URL atDEBUG, so the static backend suppresses that logger for the duration of a keyed fetch (seedigitalearth.static.builders.decoration). Do not otherwise run tile fetches atDEBUGinto shared logs. - A non-
http(s)URL is refused here, before it reaches a tile engine, because cleopatra reports that case by raising with the offending URL in the message — which the log suppression does not cover, since it is an exception rather than a log record. - The mosaic ids are Planet's, and they have varied. The pattern here matches Planet's published
normalized-analytic / visual naming, but the ids should be confirmed against Planet's
/mosaicsAPI for any date you depend on;mosaic=overrides the derived id when they differ.
KeyedTileSource
dataclass
#
A tile service that needs a credential, described without reference to any renderer.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
A display name, also used as the |
url_template |
str
|
The tile URL, containing |
attribution |
str
|
The text a map must display when using this service. |
credential_env |
str
|
The environment variable :meth: |
max_zoom |
int
|
The deepest zoom level the service serves. The web tier applies it to the MapLibre
source, so a viewer who zooms past it sees the last real tiles stretched rather than a wall
of 404s. The static tier passes it to |
bounds |
Extent | None
|
Optional lon/lat |
params |
Mapping[str, str]
|
Extra template placeholders to substitute, e.g. the resolved mosaic id. |
Examples:
- Describe a keyed service of your own and build its URL:
>>> from digitalearth.base.basemaps import KeyedTileSource >>> source = KeyedTileSource( ... name="Example.Imagery", ... url_template="https://tiles.example/{z}/{x}/{y}.png?key={api_key}", ... attribution="© Example", ... credential_env="EXAMPLE_TILE_KEY", ... ) >>> source.tile_url(api_key="abc123") 'https://tiles.example/{z}/{x}/{y}.png?key=abc123' - Extra placeholders come from
params, so a dataset id can vary per call:>>> from digitalearth.base.basemaps import KeyedTileSource >>> source = KeyedTileSource( ... name="Example.Dated", ... url_template="https://tiles.example/{layer}/{z}/{x}/{y}.png?key={api_key}", ... attribution="© Example", ... credential_env="EXAMPLE_TILE_KEY", ... params={"layer": "2024-01"}, ... ) >>> source.tile_url(api_key="abc123").split("?")[0] 'https://tiles.example/2024-01/{z}/{x}/{y}.png'
Source code in src/digitalearth/base/basemaps.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 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 | |
__hash__()
#
Hash on the same values :meth:__eq__ compares, with :attr:params as a sorted tuple.
The hash a frozen dataclass generates hashes the field tuple, and :attr:params is a
mappingproxy, which delegates to the dict underneath and is therefore unhashable. Without
this, a source could be compared but not put in a set, used as a dict key, or memoised.
Returns:
| Type | Description |
|---|---|
int
|
A hash consistent with equality. |
Source code in src/digitalearth/base/basemaps.py
__post_init__()
#
Wrap :attr:params so the frozen dataclass is actually immutable.
frozen=True stops the field being reassigned but says nothing about the dict it points at,
so source.params["mosaic"] = ... would otherwise edit a preset in place.
Source code in src/digitalearth/base/basemaps.py
check_bounds(extent)
#
Raise when extent lies entirely outside the service's coverage.
A partial overlap passes: a map spanning the tropics and beyond still shows tiles where they exist. Only a request with no overlap at all is refused, because that renders an empty basemap after a round of failed fetches.
Longitude is compared modulo 360, so a 0–360 domain (200°E, say) is understood as the same
place as -160, and a box crossing the antimeridian is treated as the two spans it really
covers rather than as an inverted one. Latitude is compared directly — it has no such convention.
That makes the two axes deliberately asymmetric: south > north is an error, while
west > east is read as a crossing rather than a mistake. The numbers cannot tell a swapped
longitude pair from a genuine Pacific extent, and refusing the crossing would break the real case
to catch the typo — so the crossing wins. A swapped tuple is caught by its latitudes instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extent
|
Extent | None
|
The area about to be drawn, as lon/lat |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
when the two boxes do not overlap, quoting both so the mismatch is obvious; or
when |
Examples:
- A tropical extent passes, and so does one that merely straddles the edge:
- An extent with no overlap at all is refused before anything is fetched:
- A domain expressed 0-360 names the same place as its negative counterpart, and passes:
- Metres are not degrees, and are reported as such rather than as missing coverage:
Source code in src/digitalearth/base/basemaps.py
365 366 367 368 369 370 371 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 | |
resolve_key(api_key=None)
#
Return the credential to use, preferring an explicit one over the environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str | None
|
A key supplied by the caller; |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The credential, stripped of surrounding whitespace — a trailing newline from |
str
|
|
str
|
module. |
Raises:
| Type | Description |
|---|---|
ValueError
|
when no key was passed and the environment variable is unset or empty, naming the variable so the caller knows what to set. |
Examples:
- An explicit key is returned as given:
- With nothing to read, the error names the variable to set:
>>> import os >>> from digitalearth.base.basemaps import KeyedTileSource >>> source = KeyedTileSource( ... name="Example", ... url_template="https://t/{z}/{x}/{y}.png?key={api_key}", ... attribution="© Example", ... credential_env="EXAMPLE_TILE_KEY_UNSET", ... ) >>> os.environ.pop("EXAMPLE_TILE_KEY_UNSET", None) and None >>> try: ... source.resolve_key() ... except ValueError as err: ... print(str(err).split(",")[0]) Example needs a credential: set the EXAMPLE_TILE_KEY_UNSET environment variable
Source code in src/digitalearth/base/basemaps.py
tile_url(api_key=None)
#
Return the tile URL with the credential and any preset placeholders filled in.
{z}/{x}/{y} are deliberately left in place: MapLibre, GeoViews and xyzservices each
substitute them at fetch time, so the same string serves all three backends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str | None
|
A key supplied by the caller; |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The URL template, ready for a tile engine. |
Raises:
| Type | Description |
|---|---|
ValueError
|
when no credential is available (see :meth: |
Examples:
- The credential is filled in and the tile coordinates are left for the engine:
- The preset's own placeholders are resolved too, so nothing is left templated but the tiles:
Source code in src/digitalearth/base/basemaps.py
planet_nicfi(date, *, flavour='analytic', mosaic=None)
#
Build the Planet NICFI basemap for one monthly mosaic.
NICFI (Norway's International Climate and Forest Initiative) funds Planet to publish ~4.77 m mosaics of
the tropics, free for non-commercial use. Monthly mosaics run from 2020-09; earlier periods are biannual
and named differently, so pass mosaic= for those.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
date
|
str
|
The mosaic month as |
required |
flavour
|
str
|
|
'analytic'
|
mosaic
|
str | None
|
An explicit Planet mosaic id, overriding the one derived from |
None
|
Returns:
| Type | Description |
|---|---|
KeyedTileSource
|
The configured source. The credential is not read here — only when a URL is built. |
Raises:
| Type | Description |
|---|---|
ValueError
|
when |
Examples:
- Build a source and see the mosaic id it derived:
- The visual flavour is a different Planet product, not a styling flag:
- A malformed month is refused rather than silently requesting a mosaic that cannot exist:
- A month before the monthly series says so, and points at the way to reach those periods:
>>> from digitalearth.base.basemaps import planet_nicfi >>> try: ... planet_nicfi("2019-06") ... except ValueError as err: ... print(str(err).split(";")[0]) NICFI monthly mosaics start at 2020-09 >>> older = planet_nicfi( ... "2019-06", mosaic="planet_medres_normalized_analytic_2019-06_2019-11_mosaic" ... ) >>> older.params["mosaic"] 'planet_medres_normalized_analytic_2019-06_2019-11_mosaic'
See Also
digitalearth.base.basemaps.get_keyed_basemap: resolve this by name from a basemap() call.
Source code in src/digitalearth/base/basemaps.py
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 545 546 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 | |
get_keyed_basemap(name, **kwargs)
#
Resolve a keyed basemap preset by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The preset name, e.g. |
required |
**kwargs
|
object
|
The preset's own keywords — for NICFI, |
{}
|
Returns:
| Type | Description |
|---|---|
KeyedTileSource
|
The configured :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
when |
TypeError
|
when a keyword is missing or misspelled — re-raised naming the preset the caller asked for and the keywords it takes, since the factory behind it is an implementation detail. |
Examples:
- Resolve NICFI by the name a
basemap()caller would type: - An unknown name says what is available:
Source code in src/digitalearth/base/basemaps.py
is_keyed_basemap(name)
#
Whether name names a keyed basemap preset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
object
|
The value a caller passed as a basemap; anything not a string is not a preset name. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Examples:
- The preset name is matched case-insensitively:
- An ordinary basemap name, a URL or a built provider object is not one: