Skip to content

geohierarchy.maps.folium.render

HierarchyMap / MultiHierarchyMap: orchestrate tiling, styling, legend, and .save().

MapLayer(style=None, style_js=None, popup_fields=None, popup_js=None, tooltip_js=None, legend_html=None, resolution=None, buffer_frac=None, native_zoom_range=None, layer_type=None, maplibre_paint=None) dataclass

Per-level rendering configuration for one hierarchy level.

Attributes:

Name Type Description
style Optional[ColorSpec]

A :class:ColorSpec describing color/fill declaratively.

style_js Optional[str]

Raw JS function body function(properties){...}, bypassing style entirely. Takes precedence over style.

popup_fields Optional[List[str]]

Attribute columns to show in a default popup table.

popup_js Optional[str]

Raw JS function function(properties){ return '<html>'; } building the popup content, bypassing popup_fields.

tooltip_js Optional[str]

Raw JS function building tooltip content, analogous to popup_js.

legend_html Optional[str]

Raw HTML overriding the auto-generated legend box for this level.

resolution Optional[Any]

Explicit (min_zoom, max_zoom) override for this level, bypassing auto-assignment.

buffer_frac Optional[float]

Tile buffer as a fraction of tile width, forwarded to :func:~geohierarchy.maps.folium.tiles.write_level_tiles (default there is 2%). Point layers rendered as client-side circles (a fixed pixel radius, not a geometry that scales with zoom) need a bigger buffer than polygon layers do -- a point just inside a tile's edge still gets its circle clipped by that tile's own canvas bounds unless the neighboring tile also carries a copy of it to draw the overflow, and 2% of a tile's geographic width can be far fewer pixels than an 18px circle radius at high zoom.

layer_type Optional[str]

Registry key from :mod:geohierarchy.maps.layers (e.g. "polygon", "circle", "street_overlay"), classifying how this level's tiles render (filled area / radius-scaled points / stroked line). Defaults to "polygon" when unset. Read by :class:geohierarchy.maps.maplibre.render.MapLibreHierarchyMap to pick the right MapLibre layer type/paint shape; the Folium renderer currently infers the same thing from style_js, so this field is additive (safe to leave unset for existing Folium-only code).

native_zoom_range Optional[Any]

Optional (native_min_zoom, native_max_zoom) override, decoupling the zoom range tiles are actually BUILT at from the (generally much wider) range they're DISPLAYED at (resolution/the auto-assigned display band). Leaflet. VectorGrid reuses the nearest native zoom's tiles (scaled) for any display zoom outside [native_min_zoom, native_max_zoom] -- so a level whose content doesn't meaningfully change in complexity across zoom (e.g. a single, always-visible border-only overlay spanning the full [0, 25] display band) can build tiles at, say, only zoom 8-14 and still display correctly everywhere, instead of independently tiling all 19 zooms up to MAX_NATIVE_TILE_ZOOM. Only safe for that kind of stable- content, wide-display-band level -- narrowing this for a level whose geometry/detail genuinely differs a lot by zoom would make far-zoomed-in views reuse an overly-coarse tile. None (the default) keeps the existing behavior: native range = the display range, capped at MAX_NATIVE_TILE_ZOOM.

maplibre_paint = None class-attribute instance-attribute

Raw MapLibre GL paint dict, used verbatim by :class:geohierarchy.maps.maplibre.render.MapLibreHierarchyMap in place of translating style/style_js (which is Leaflet/Folium-specific JS and has no MapLibre equivalent). Takes precedence over style. Callers whose per-level coloring is expressed as style_js (a raw JS function -- e.g. transitlos.map.build's score-based red/yellow/green ramp) must additionally set this to get the equivalent MapLibre ["interpolate", ...]/["step", ...] paint expression; MapLibre output otherwise falls back to a flat default fill color for that level.

HierarchyMap(hierarchy, levels=None, basemap='openfreemap_positron', tiles_dir=None, resolutions=None, use_pmtiles=True, extract_xyz=True, allow_overlapping_zoom_ranges=False)

Renders a whole :class:~geohierarchy.core.GeoHierarchy as one interactive Leaflet map.

Each level owns a zoom-resolution range; exactly one level's vector tiles are visible at any given zoom.

Parameters:

Name Type Description Default
allow_overlapping_zoom_ranges bool

If True, manually-specified zoom ranges are used as given, without requiring them to partition [0, 25] (for sets of alternative levels that are all shown over the full range and toggled by the caller, e.g. a dropdown of unrelated boundary sets).

False
hierarchy

A :class:~geohierarchy.core.GeoHierarchy.

required
levels Optional[Sequence[str]]

Level names to render. Defaults to all of hierarchy.geometries.

None
basemap Union[str, dict, Any]

Preset name / dict / folium.TileLayer. See :func:geohierarchy.maps.folium.basemap.build_tile_layer.

'openfreemap_positron'
tiles_dir Optional[str]

Directory vector tiles are written to by :meth:build. Required before calling :meth:build.

None
resolutions Optional[Dict[str, Any]]

Optional manual {level: (min_zoom, max_zoom)} overrides, equivalent to calling :meth:set_resolution for each entry.

None
use_pmtiles bool

If True (default), generate and use PMTiles format. If False, use legacy XYZ PBF directories for backward compatibility.

True
extract_xyz bool

If True (default), also extract a {z}/{x}/{y}.pbf XYZ directory tree from each level's .pmtiles during :meth:build -- required by :meth:save (Folium's Leaflet.VectorGrid-based renderer has no native PMTiles support). Set False when only :meth:save_maplibre will be called (MapLibre reads .pmtiles directly) to skip this extraction entirely -- for large levels this is the difference between a single .pmtiles archive and an extracted tree of tens/hundreds of thousands of loose files.

True

set_fallback_level(level)

Mark level (normally the coarsest) as an always-rendered fallback -- see fallback_level.

Parameters:

Name Type Description Default
level str

Name of a level of this map (normally the coarsest).

required

Returns:

Type Description
'HierarchyMap'

This map (for chaining).

Raises:

Type Description
KeyError

If level is not one of the map's levels.

configure_level(name, **kwargs)

Set per-level rendering options (see :class:MapLayer fields).

Parameters:

Name Type Description Default
name str

Level name (must be one of self.levels).

required
**kwargs

Any :class:MapLayer field.

{}

Returns:

Type Description
'HierarchyMap'

self, for chaining.

set_resolution(level, min_zoom, max_zoom)

Manually pin a level's zoom range, overriding auto-assignment.

Parameters:

Name Type Description Default
level str

Level name.

required
min_zoom int

Inclusive minimum zoom.

required
max_zoom int

Inclusive maximum zoom.

required

Returns:

Type Description
'HierarchyMap'

self, for chaining.

resolve_zoom_ranges()

Compute the final zoom range for every level (manual overrides + auto-fill).

Levels with a manual range (via :meth:set_resolution or the constructor's resolutions=) keep it; the rest are auto-assigned with :func:assign_resolutions restricted to those remaining levels and validated together against the manual ones so the overall set still partitions [0, 25].

Returns:

Type Description
Dict[str, Any]

Mapping of level name to (min_zoom, max_zoom).

build(free_level_data=False)

Generate vector tiles for every level under tiles_dir.

Parameters:

Name Type Description Default
free_level_data bool

If True, once every level's tiles are written, shrink self.hierarchy.levels[name] down to just its minx/miny/maxx/maxy bounds columns (dropping every attribute/geometry column). Real 2026-08-26 OOM fix: a MultiHierarchyMap with several named groups (e.g. Boston's hexagons/circles/census, each itself several H3 resolutions or census levels) keeps EVERY group's full GeoHierarchy -- the complete attribute table add_level copied in, for every level -- resident for the entire MultiHierarchyMap.build() loop, even though each group's own .build() call only ever touches one group's data at a time; nothing previously freed a finished group's data before the next group's .build() ran, so peak memory was the SUM of every group's full attribute tables, not the max of any one. Only safe to set when nothing downstream needs this hierarchy's per-feature attribute data again -- level_bounds (map centering) still works after this (it only reads the four bounds columns kept here), but get_level (_vectorgrid_js_and_legend's layer.style is not None branch, and the MapLibre renderer's equivalent) would come back empty. transitlos.map.build.build_city_map only ever configures levels with style_js/maplibre_paint (never the style= ColorSpec param), so layer.style is always None there and this is safe for that caller; defaults to False so every other caller's behavior is unchanged.

False

Idempotent/re-runnable: re-running overwrites existing tile files.

Parallelized per (level, zoom), not per level: levels can differ by orders of magnitude in tile count -- not just from zoom-band width, but also from sheer feature density/count (a real rebuild showed census at ~1.17M tiles vs. ~80k for the next largest level, despite comparable band widths, simply because census polygons are far more numerous/complex per unit area than street edges) -- so splitting work only across levels leaves most cores idle while the single biggest level's zooms grind through serially on one core. Each level is reprojected/trimmed once (prep_level_gdf) and then every zoom in its range becomes its own job in one shared pool sized to the machine's core count, so a lopsided level's zooms run alongside every other level's instead of after them.

(A more aggressive version of this -- tiling each level at a single native zoom and letting Leaflet.VectorGrid's minNativeZoom/ maxNativeZoom reuse it across the whole display band, the way raster tiles already do -- was considered and is NOT done here. Some levels in this codebase are configured with very wide display bands (e.g. a single-level overlay spanning the full [0, 25] zoom range), and pinning minNativeZoom to a deep native zoom for a level like that would make Leaflet fetch 4^(native_z - display_z) tiles to cover one screen at a zoomed-out display level -- a regression, not an improvement, for exactly the levels with the widest bands. That needs each level's natural resolution vs. its display band width worked out deliberately, with real browser-verified zoomed-out behavior, not a blanket rule; flagged as a real follow-up lever, not applied blindly.)

Returns:

Type Description
'HierarchyMap'

self, for chaining.

to_folium()

Build and return the underlying folium.Map, without saving to disk.

save(path)

Render the map (basemap + vector-tile layers + legend) to an HTML file.

Parameters:

Name Type Description Default
path str

Output HTML file path.

required

Returns:

Type Description
str

The path saved to.

save_maplibre(path, basemap=None, title='Map')

Render this map's base layers via MapLibre GL JS + PMTiles instead of Folium/Leaflet.

Base-layer parity only (fill/circle/line coloring, click popups, hover) -- the scenario editor and stats panel remain Folium-only. See :class:geohierarchy.maps.maplibre.render.MapLibreHierarchyMap. Requires :meth:build to have already been run (PMTiles must exist under self.tiles_dir), and path must be saved next to self.tiles_dir (same relative-URL convention as :meth:save).

Parameters:

Name Type Description Default
path str

HTML file to write, next to self.tiles_dir.

required
basemap Union[str, dict]

Basemap name or spec; None = the MapLibre default.

None
title str

Page title.

'Map'

Returns:

Type Description
str

The written path.

MultiHierarchyMap(named_hierarchy_maps, default=None, basemap='openfreemap_positron', tiles_dir=None, overlay_hierarchy_maps=None, overlay_show=None)

Combines several :class:HierarchyMap instances as mutually-exclusive Leaflet layers.

Each named group is rendered as a folium.FeatureGroup(overlay=False), which folium.LayerControl renders as a radio-button group (Leaflet's baseLayer semantics: only one non-overlay layer is ever active at a time) -- giving the "select H3 or Polygons" toggle with no custom JS.

overlay_hierarchy_maps additionally supports independently togglable (checkbox) layers on the same map -- e.g. a streets layer and a separate "development opportunity" layer that should each turn on/off on their own, not as part of the exclusive shape choice.

Parameters:

Name Type Description Default
named_hierarchy_maps Dict[str, HierarchyMap]

Mapping of display name -> :class:HierarchyMap, rendered as mutually-exclusive (radio) base layers.

required
default Optional[str]

Name of the base-layer group shown by default. Defaults to the first key.

None
basemap Union[str, dict, Any]

Shared basemap for the combined map.

'openfreemap_positron'
tiles_dir Optional[str]

If given, applied to every child :class:HierarchyMap (in both named_hierarchy_maps and overlay_hierarchy_maps) that doesn't already have its own tiles_dir set (namespaced under a per-group subdirectory to avoid collisions between groups sharing level names).

None
overlay_hierarchy_maps Optional[Dict[str, HierarchyMap]]

Mapping of display name -> :class:HierarchyMap, rendered as independently togglable (checkbox) overlay layers, each shown/hidden without affecting the others or the base-layer choice.

None
overlay_show Optional[Dict[str, bool]]

Optional per-overlay initial visibility (defaults to visible/True).

None

build(free_level_data=False)

Build tiles for every child :class:HierarchyMap (base layers and overlays).

Parameters:

Name Type Description Default
free_level_data bool

Forwarded to each child :meth:HierarchyMap.build -- see its docstring. Frees a finished group's full attribute data before the next group's .build() materializes its own, so peak memory is the max of any one group's data instead of the sum of all of them.

False

save(path)

Render all groups onto one map, each as a non-overlay (radio-button) layer.

Parameters:

Name Type Description Default
path str

Output HTML file path.

required

Returns:

Type Description
str

The path saved to.

save_maplibre(path, basemap=None, title='Map', radius_field_domains=None, opacity_field_domains=None, circle_fields=None, opacity_fields=None, default_circle_field=None, field_labels=None, radius_field_domains_by_res=None, circle_zoom_bands=None, special_group_levels=None, special_group_level_labels=None, special_group_name='special', special_group_fallback_level=None, special_group_fallback_zoom=5)

Render every group via MapLibre GL JS + PMTiles, toggled by a radio-button switcher.

Base-layer parity only, same caveat as :meth:HierarchyMap.save_maplibre: no scenario editor, no stats panel -- those remain Folium-only (see :meth:save). Each named group (e.g. "hexagons"/"census") is rendered as a mutually-exclusive base layer (matching :meth:save's Leaflet radio-button semantics); overlay groups (e.g. "streets", "development") are independently togglable checkboxes. Requires every child :class:HierarchyMap to have already been .build()-run (PMTiles must exist under each tiles_dir).

radius_field_domains/opacity_field_domains/circle_fields/ opacity_fields/default_circle_field: optional, mirror Folium's _control_panel_html's "Circle size by"/"Opacity by"/"Contrast" controls (see transitlos.map.build._control_panel_html) -- when given, save_multi_maplibre adds the matching live dropdowns/ sliders to the layer-switcher panel. Omitted entirely when not passed (caller has no such fields), matching prior behavior.

Parameters:

Name Type Description Default
path str

HTML file to write, next to the children's tiles folders.

required
basemap Union[str, dict]

Basemap name or spec; None = the MapLibre default.

None
title str

Page title.

'Map'
radius_field_domains Optional[Dict[str, tuple]]

{field: (min, max)} for the "Circle size by" control.

None
opacity_field_domains Optional[Dict[str, tuple]]

{field: (min, max)} for the "Opacity by" control.

None
circle_fields Optional[List[str]]

Fields offered in "Circle size by".

None
opacity_fields Optional[List[str]]

Fields offered in "Opacity by".

None
default_circle_field Optional[str]

Field selected first in "Circle size by".

None
field_labels Optional[Dict[str, str]]

{field: display text} for those dropdowns.

None
radius_field_domains_by_res Optional[Dict[int, Dict[str, tuple]]]

{H3 resolution: {field: (min, max)}}: per-resolution circle domains.

None
circle_zoom_bands Optional[Dict[int, tuple]]

{H3 resolution: (min zoom, max zoom)} of each resolution's circles.

None
special_group_levels Optional[List[str]]

Levels of the special group shown one at a time (picked by hand, not by zoom).

None
special_group_level_labels Optional[Dict[str, str]]

{level: display text} for the special-level dropdown.

None
special_group_name str

Name of the special group.

'special'
special_group_fallback_level Optional[str]

Special level shown below special_group_fallback_zoom while another special level is picked.

None
special_group_fallback_zoom int

Zoom below which the fallback level is shown.

5

Returns:

Type Description
str

The written path.