Map site¶
A self-contained, archivable map site built from one run's outputs.
build_site(run_dir) writes <run_dir>/site/ — an HTML page, a vendored MapLibre front end,
PMTiles tilesets and a copy of the run manifest. It opens with a Python interpreter and nothing
else, reaches no network, and needs no API key.
See lczkit.viz.site for what it contains and why, and lczkit.viz.serve for why a local server
is required rather than a bare file:// open.
A static web map written to output/lczkit/<run_id>/site/. It is drawn by MapLibre GL, a browser
mapping library, reading PMTiles — a single-file tile archive served over ordinary HTTP range
requests, so no tile server is needed. The tiles are built by tippecanoe, a command-line tool
installed by the lczkit[viz] extra and invoked as a subprocess. The front end is vendored, so the
site depends on nothing remote.
The site opens with no network and no software the user must install. It is served by its own
bundled serve.py, standard library only, over loopback.
file:// does not work, and that is not fixable
PMTiles reads byte ranges through fetch, and the Fetch standard leaves file: URLs
unhandled — Chrome and Firefox both return a network error. Every built site ships a
README.md giving the working command, because opening index.html is the first thing a
recipient tries and it is the thing that fails.
The basemap is the run's own cleaned Overture water and streets: already cached for the bbox,
ODbL-attributable, and the same linework the classification was computed from. Online raster grounds
are available opt-in via VizConfig.online_basemaps, one or several, offered to the reader as a
dropdown; with it empty the emitted site names no remote host anywhere, and that default is enforced
by a test rather than promised in prose. Two of the providers need an API key, which is written into
style.json and therefore travels with the built site — see VizConfig.maptiler_key for what that
does and does not bound.
lczkit.viz.site
¶
build_site(run_dir) — a self-contained, archivable map of one run.
The deliverable is a directory that a reader can copy, open with a Python interpreter and nothing else, and still read in ten years: no CDN, no basemap API key, no live kernel, no build step. It is a paper supplement, not a dev tool.
It is a pure transform of run outputs. Every number it draws — labels, parameters, the 17-way
distance vector, the classification breaks the choropleths bin on — was decided by the run and read
back from units.parquet, units_viz.parquet and manifest.json. Nothing here computes a
parameter or a quantile, and nothing here reads input/. That is why write_run gained a layers=
argument: the basemap and the extrusions are drawn from geometry the run persisted, so an archived
run directory rebuilds its own site with no access to the source data.
The one thing that is measured rather than assumed is the attribute split. MVT repeats a
feature's whole attribute table in every tile at every zoom, so at metropolitan scale a 38-column
unit table costs more to tile than 892 000 building footprints — 115 MB against 61 MB. The render
attributes therefore ride at every zoom and the rest ride once, at the maximum zoom, where the only
thing that reads them is a click. Both tilesets and the choice between them are recorded in
site.json.
ASSETS_DIR
module-attribute
¶
The vendored front end, shipped inside the wheel.
This is the one place in the package that resolves a path from __file__. The rule against that
is about locating data relative to the source tree, because data lives under DATA_DIR. These
are package resources — JavaScript and HTML that ship in the wheel — and there is no other way to
find a file inside an installed package.
BASEMAP_LAYERS
module-attribute
¶
Context layers drawn under the units, in draw order.
Tiled as geometry alone. They are painted flat, carry no labels, and answer no click, so every
attribute on them is dead weight — and it is not small dead weight: Overture's id is a
32-character GERS string, repeated once per feature per zoom level. Stripping the columns took a
9 km² basemap from 6.43 MB to 4.00 MB, for pixels that look identical.
SiteReport
dataclass
¶
SiteReport(site_dir: Path, tilesets: list[TilesetReport] = list(), n_units: int = 0, render_columns: list[str] = list(), detail_columns: list[str] = list(), skipped: dict[str, str] = dict())
What build_site wrote, and how.
skipped
class-attribute
instance-attribute
¶
Anything the site could not draw, and why — an absent layer, a detail tileset declined for size. Recorded rather than silently omitted, so a missing basemap is distinguishable from a basemap that failed.
as_dict
¶
The report as JSON-ready primitives, for the run manifest's site block.
Source code in src/lczkit/viz/site.py
build_site
¶
build_site(run_dir: Path | str, *, config: VizConfig | None = None) -> SiteReport
Write <run_dir>/site/ from the run's own outputs, returning what was built.
config defaults to the viz section recorded in the run's manifest, so rebuilding a site from
an archived run reproduces the same tilesets without the caller having to restate the settings.
Source code in src/lczkit/viz/site.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 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 | |
distance_columns_present
¶
The 17-way distance columns among columns, in prototype order.
Exposed so the sidebar's bar chart and the tests agree on the ordering without either re-deriving it from a column name pattern.
Source code in src/lczkit/viz/site.py
Tilesets¶
Attributes, not geometry, are what a unit tileset costs. MVT repeats a feature's whole attribute table in every tile at every zoom, so at 172 181 units a 38-column table costs more to tile than 892 000 building footprints. Hence the render/detail split: render attributes at every zoom, the rest once at maximum zoom where only a click reads them.
lczkit.viz.tiles
¶
Vector tiles: GeoParquet in a GeoDataFrame, PMTiles out, tippecanoe in between.
The chain is GeoParquet -> FlatGeobuf via pyogrio -> tippecanoe -> PMTiles. Routing through
GeoJSON instead is dramatically slower at buildings scale and is not used.
tippecanoe is a subprocess, never linked or vendored, and it is an optional extra (lczkit[viz])
so that the classification pipeline does not acquire a 36 MB binary it never calls.
The binary is located through the installed package, not PATH. The tippecanoe PyPI wheel
ships the real upstream binaries under tippecanoe.BIN_DIR, and resolving them that way means the
version tippecanoe reports is the version the lockfile pinned. A PATH lookup would silently prefer
whatever a system package manager had put there, which is exactly the reproducibility hole the
manifest exists to close.
Every invocation is recorded verbatim, argv and all, in the site manifest. A recorded command line
is the only way a reader can
tell a tile that is empty because the data was empty from one that is empty because
--drop-densest-as-needed threw it away.
tippecanoe's thread count is capped, and that is a bug workaround with a measurement behind it.
On this project's 256-core node every tileset failed with Internal error: 745 shards not a power
of 2, raised from tippecanoe's radix sort while reordering geometry. Sweeping the thread count
showed 8, 16, 32, 48, 64, 96, 128 and 192 all succeed and only 256 fails, so the shard arithmetic
breaks at the top of the range rather than at a particular value. Decoding two tilesets built at 8
and 128 threads showed identical tile content — the only bytes that differ are the output
filename tippecanoe records in its own metadata — so capping costs nothing but wall time, and tile
generation is minutes rather than hours. Like the multiprocessing start-method choice in
lczkit.cleaning.streets, this is invisible on a laptop and fatal on a many-core machine.
TIPPECANOE_EXTRA
module-attribute
¶
Install target named in the error when the binary is missing. One string, so the message and the packaging cannot drift apart.
MAX_THREADS
module-attribute
¶
Ceiling on tippecanoe's worker threads. See the module docstring: above roughly this, the gain
is nil and at 256 the shard arithmetic fails outright. An operator who has already set
TIPPECANOE_MAX_THREADS keeps their value — this is a floor under a broken default, not a policy
about how many cores anyone may use.
TippecanoeMissingError
¶
Bases: RuntimeError
Raised when a tileset is requested but tippecanoe is not installed.
TilesetReport
dataclass
¶
TilesetReport(name: str, path: Path, layers: tuple[str, ...], n_features: int, size_bytes: int, min_zoom: int, max_zoom: int, argv: tuple[str, ...], version: str, max_threads: str, seconds: float)
One tileset, and exactly how it was produced.
argv
instance-attribute
¶
The full command line, including the binary's resolved path.
max_threads
instance-attribute
¶
The TIPPECANOE_MAX_THREADS the run used. Recorded because it is a workaround for a
machine-dependent failure, and a reader comparing two runs should be able to see it.
as_detail
¶
One tileset's row for the manifest: what was built, how big, and at which zooms.
Source code in src/lczkit/viz/tiles.py
tippecanoe_binary
¶
Path to the pinned tippecanoe executable, or a message saying how to get one.
Source code in src/lczkit/viz/tiles.py
tippecanoe_available
¶
Whether a tileset can be built here. For skipping tests, not for silently degrading.
tippecanoe_version
¶
The version string the pinned binary reports, for the manifest.
Source code in src/lczkit/viz/tiles.py
tippecanoe_environment
¶
The subprocess environment, with the thread ceiling applied unless already set.
Source code in src/lczkit/viz/tiles.py
write_flatgeobuf
¶
Write frame to FlatGeobuf in EPSG:4326, returning the feature count.
Reprojected here rather than by the caller because tippecanoe reads coordinates as lon/lat and has no CRS machinery of its own: handing it the projected CRS every other stage of this package computes in would produce a tileset covering a few square metres off the coast of Africa, and it would do so without complaining.
Source code in src/lczkit/viz/tiles.py
build_tileset
¶
build_tileset(layers: dict[str, GeoDataFrame], destination: Path, *, name: str, min_zoom: int, max_zoom: int, drop_densest: bool = True, simplification: int | None = None) -> TilesetReport
Tile one or more named layers into a single .pmtiles at destination.
Several layers in one tileset rather than one file each: a basemap's water, land use and streets are always drawn together, and MapLibre re-requests tiles per source, so splitting them would triple the request count for tiles that always arrive together anyway.
drop_densest is --drop-densest-as-needed, which drops features from tiles that would blow
the size limit rather than emitting a tile a browser cannot parse. It is on for everything
except the click-detail tileset, where a dropped feature is a unit whose sidebar would silently
come up empty — there the right failure is a large tile, not a missing one.
simplification is passed only for the basemap. Context geometry carries no measurement, so it
is the one thing in the site that may be coarsened for display; the unit and building tilesets
keep tippecanoe's faithful default, because their vertices are the run's own output.
Source code in src/lczkit/viz/tiles.py
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 | |
copy_tree
¶
Copy a vendored asset directory into a site, replacing whatever was there.
Style¶
lczkit.viz.style
¶
The MapLibre style, built in Python from a run manifest.
Why the style is generated here and not in JavaScript. The site never recomputes a parameter or
a quantile — it renders what the run already decided. Building the style in Python makes that
constraint testable: a test can assert that every
LCZ colour equals classify.labels.legend() and that every choropleth's class boundaries are the
manifest's own breaks, with nothing derived at draw time. The same assertions written against
app.js would be assertions about a string.
It also keeps the browser code to what only the browser can do — pan, click, and toggle. app.js
loads style.json, and switching a view calls setPaintProperty on one already-loaded layer, so
no view change ever refetches a tile.
No glyphs and no sprite. MapLibre fetches both over HTTP when a style names them, and a
style with neither is a style that cannot reach for anything outside the directory. The cost is that
the map carries no text labels; for a class map with a legend that is a small price, and it is the
difference between a directory that renders in ten years and one that renders until a font endpoint
moves.
NODATA_COLOUR
module-attribute
¶
Units with no value for the active variable. Deliberately not a ramp colour and not the
background: a null parameter is a real and reportable state — aspect_ratio is null wherever no
street reaches a building — and painting it as though it were a low value would hide that.
UNITS_FILL_LAYER
module-attribute
¶
The single layer every view paints. One layer rather than one per variable so that switching a view is a paint change over tiles already in memory rather than a refetch.
RASTER_BASEMAP_PREFIX
module-attribute
¶
Leading string of every remote raster's source and layer id, which are the same string.
Only raster_id may use it, and nothing may match on it. The site's own linework layers are
also basemap-*, and collecting them by prefix once put the remote raster into the choice that
exists precisely to avoid the network. Both sets are built from the decision that separates them —
see metadata.lczkit.basemap below.
GROUP_CONFIDENCE
module-attribute
¶
Selector groups, in the order selector_rank already puts their members in.
The groups are named here rather than derived in the front end for the same reason the labels are: the ordering is a decision this package made and a test asserts, and a second copy of it in JavaScript would be a second place for it to be wrong.
REGISTRY_LABELS
module-attribute
¶
ParameterSpec.label for every parameter this version of the package knows about.
Consulted when a run's own manifest carries no label, which older runs do — including the three published ones. Without it, rebuilding an archived site with a newer lczkit would keep showing the labels the rebuild was meant to fix.
display_label
¶
The human-readable name for column, or a readable fallback.
parameters maps a column to the label the run recorded. A run written before labels
existed carries none, so the packaged registry answers next — otherwise rebuilding an archived
run's site with a newer lczkit would still show "height of roughness elements m", and the three
published sites are exactly such runs.
That is not the site recomputing something the run decided. A display name is presentation, not
a measurement: the values, the breaks and the colours still come from the manifest, and
DISPLAY_LABELS and HEIGHT_SOURCE_LABELS below already answer from the package. The run's own
label still wins where it has one, so a manifest that named a column differently keeps its name.
Source code in src/lczkit/viz/style.py
selector_group
¶
Which selector group column belongs to. Follows selector_rank, not a second ordering.
Source code in src/lczkit/viz/style.py
selector_rank
¶
Where column sits in the layer selector.
The order is chosen here, not inherited. build_views used to emit views in whatever order
the manifest's breaks arrived in, which is writer.py's continuous — every numeric column
in DataFrame order. That is incidental, and it put height provenance last, below ten urban
canopy parameters. height_completeness and
height_tier_fractions are first-class layers and sit second in the selector, above the UCP
choropleths. They are the visible form of what this package reports — Cairo at 0.4% tier-1
coverage against Berlin at 68.9% is the comparison the site exists to make legible.
Ties keep the manifest's order, so a parameter added later lands among the UCPs without needing an edit here.
Source code in src/lczkit/viz/style.py
ramp_colours
¶
n colours sampled evenly from SEQUENTIAL_RAMP, endpoints included.
Source code in src/lczkit/viz/style.py
lcz_colour_expression
¶
A match expression mapping LCZ integer codes to the Demuzere colours.
Read from classify.labels, which a test already asserts equal to the committed reference
table — so the map's colours and the output raster's colours cannot drift apart.
to-number is load-bearing, not defensive. tippecanoe's FlatGeobuf reader emits every
integer attribute as a string — measured at int16, int32, int64 and uint8, while float64 comes
through as a number. lcz_primary is the only integer column the site renders, so a match on
the raw value found no label, every cell fell through to NODATA_COLOUR, and the default view
of every published site was a field of blank grey squares. Coercing here rather than casting
the column to float in write_flatgeobuf keeps a class code an integer everywhere it is read,
and keeps the fix at the one place that depends on the type.
A missing value coerces to 0, which matches no label and so still takes NODATA_COLOUR.
Source code in src/lczkit/viz/style.py
choropleth_expression
¶
A step expression over the run's precomputed break points.
breaks are the k + 1 boundaries output.breaks wrote, so the interior boundaries are
breaks[1:-1] and the number of classes is one more than that. Nothing is quantised, binned or
quantiled here; the boundaries arrive already decided.
Guarded by has so a unit missing the parameter paints as missing rather than as the lowest
class — the distinction the null-parameter policy exists to preserve.
Source code in src/lczkit/viz/style.py
build_views
¶
build_views(breaks: list[dict[str, Any]], columns: list[str], parameters: list[dict[str, str]]) -> list[dict[str, Any]]
One view per renderable variable, LCZ first and height provenance second.
A variable earns a view only if it is both in the tiles (columns) and has breaks in the
manifest. Anything else would be a menu entry that paints nothing.
The continuous views are ordered by selector_rank rather than by the order the breaks arrive
in — see that function for why the inherited order was wrong.
Source code in src/lczkit/viz/style.py
raster_id
¶
raster_id(entry: BasemapProvider) -> str
The style id of entry's source and layer, which are deliberately the same string.
One id per provider, because each carries its own tile size and maximum zoom and a MapLibre source carries both — so several grounds cannot share one source whose tiles are swapped.
Source code in src/lczkit/viz/style.py
build_style
¶
build_style(manifest: dict[str, Any], *, columns: list[str], bounds: tuple[float, float, float, float], centre: tuple[float, float], has_detail: bool, basemap_layers: tuple[str, ...], has_buildings: bool, online_basemaps: Sequence[str] = (), maptiler_key: str | None = None) -> dict[str, Any]
The complete style document, ready to be written as style.json.
columns is what the unit tileset actually carries, so a manifest listing breaks for a column
that did not make it into the tiles produces no menu entry rather than a blank map. Likewise
basemap_layers is what the basemap tileset actually contains: a style layer naming a
source-layer that is not in the tileset renders nothing and reports nothing, which is the
hardest kind of blank map to diagnose.
online_basemaps names remote raster grounds to add beneath everything, in picker order. They
are the only thing in this document that reaches outside the directory, and there are none
unless a caller asks — see lczkit.viz.basemaps for why that default is load-bearing rather
than cautious. Each gets its own source and layer rather than sharing one whose tiles are
swapped: tile size and maximum zoom differ per provider and a source carries both.
Source code in src/lczkit/viz/style.py
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 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 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 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 | |
Basemaps¶
Each provider records its licence and its usage terms, and the CLI prints them when one is selected — OpenStreetMap's own tile service in particular is a donated resource rather than a commercial one, and its usage policy applies to whoever opts in.
lczkit.viz.basemaps
¶
Optional online raster base layers, and the attribution each one obliges the site to carry.
Read this before enabling one. A built site opens with no network and no software the reader must install, and stays valid years from now. That is not a preference — it is what makes a site archivable beside a paper. Everything here breaks it, so nothing here is on by default.
VizConfig.online_basemaps is empty unless a caller asks, and with it empty the emitted site
contains no external reference at all — a test asserts exactly that, and a second test asserts that
when one is configured the only file mentioning a remote host is style.json. The front end
treats each raster as a layer that may fail: tiles that do not load leave every other layer working
and say so, rather than producing a blank map.
Configuring several is normal and costs nothing until one is chosen: each becomes its own hidden source and layer, and the page's base picker switches between them. Sizes and zoom limits differ per provider, which is why they cannot share one source whose tiles are swapped at runtime.
Two providers need an API key, and the key ships in the site. MapLibre fetches tiles from the
browser, so style.json carries the key in plain text and anyone holding the directory holds the
key. It is deliberately kept out of the run manifest — see VizConfig.maptiler_key — but that
bounds the exposure rather than removing it, and a key used this way should be origin-restricted at
the provider.
A site built with one of these is not archival. The provider outlives the run only as long as it chooses to. The run's own Overture linework stays available in the same site and remains the default ground, so a reader who opens an old site offline still sees the geometry the classification was computed from.
Tile usage policies are the caller's obligation, not this module's. Each provider records its licence and the terms in its own docstring. The OpenStreetMap Foundation's tile servers in particular are a donated resource with an explicit usage policy: fine for reading a map, not for bulk or automated fetching, and a heavy consumer is expected to run its own tiles.
OPENSTREETMAP
module-attribute
¶
OPENSTREETMAP = BasemapProvider(key='osm', label='OpenStreetMap', tiles=('https://tile.openstreetmap.org/{z}/{x}/{y}.png',), attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', licence='ODbL 1.0 (data), CC-BY-SA 2.0 (tiles)', max_zoom=19, terms='The OSMF tile servers are a donated resource under an explicit usage policy: acceptable for a person reading a map, not for bulk or automated downloading. A site that will be opened often should point at its own tiles instead.', hosts=('tile.openstreetmap.org',))
The obvious choice, and the one to be most careful with — see terms.
CARTO_POSITRON
module-attribute
¶
CARTO_POSITRON = BasemapProvider(key='carto-positron', label='Carto Positron (light)', tiles=('https://a.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', 'https://b.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', 'https://c.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png'), attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attributions">CARTO</a>', licence='ODbL 1.0 (data), CC-BY 3.0 (style)', max_zoom=20, dark=False, hosts=('a.basemaps.cartocdn.com', 'b.basemaps.cartocdn.com', 'c.basemaps.cartocdn.com'))
Deliberately muted, which is the point: a basemap under a choropleth should not compete with it. Light, so the front end raises the unit fill's opacity to keep the LCZ palette readable over it.
CARTO_DARK_MATTER
module-attribute
¶
CARTO_DARK_MATTER = BasemapProvider(key='carto-dark', label='Carto Dark Matter', tiles=('https://a.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 'https://b.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 'https://c.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png'), attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://carto.com/attributions">CARTO</a>', licence='ODbL 1.0 (data), CC-BY 3.0 (style)', max_zoom=20, dark=True, hosts=('a.basemaps.cartocdn.com', 'b.basemaps.cartocdn.com', 'c.basemaps.cartocdn.com'))
The best fit for this site's palette, which was built for a light figure on a dark ground.
ESRI_WORLD_IMAGERY
module-attribute
¶
ESRI_WORLD_IMAGERY = BasemapProvider(key='esri-satellite', label='Esri World Imagery (satellite)', tiles=('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',), attribution='Imagery © <a href="https://www.esri.com">Esri</a>, Maxar, Earthstar Geographics, and the GIS User Community', licence='Esri Terms of Use — free to use with attribution', max_zoom=19, terms="Esri's World Imagery service is free to use in a map that carries its attribution, which this site does. It is not a bulk imagery source and Esri may rate-limit or withdraw it.", hosts=('server.arcgisonline.com',))
Satellite imagery without a key, and the reason this package ships no Google tiles.
Google's mt*.google.com/vt endpoint is undocumented and using it outside a Google Maps API breaks
their terms of service, so it cannot carry a licence string and has no place in a table whose point
is that every ground records one.
MAPTILER_HYBRID
module-attribute
¶
MAPTILER_HYBRID = BasemapProvider(key='maptiler-hybrid', label='MapTiler Satellite Hybrid', tiles=('https://api.maptiler.com/maps/hybrid/256/{z}/{x}/{y}.jpg?key={key}',), attribution='© <a href="https://www.maptiler.com/copyright/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', licence='MapTiler Cloud terms — requires an API key', max_zoom=20, terms="Requires a MapTiler API key, which is written into the site's style.json in plain text because the browser fetches the tiles. Anyone given the site directory has the key: restrict it by origin in the MapTiler console, or hand out a site built without it.", hosts=('api.maptiler.com',), requires_key=True, key_name='MAPTILER_API_KEY')
Satellite imagery with roads and place names over it — the closest thing here to what people mean by "Google satellite", from a provider whose terms permit it.
MAPTILER_TOPO
module-attribute
¶
MAPTILER_TOPO = BasemapProvider(key='maptiler-topo', label='MapTiler Topo', tiles=('https://api.maptiler.com/maps/topo-v2/256/{z}/{x}/{y}.png?key={key}',), attribution='© <a href="https://www.maptiler.com/copyright/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors', licence='MapTiler Cloud terms — requires an API key', max_zoom=22, terms="Requires a MapTiler API key, which is written into the site's style.json in plain text because the browser fetches the tiles. Anyone given the site directory has the key: restrict it by origin in the MapTiler console, or hand out a site built without it.", hosts=('api.maptiler.com',), requires_key=True, key_name='MAPTILER_API_KEY')
Terrain shading and contours. The one ground here that shows relief, which is the context an LCZ map most often lacks: a valley floor and a hillside classify alike and behave differently.
DEFAULT_BASEMAP_KEYS
module-attribute
¶
DEFAULT_BASEMAP_KEYS: tuple[str, ...] = tuple(key for key, entry in PROVIDERS.items() if not entry.requires_key)
What lczkit run and lczkit site build offer when the caller names nothing.
Derived from requires_key rather than listed, because that is the rule. A ground that needs no
key costs a reader nothing to be offered and publishes no secret; a keyed one writes an API key into
the built site, which is a decision someone has to make on purpose. A keyless provider added later
joins this set by being keyless, and a keyed one cannot join it by being forgotten.
This is a command-line default, not the library's. VizConfig.online_basemaps is still empty by
default, so build_site() and a rebuild of an archived manifest reach no network unless told to —
that is the property the no-external-reference test pins, and it is unchanged. A site built by the
command line names these tile hosts in its style.json; a site built through the library names
none. Pass --basemap none for an archival build.
BasemapProvider
dataclass
¶
BasemapProvider(key: str, label: str, tiles: tuple[str, ...], attribution: str, licence: str, max_zoom: int = 19, tile_size: int = 256, terms: str = '', dark: bool = False, hosts: tuple[str, ...] = tuple(), requires_key: bool = False, key_name: str = '')
One remote raster tile source, with everything the style and the page need to use it.
tiles
instance-attribute
¶
Tile URL templates. More than one is a subdomain rotation.
attribution
instance-attribute
¶
Shown by MapLibre's attribution control. Required by every provider here, and the reason the control is switched on whenever a raster basemap is configured.
terms
class-attribute
instance-attribute
¶
The usage constraint a caller takes on by selecting this provider.
dark
class-attribute
instance-attribute
¶
Whether the tiles are dark. The unit fill and the LCZ palette are built for a dark ground, so a light basemap needs the fill drawn more opaquely to stay legible.
hosts
class-attribute
instance-attribute
¶
The hosts this provider contacts, so a test can assert the site reaches nothing else.
requires_key
class-attribute
instance-attribute
¶
Whether tiles carry a {key} placeholder that must be filled before the site is written.
lczkit.viz.style substitutes it and raises when it cannot, because the failure is otherwise
silent: a tile URL still containing {key} is a well-formed URL that returns 403 per tile, and
MapLibre reports that as an empty basemap rather than as a configuration error.
key_name
class-attribute
instance-attribute
¶
The environment variable holding this provider's key, named in the error when it is absent.
Documentation only — nothing in this module reads the environment. Every environment read
happens in the config layer, so lczkit.config.maptiler_key() is what actually resolves
it.
provider
¶
provider(key: str) -> BasemapProvider
The provider called key, or a KeyError naming the ones that exist.
Source code in src/lczkit/viz/basemaps.py
tile_urls
¶
tile_urls(entry: BasemapProvider, api_key: str | None) -> list[str]
entry's tile templates with {key} filled in, or a ValueError naming the variable.
{z}, {x} and {y} are left alone — MapLibre substitutes those per tile, and only {key}
is replaced here. Raising when a keyed provider has no key is the point of the function: an
unsubstituted template is a well-formed URL that 403s on every tile, so the site would build
cleanly and show an empty basemap with nothing anywhere saying why.
Source code in src/lczkit/viz/basemaps.py
external_hosts
¶
Every host any provider can contact.
Exists so tests/test_viz_site.py can assert that a site configured with one of these reaches
that provider and nothing else, rather than dropping the no-external-reference guarantee.
Source code in src/lczkit/viz/basemaps.py
Server¶
lczkit.viz.serve
¶
A standard-library static server that answers HTTP Range requests.
python serve.py [--port 8000] [--directory .]
This file is copied verbatim into every site directory, which is why it imports nothing outside the standard library and takes no arguments the site does not already know. A reader who receives the directory years from now needs a Python interpreter and nothing else.
Why it exists at all. PMTiles works by asking for byte ranges of one file over HTTP, and
http.server.SimpleHTTPRequestHandler does not implement Range — it answers 200 with the whole
body, every time, for every tile. A 60 MB tileset would then be re-sent for each of hundreds of tile
reads. So the forty lines below are the difference between a site that loads and one that does not,
and they are cheaper than taking on a web-server dependency for them.
Why a server is needed rather than opening index.html directly. The Fetch standard leaves
file: URLs unhandled, so fetch() against one returns a network error in both Chrome and Firefox,
and PMTiles is built on fetch. Nothing here reaches the network: the server is local, the assets
are vendored, and the map has no basemap API key and no CDN link. "Offline" is satisfied; "no
process at all" is not achievable with range-requested tiles in a current browser.
RangeRequestHandler
¶
Bases: SimpleHTTPRequestHandler
SimpleHTTPRequestHandler plus single-range bytes= support and the right MIME types.
end_headers
¶
Advertise range support on every response, then close the header block.
Source code in src/lczkit/viz/serve.py
send_head
¶
Answer a Range request with 206 Partial Content, or defer to the base class.
This is the whole reason the site ships its own server. SimpleHTTPRequestHandler has
no range support, so it would re-send an entire tileset per tile — and PMTiles reads a
map by issuing one ranged read per tile.
A request with no Range header, or for a directory, goes to the base class untouched.
A start past the end of the file gets 416 with a Content-Range stating the real size,
which is what lets a client that guessed wrong recover. Sets _remaining for copyfile.
Source code in src/lczkit/viz/serve.py
copyfile
¶
Write exactly the bytes send_head promised, or the whole file if it promised none.
_remaining is cleared before the loop rather than after, so a connection that drops
part-way cannot leave a stale byte count for the next request on the same handler.
Source code in src/lczkit/viz/serve.py
serve
¶
Serve directory until interrupted.
Source code in src/lczkit/viz/serve.py
main
¶
Command-line entry point: serve the directory this file sits in, over loopback.
Defaulting --directory to the script's own parent is what makes a built site openable by
python serve.py from inside it, with no arguments and nothing installed.