Skip to content

transitlos.map

Lightweight, tile-based folium map builder -- reusable across any transitLOS study.

build_city_map is column-agnostic: every field it renders (the score column, circle-size/opacity candidate fields, census-level GeoDataFrames, stats-panel data) is supplied by the caller, not hardcoded to any specific study's schema (e.g. a particular census provider's column names). A study with a different set of census columns, a different scoring column name, or no census data at all works without changing this package -- only the caller's own column lists change.

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.

build_download_panel_block(manifest_json, base_path='results', place_options=None)

Shared HTML+JS for the "Download data" panel.

Used by both _inject_maplibre_download_panel_into_saved_html (one city's own map, place_options=None) and combined_map.py (which passes place_options -- one {value, label, base_path} per city -- to add the place dropdown described in the task; base_path there is each city's own relative path from the combined map's HTML location, e.g. "../beerseba/results", since the combined map has no downloads of its own to point at).

manifest_json is a JSON object (baked in, same pattern as _stats_json_data) shaped: {"scopes": ["metro","core"], "h3_resolutions": [5,7,9,11], "census_levels": ["county","tract",...], "has_stops": true, "has_routes": true} For the combined map, manifest_json is instead a JSON mapping of place value -> that same per-place object (window.__downloadManifests), since different cities can have different resolutions/levels/census availability.

Parameters:

Name Type Description Default
manifest_json str

JSON of what can be downloaded (see above).

required
base_path str

Relative path of the results folder.

'results'
place_options Optional[List[dict]]

Optional [{value, label, base_path}] for a page with several places.

None

Returns:

Type Description
str

HTML and script of the panel.

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