GIS¶
golit.gis — reactive maps as ordinary views: vector data (GeoDataFrames), raster data
(georeferenced arrays), and DuckDB spatial SQL, all rendered with native MapLibre GL.
Install with pip install "golit[gis]" (vector) and "golit[gis-raster]" (raster);
everything heavy is imported lazily, so import golit never pulls it in. See the
Maps & GIS tutorial for usage.
maplibre¶
A native MapLibre GL map from a style and a camera.
maplibre
¶
maplibre(
style: Any,
*,
center: Any = None,
zoom: float | None = None,
pitch: float = 0,
bearing: float = 0,
height: str = "420px",
**opts: Any,
) -> str
A native MapLibre GL map from a style and camera, as a reactive view fragment.
style is either a style-URL string (e.g. a vector tile style) or a full MapLibre
style dict ({"version": 8, "sources": {...}, "layers": [...]}). center is
[lng, lat]; zoom the zoom level; pitch/bearing tilt and rotate for a
3D view (combine with a style carrying fill-extrusion or terrain layers). Extra
keyword args (minZoom, maxZoom, bounds, …) pass straight to the map spec::
@app.view
def map(city):
return gis.maplibre(
"https://demotiles.maplibre.org/style.json",
center=[city["lng"], city["lat"]], zoom=11, pitch=45,
)
Pure dict assembly — imports nothing. The mount hydrates on first paint and on every POST/SSE swap, and its WebGL context is freed when the fragment is replaced.
Source code in python/golit/gis.py
geo_map¶
A GeoPandas GeoDataFrame straight to a MapLibre choropleth / line / point map. A view
may also just return a GeoDataFrame — render_value routes it here with defaults.
geo_map
¶
geo_map(
gdf: Any,
*,
color: str | None = None,
tooltip: Any = None,
tooltip_trigger: str = "click",
basemap: Any = "default",
fit: bool = True,
fit_padding: int = 24,
legend: bool = True,
geometry: str | None = None,
height: str = "420px",
**opts: Any,
) -> str
Render a GeoPandas GeoDataFrame as a native MapLibre map.
The frame is reprojected to EPSG:4326 if needed, serialized to GeoJSON, and added to
a MapLibre style as a source with a fill (polygons), line (lines), or circle (points)
layer picked from the geometry type. color names a column to drive the fill — a
blue ramp for a numeric column (a choropleth), a categorical palette for a text one;
when color is set, a legend is overlaid (gradient bar or swatches) unless
turned off. tooltip shows feature properties: True for every attribute, or a
column name / list of names — on click, or on hover with tooltip_trigger="hover".
basemap is a vector preset ("default"/"positron", "liberty",
"bright", "dark" — free OpenFreeMap styles, no API key), a raster preset
("osm", "carto-light", "carto-dark"), "none", a full style dict,
or any style-URL string. With fit the camera frames the data (fit_padding px)::
@app.view
def map(regions): # regions is a filtered GeoDataFrame
return gis.geo_map(regions, color="revenue", tooltip=["name", "revenue"])
A plain Polars/pandas frame works too if you name its geometry column with
geometry= (WKB/WKT/shapely) — the bridge from :func:spatial_sql::
return gis.geo_map(gis.spatial_sql("SELECT name, geom FROM p …", p=places),
geometry="geom", color="name")
A view may also just return a GeoDataFrame — :func:golit.rendering.render_value
routes it here with defaults. Requires pip install "golit[gis]".
Source code in python/golit/gis.py
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 | |
vector_tiles¶
Serve a large GeoDataFrame as on-demand MVT vector tiles — the data stays server-side, only the visible tiles cross the wire (the vector analog of tiles). Needs pip install "golit[gis,gis-vector-tiles]".
vector_tiles
¶
vector_tiles(
gdf: Any,
*,
color: str | None = None,
tooltip: Any = None,
tooltip_trigger: str = "click",
properties: Any = None,
basemap: Any = "default",
fit: bool = True,
fit_padding: int = 24,
legend: bool = True,
geometry: str | None = None,
min_zoom: int = 0,
max_zoom: int = 14,
height: str = "420px",
**opts: Any,
) -> str
Render a large GeoDataFrame as server-side vector tiles (GIS phase 2.5).
Where :func:geo_map inlines the whole GeoJSON into the page — fine for thousands of
features, not for hundreds of thousands — vector_tiles keeps the data server-side
and streams only the features in each z/x/y tile as a Mapbox Vector Tile (MVT). The
map looks the same (color choropleth, tooltip popups, basemap, legend) but
scales: nothing but the visible tiles crosses the wire, and the GPU styles the vector
features client-side::
@app.view
def map(parcels): # parcels: a big GeoDataFrame
return gis.vector_tiles(parcels, color="value", tooltip=["id", "value"])
The frame is reprojected to Web Mercator and registered under an opaque token; the
/gis/vector route encodes tiles on demand. properties limits which columns ride in
the tiles (the color column and tooltip fields are always included); min_zoom /
max_zoom bound the tile pyramid (MapLibre over-zooms past max_zoom). A plain
Polars/pandas frame works with geometry=<column> (as in :func:geo_map). Requires
pip install "golit[gis,gis-vector-tiles]".
Source code in python/golit/gis.py
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 | |
raster¶
Render a georeferenced raster (rioxarray/xarray DataArray, GeoTIFF path, or NumPy array + bounds) as a native MapLibre image layer.
raster
¶
raster(
data: Any,
*,
cmap: str = "viridis",
opacity: float = 0.85,
band: int | None = None,
vmin: float | None = None,
vmax: float | None = None,
bounds: Any = None,
label: str = "value",
basemap: Any = "default",
fit: bool = True,
fit_padding: int = 24,
legend: bool = True,
max_size: int = 1024,
height: str = "420px",
**opts: Any,
) -> str
Render a georeferenced raster as a native MapLibre image layer (GIS phase 2).
data is a rioxarray/xarray DataArray (reprojected to EPSG:4326 via its .rio
CRS), a GeoTIFF path, or a NumPy 2-D array with explicit bounds=[w, s, e, n]. A
single band is colormapped (cmap: "viridis", "magma", "blues",
"terrain", "greys"; vmin/vmax set the range, NaN nodata is transparent),
encoded to a PNG, and placed as an image source on the basemap with opacity. A
colorbar legend (titled label) is overlaid. Large rasters are downsampled to
max_size px on the long edge to keep the fragment small::
@app.view
def map(elevation, cmap=select(["viridis", "terrain"], default="terrain")):
return gis.raster(elevation, cmap=cmap, label="Elevation (m)")
A view may also just return a georeferenced DataArray. For a multiband raster
(satellite imagery), see :func:rgb. Requires pip install "golit[gis-raster]".
Source code in python/golit/gis.py
rgb¶
Render a multiband raster (satellite imagery) as a true/false-color RGB composite — three selected bands, each contrast-stretched independently, as a MapLibre image layer.
rgb
¶
rgb(
data: Any,
*,
bands: Any = (0, 1, 2),
percentiles: Any = (2.0, 98.0),
vmin: Any = None,
vmax: Any = None,
gamma: float | None = None,
opacity: float = 1.0,
bounds: Any = None,
basemap: Any = "default",
fit: bool = True,
fit_padding: int = 24,
max_size: int = 1024,
height: str = "420px",
**opts: Any,
) -> str
Render a multiband raster as a true/false-color RGB composite (GIS phase 2.5).
data is a rioxarray/xarray DataArray (reprojected to EPSG:4326 via its .rio
CRS), a multiband GeoTIFF path, or a NumPy array with explicit bounds=[w, s, e, n]
— band-first (band, y, x) (the rasterio/rioxarray layout) or channel-last
(y, x, band) (auto-detected). bands selects the three bands mapped to red,
green, blue: the default (0, 1, 2) is a natural-color composite for an R-G-B raster;
pick others for false color (e.g. NIR-R-G to highlight vegetation).
Each band is contrast-stretched independently — by default to its 2nd–98th
percentiles (robust to outliers), or to an explicit vmin/vmax (a scalar for
all three, or a 3-sequence per band). gamma brightens (>1) or darkens (<1) the
midtones; pixels that are nodata (non-finite) in any band are transparent. The composite
is encoded to a PNG and placed as an image layer on the basemap with opacity.
Large rasters are downsampled to max_size px on the long edge::
@app.view
def scene(stack, combo=select(["natural", "false-color"], default="natural")):
bands = (0, 1, 2) if combo == "natural" else (3, 0, 1) # NIR-R-G
return gis.rgb(stack, bands=bands)
Requires pip install "golit[gis-raster]".
Source code in python/golit/gis.py
tiles¶
Stream a very large Cloud-Optimized GeoTIFF as on-demand z/x/y map tiles via rio-tiler — only the visible window crosses the wire. Needs pip install "golit[gis-tiles]".
tiles
¶
tiles(
source: Any,
*,
bands: Any = None,
cmap: str = "viridis",
rescale: Any = None,
opacity: float = 1.0,
basemap: Any = "default",
fit: bool = True,
fit_padding: int = 24,
min_zoom: int | None = None,
max_zoom: int | None = None,
tile_size: int = 256,
height: str = "420px",
**opts: Any,
) -> str
Stream a very large raster as on-demand map tiles (GIS phase 2.5).
Where :func:raster/:func:rgb ship the whole array as one PNG, tiles serves a
Cloud-Optimized GeoTIFF (a local path or a remote http(s) URL) through a
server-side tile route: rio-tiler reads only the z/x/y window each MapLibre request
needs, colormaps/rescales it, and returns a 256-px PNG. A multi-gigabyte COG renders
without ever loading or transmitting the full raster.
bands selects the source band(s): omit (or one index) for a single band, colormapped
with cmap (any rio-tiler colormap — "viridis", "magma", "terrain", …);
three indexes for an RGB composite (no colormap). Each band is contrast-stretched to
rescale — a (min, max) per band, or auto from the COG's 2nd–98th percentile
statistics when omitted. The data's geographic footprint frames the camera (fit)::
@app.view
def scene(layer=select(["elevation", "landcover"], default="elevation")):
return gis.tiles(f"/data/{layer}.tif", cmap="terrain") # a COG path or URL
Reading the source's metadata needs pip install "golit[gis-tiles]" (rio-tiler). The
tile route is part of every Golit server; tiles for a session are served by the worker
that rendered the view (the usual session affinity).
Source code in python/golit/gis.py
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 | |
terrain¶
Run a WhiteboxTools terrain operation (hillshade, slope, aspect, fill, flow accumulation, …) on a DEM, returning a georeferenced DataArray that feeds raster/tiles. Needs pip install "golit[gis-terrain]".
terrain
¶
Run a WhiteboxTools terrain analysis on a DEM, returning the result as a
georeferenced DataArray — feed it to :func:raster/:func:tiles, or just return it.
dem is a DEM as a GeoTIFF path or a georeferenced rioxarray/xarray DataArray
(terrain analysis needs the cell size, so a bare NumPy array won't do; use a projected
CRS in metres — e.g. a UTM zone — for meaningful slopes). op is one of the curated
operations — "hillshade", "slope", "aspect", "fill" (fill depressions),
"flow_accumulation" — or any other WhiteboxTools tool name; extra keyword args pass
straight to the tool (e.g. azimuth=/altitude= for hillshade)::
@app.reactive
def shaded(dem, azimuth=slider(0, 360, default=315)):
return gis.terrain(dem, "hillshade", azimuth=azimuth) # -> a DataArray
@app.view
def relief(shaded):
return gis.raster(shaded, cmap="greys", label="Hillshade")
The DEM is run through the WhiteboxTools binary (downloaded once on first use) in a temp
workspace, and the output is read back into memory. Requires
pip install "golit[gis-terrain]".
Source code in python/golit/gis.py
ee_layer¶
Overlay a Google Earth Engine image as live XYZ tiles — EE renders the imagery, Golit points a MapLibre raster source at the tile URL from getMapId(vis). Needs pip install "golit[gis-ee]" and an Earth Engine account.
ee_layer
¶
ee_layer(
image: Any,
*,
vis: Any = None,
opacity: float = 1.0,
basemap: Any = "default",
center: Any = None,
zoom: float | None = None,
attribution: str = "Map data © Google Earth Engine",
height: str = "420px",
**opts: Any,
) -> str
Overlay a Google Earth Engine image as live XYZ tiles (GIS phase 3).
image is anything with a getMapId(vis) method — an ee.Image (reduce a
collection first with .median()/.mosaic()). Earth Engine renders the tiles on its
own servers; this asks for a tile-URL template (image.getMapId(vis)) and points a
MapLibre raster source at it, overlaid on basemap. vis is the usual Earth
Engine visualization dict ({"min", "max", "bands"} or "palette"); center /
zoom frame the camera (an EE image can be global, so there's no data extent to fit)::
import ee
ee.Initialize(project="my-cloud-project") # after `earthengine authenticate`
@app.view
def scene(cloud=slider(5, 80, default=30)):
s2 = (ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
.filterBounds(aoi)
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", cloud))
.median())
return gis.ee_layer(s2, vis={"bands": ["B4", "B3", "B2"], "min": 0, "max": 3000},
center=[-0.15, 5.62], zoom=10)
This function imports nothing itself — Earth Engine authentication and the ee objects
are the caller's. Install the client with pip install "golit[gis-ee]" and authenticate
once (earthengine authenticate + ee.Initialize(project=…)).
Source code in python/golit/gis.py
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 | |
explore¶
The folium/leafmap escape hatch — embed gdf.explore() as a swappable fragment.
explore
¶
The folium/leafmap escape hatch: delegate to gdf.explore(**kwargs) and embed
its HTML. Returns a self-contained (iframe) folium map wrapped in a sized container,
so it swaps cleanly like any other fragment — the cost is folium's client runtime,
versus :func:geo_map's native MapLibre. Use this when you want the folium ecosystem
(layer control, marker clusters, plugins)::
@app.view
def map(regions):
return gis.explore(regions, column="revenue", cmap="Blues")
Requires pip install "golit[gis]" (folium ships with the extra).
Source code in python/golit/gis.py
spatial_sql¶
DuckDB ST_* SQL over Polars/GeoJSON sources, returning Polars (bridge to geo_map with to_geo).
spatial_sql
¶
Run a DuckDB spatial SQL query (ST_* functions) over named frames,
returning Polars — the spatial extension is loaded on the connection first, then the
query runs through the ordinary :func:golit.sql path, so the result memoizes and
feeds :func:geo_map like any frame::
@app.reactive
def nearby(places, radius_km=slider(1, 50, default=10)):
return gis.spatial_sql(
"SELECT name, geom FROM p "
f"WHERE ST_DWithin(geom, ST_Point(-0.19, 5.6), {radius_km} / 111.0)",
p=places,
)
Requires the sql extra (pip install "golit[sql]"); DuckDB downloads the
spatial extension on first use. Select geometry as ST_AsWKB(geom) (or
ST_AsText) and pass it through :func:to_geo to feed :func:geo_map.
Source code in python/golit/gis.py
to_geo¶
Turn a frame with a WKB/WKT/shapely geometry column into a GeoDataFrame — the bridge from spatial_sql to geo_map.
to_geo
¶
Turn a frame with a geometry column into a GeoPandas GeoDataFrame.
The bridge from :func:spatial_sql (which returns Polars) to :func:geo_map. The
geometry column may be WKB bytes (a DuckDB GEOMETRY / ST_AsWKB column —
the usual spatial_sql output), WKT text (ST_AsText), or shapely objects.
Accepts a Polars or pandas frame; crs defaults to EPSG:4326 (lon/lat)::
frame = gis.spatial_sql("SELECT name, ST_AsWKB(geom) AS geometry FROM p …", p=places)
gdf = gis.to_geo(frame, geometry="geometry")
Requires pip install "golit[gis]".
Source code in python/golit/gis.py
is_geodataframe¶
is_geodataframe
¶
Whether value is a GeoPandas GeoDataFrame — by class, without importing
geopandas (mirrors the matplotlib/Lets-Plot detectors). Used by
:func:golit.rendering.render_value and :func:golit.hashing.hash_value so a view
can return a GeoDataFrame directly.
Source code in python/golit/gis.py
is_dataarray¶
is_dataarray
¶
Whether value is an xarray DataArray — by class, without importing xarray.
Used by :func:golit.rendering.render_value so a view can return a (georeferenced)
raster directly.