Skip to content

transitlos.map.build

Lightweight, tile-based folium map builder shared by every city.

Uses geohierarchy.maps.folium.render.HierarchyMap/MultiHierarchyMap as the tile-based rendering backbone (never raw embedded GeoJSON): one zoom-banded level per H3 resolution (or, for US/census cities, per census geometry level) so only one resolution's tiles are ever fetched at a time.

Three kinds of layer
  • Shape (mutually exclusive, native Leaflet radio via MultiHierarchyMap's base-layer groups): "hexagons", "circles", and -- only for cities with census data -- "census" (itself a multi-level hierarchy from the coarsest to the finest available census geometry).
  • Streets (independent checkbox overlay): always rendered above the shape layer, togglable on its own regardless of which shape is active.
  • Development opportunity (independent checkbox overlay, US/census cities only): h3 hexagon borders only, shown above streets when active.

A small custom control panel (opacity-by-field, circle-size-by-field, background-map choice, B&W basemap) and a legend are injected as extra Leaflet controls stacked below the native layer control. All level_of_service coloring uses a fixed red (bad)-yellow-green (good) scale.

register_relative_fields(names)

Declare columns as relative (intensive) values: offered for colour/opacity/regression, never as a count (circle size, distribution).

Parameters:

Name Type Description Default
names

Column names.

required

is_relative_field(col)

True if col's name marks it as a share/rate/density/median-style intensive value.

Parameters:

Name Type Description Default
col str

Column name.

required

relative_fields(fields)

fields filtered to relative (share/rate/density/...) columns, order preserved.

Parameters:

Name Type Description Default
fields Sequence[str]

Column names.

required

field_unit_suffix(col)

" (pop/km²)", " (%)", " (min)", " (km/h)", or "" -- appended to a field's display label.

Parameters:

Name Type Description Default
col str

Column name.

required

source_label(col)

Display name of the dataset a column comes from ("derived" for pipeline-computed, unprefixed columns).

Parameters:

Name Type Description Default
col str

Column name.

required

strip_source_prefix(col)

col with its known census-source prefix removed, or col unchanged if none matches.

Parameters:

Name Type Description Default
col str

Column name.

required

register_field_labels(labels)

Study-specific display names (logical column name, i.e. without its source prefix -> label), e.g. English names for columns whose raw names are in Spanish. Used by every label function of the pages built afterwards in this process.

Parameters:

Name Type Description Default
labels Dict[str, str]

{logical column: label}.

required

display_field_name(col)

col's cross-country-comparable display name: source prefix stripped, then humanized.

2026-09-28, explicit user request: "the worldpop columns should always have worldpop in the column name even in dropdown boxes in all maps" -- every OTHER source's prefix is deliberately stripped for cross-country comparability (see _SOURCE_PREFIXES's docstring -- e.g. cbs_population/ inegi_population both just read "Population"), but WorldPop columns specifically must keep a visible "WorldPop" marker in their display label everywhere a column name is shown (dropdowns, legends, metadata "Column" name), since a map can have BOTH a real census count and a WorldPop-derived one for the same logical field (e.g. population vs worldpop_residents) and losing the source label there would make them indistinguishable in the UI.

Parameters:

Name Type Description Default
col str

Column name.

required

Returns:

Type Description
str

The display name.

field_label(col)

A field's dropdown/legend display label, with its unit suffix (see field_unit_suffix).

Parameters:

Name Type Description Default
col str

Column name.

required

Returns:

Type Description
str

The label with its unit.

absolute_fields(fields)

fields filtered to absolute raw-count columns -- the exact complement of relative_fields.

Parameters:

Name Type Description Default
fields Sequence[str]

Column names.

required

build_city_map(h3_by_resolution, edges_gdf, tiles_dir, out_html, score_col='level_of_service', street_min_zoom=14, census_by_level=None, circle_fields=None, opacity_fields=None, stats_by_area=None, is_us=False, stops_chunks=None, routes_chunks=None, stops_gdf=None, routes_gdf=None, region='global', skip_tile_build=False, external_tile_writers=None, force_development_tiles=False, force_census_tiles=False, stats_scope_cfg=None, development_gdf=None, use_pmtiles=True, renderer='maplibre', enable_place_comparison=False, downloads_manifest=None, share_source_map=None, country=None, special_levels=None, special_level_labels=None, include_streets=True, include_development=True)

Build and save one city's transit-LOS map (include_streets / include_development = False: no street / development layer).

Parameters:

Name Type Description Default
h3_by_resolution Dict[int, GeoDataFrame]

Mapping of H3 resolution -> GeoDataFrame (h3 polygon geometry + score_col, optionally equity_flag and any number of other numeric columns). One HierarchyMap level ("h3_{res}") is created per entry, zoom-banded so only one resolution renders at a time. Every column present is shown in the click popup (all census variables + the access value).

required
edges_gdf GeoDataFrame

Street-edges GeoDataFrame with score_col, its own independently togglable overlay layer, rendered only at street_min_zoom and above and always above the active shape layer.

required
tiles_dir str

Directory vector tiles are written to.

required
out_html str

Output map HTML path.

required
score_col str

Column name colored (red-yellow-green) on every level.

'level_of_service'
street_min_zoom int

Minimum zoom streets become visible at.

14
census_by_level Optional[Dict[str, GeoDataFrame]]

Optional mapping of census level name -> GeoDataFrame with the same geometry/score/field conventions as h3_by_resolution, in coarse-to-fine order (e.g. county, tract, blockgroup, block -- there is no true national boundary in the available Census geometry schema, so county stands in as the coarsest/"country"-scale level). Only passed for cities with census data; when given, a third "census" shape option (itself multi-resolution, zoom-banded exactly like the h3 levels) is exposed. GeoDataFrames should carry a unique per-row identifier; if none of ("geo_id", "GEOID", "geoid") is present the DataFrame index is used.

None
circle_fields Optional[List[str]]

Numeric columns selectable in the "Circle size by" dropdown. Defaults to every numeric, non-identifier column found on the finest H3 resolution's GeoDataFrame.

None
opacity_fields Optional[List[str]]

Numeric columns selectable in the "Opacity by" dropdown (affects hexagons/circles/census, never streets). Defaults to the same list as circle_fields.

None
stats_by_area Optional[Dict[str, GeoDataFrame]]

Optional {"metro": gdf, "core": gdf} (the stats_h3_resolution grid, already split) powering the bottom-left stats panel (distribution / regression / ANOVA tabs). Omit to skip the stats panel entirely.

None
is_us bool

Whether stats_by_area/h3_by_resolution grids carry US Census acs_* columns.

False
development_gdf Optional[GeoDataFrame]

Optional polygon GeoDataFrame (e.g. census block groups) with an equity_flag column to draw the development- opportunity overlay on directly, instead of the H3-hexagon fallback built from h3_by_resolution. Any per-row identifier column named GEOID/geo_id/geoid is used as the tile feature key; the DataFrame index is used otherwise. Building straight from this (when the caller has it) instead of building H3 tiles and overwriting them afterward avoids writing millions of tiles that get immediately discarded -- see this function's own development-overlay section for why that two-phase dance existed and why it's no longer needed.

None
stops_gdf Optional[GeoDataFrame]

Optional stop-level GeoDataFrame (point geometry) with a mode_category column ("bus"/"tram"/"rail") and a stop_score column, plus any other columns to show in each stop's click popup. Rendered as clustered, emoji markers (clustering at low zoom, individual stops once zoomed in), colored by stop_score on a blue scale -- a genuinely different rendering path from every other layer (real Leaflet markers via Leaflet.markercluster, not vector tiles), since clustering and arbitrary marker content aren't something vector-tile canvas styling can do. Omit to skip the stops layer entirely.

None
routes_gdf Optional[GeoDataFrame]

Optional route-level GeoDataFrame -- one Line/ MultiLineString feature per route -- as produced by transitlos.map.routes.build_route_lines, with route_label, mode ("bus"/"tram"/"rail"), color and text_color columns. Rendered as a client-side polyline overlay (not vector tiles: it's hundreds of features, and its per-mode zoom gating and checkbox toggling would otherwise need a tile rebuild to change), one togglable L.layerGroup per mode, each visible only at/above ROUTE_MODE_MIN_ZOOM[mode]. Also supplies the per-route color/text-color lookup that stop popups and the on-map "routes" annotation use for their route badges; without it those badges fall back to MODE_FALLBACK_COLOR. Omit to skip the transit-lines overlay entirely.

None
region str

transitlos.scoring.REGIONS key whose parameters power the stats panel's "Discretization" tab (speed_score/frequency_score/ reliability_score/walk_decay curve shapes) -- should match whatever region was actually used to compute this city's stop_score/level_of_service columns, so the tab reflects the parameters genuinely behind the map's own data, not a mismatched default. Only affects that one tab; every other layer/score is unaffected by this value.

'global'
external_tile_writers Optional[Dict[tuple, Any]]

Optional {(map_kind, level_name): writer} for levels whose tiles are written externally, e.g. one state at a time for continent-scale levels (map_kind is one of "hexagons", "circles", "census", "special", "streets"); see HierarchyMap.external_tile_writers. Those levels' frames only supply schema/domains; their geometry is never tiled in-process.

None
skip_tile_build bool

If True, skip regenerating vector tiles entirely and reuse whatever already exists on disk under tiles_dir (added 2026-08-12, for fast HTML/JS/CSS-only iteration). Tile generation is by far the most expensive part of this function (tens of minutes on a real city); nothing about a stop popup's HTML, a legend's CSS, an opacity slider, or the stats panel's JS depends on the tile contents (geometry/properties baked into the .pbf files) at all -- only on this function's own Python-generated wrapper HTML/JS, which this always regenerates regardless of this flag. Only set this when you know the underlying data (h3_by_resolution/edges_gdf/census_by_level /styling fields) hasn't changed since tiles were last built -- if it has, the map will render stale or missing data using the new wrapper's styling logic.

False
enable_place_comparison bool

Whether the stats panel's "Place rank" tab (cross-city, population-weighted median level_of_service, ranked across the CS_transitLOS multi-city roster -- see CS_PLACE_MANIFEST in _stats_panel_js) is shown at all. Defaults to False: it only makes sense for a map that is genuinely one of that roster's cities, where the sibling ../<city>/results/summary.json fetches it performs actually resolve. A standalone study map outside CS_transitLOS/ (e.g. TransitLOSStudies/boston_city) isn't in the manifest, so leaving this on there just fires a batch of always-404 fetches on open with no way for the tab to ever populate -- pass True only from a caller that knows this map lives at CS_transitLOS/<city>/map.html. When False, the tab (and its button) don't render at all; "Distribution" becomes the default active tab instead. Applies to both renderers.

False
use_pmtiles bool

If True (default), generate and use PMTiles (.pmtiles) format for vector tiles. PMTiles are single-file archives that are faster to generate and easier to host. If False, use legacy XYZ PBF directory structure for backward compatibility.

True
renderer str

"maplibre" (default) or "folium". MapLibre reads the .pmtiles written by the tile build directly -- no XYZ/pbf extraction step -- and gives fast base-layer parity (per-level coloring, popups, hover, layer switcher) but NOT the scenario editor or stats panel. Pass "folium" to get the full Leaflet-based editor (route drawing, grade-separation paint, live recolor, Distribution/Regression/ANOVA tabs) -- Folium's editor still requires XYZ PBF tiles internally (extracted from the same .pmtiles by HierarchyMap.build()), so it remains the slower path; a fully PMTiles-native Folium editor (via protomaps-leaflet) is not yet implemented.

'maplibre'

Returns:

Type Description
str

Absolute path to the saved HTML file.

Note

HierarchyMap embeds tiles_dir verbatim into the browser-side Leaflet tile URL, so an absolute filesystem path would produce a map.html that only loads correctly if a web server happened to be rooted at /. tiles_dir is converted to a path relative to out_html's directory, and tile-writing is done with the working directory temporarily switched to that same directory so on-disk tiles land exactly where the relative URL expects them.

write_city_popup9(out_html_abs, cells9, stats_by_area)

results/popup9/ of a city map (transitlos.map.popup_cells): the populated res-9 cells with the stats panel's columns, and per analysis area (urban area, metro area, municipality, city core: a res-9 cell belongs to an area when its res-8 parent does) the quantile tables of the popup's percentiles. The cells also go to results/map_inputs_checkpoint/popup9_cells.parquet for the all-cities table of the combined map (world_quantiles9.json).

Parameters:

Name Type Description Default
out_html_abs str

Absolute path of the city's map.html.

required
cells9

Res-9 cells with the map's columns.

required
stats_by_area Dict[str, GeoDataFrame]

{area: GeoDataFrame} of the stats panel.

required

Returns:

Type Description
str

The popup9 folder.

write_stats_data_json(out_html_abs, stats_by_area)

Write results/stats_data.json next to results/*.parquet: the same payload baked into map.html.

map.html already inlines this exact payload via _stats_json_data (baked into window.__statsData so the in-page stats panel needs no network round-trip). This sibling file re-derives the identical column-oriented {"metro": {...}, "core": {...}} JSON and writes it to <city_dir>/results/stats_data.json so other pages -- the combined multi-city map, or another city's stats panel doing a cross-city comparison -- can fetch() just this small JSON instead of loading the whole (tile-heavy) map.html.

Uses the same field selection as the inlined payload (_stats_field_candidates/_stats_count_fields over the finest area's columns) so the two stay in sync.

Parameters:

Name Type Description Default
out_html_abs str

Absolute path of the city's map.html.

required
stats_by_area Dict[str, GeoDataFrame]

{area: GeoDataFrame} of the stats panel.

required

Returns:

Type Description
str

Path of the written JSON.

build_place_rank_panel_block(place_manifest, weight_columns=(), fetch_prefix='')

The bottom-left 📊 stats popup, reduced to ONLY its "Place rank" tab.

Public entry point for a caller with no per-place stats_by_area GeoDataFrame of its own -- concretely, CS_transitLOS/code/combined_map.py (a lightweight page generator with no geopandas/per-h3-cell data, assembling a page that iframes other already-built city map.htmls rather than owning any map data itself). It reuses the exact same _stats_panel_html/_stats_panel_js a real per-city build_city_map call uses for its own "Place rank" tab -- one implementation, two call sites -- with the other four tabs (Distribution/Regression/ANOVA/ Discretization) omitted entirely via place_rank_only=True, since this caller has no per-place h3 data to feed them.

place_manifest: [{"key": ..., "label": ...}, ...] -- the live roster (e.g. from combined_map.py's own _available_cities()), NOT this module's hand-maintained _DEFAULT_CS_PLACE_MANIFEST fallback. weight_columns: candidate weight-column keys for the tab's own weight-column