Web and Cloud GIS

Interactive Web Maps in Python: Folium, leafmap and lonboard

An interactive web map lets readers pan, zoom, hover and click instead of looking at one fixed view. Python can produce one in a few lines, but every web map has to send its data to a browser, and how much it sends, in what form, decides whether the map opens in a second or freezes the page. This notebook builds interactive maps of Bangladesh poverty, rice-field arsenic, 37,923 soil samples and Sentinel-2 NDVI over Syracuse, New York, with three libraries:

  • Folium writes Leaflet maps as self-contained HTML files;
  • leafmap wraps Folium, ipyleaflet and MapLibre with one-line helpers;
  • lonboard draws large datasets on the GPU with deck.gl, sending binary GeoArrow data.

Along the way it measures what each map sends, and shows two traps: simplifying polygons one at a time opens gaps between neighbours, and placing a UTM image on a web map by its corner coordinates puts pixels in the wrong place.

Learning objectives

  1. Explain how a browser draws a web map: basemap tiles, vector overlays and raster overlays.
  2. Prepare vector data for the web: measure payload, simplify a polygon coverage without gaps, round coordinates.
  3. Build Folium maps with choropleths, tooltips, popups, layer control and plugins, and save them as HTML.
  4. Choose a classification scheme for a choropleth and judge it with the goodness of variance fit.
  5. Show thousands of points with clustering, heat maps or GPU rendering, and compare their size.
  6. Put rasters on a web map correctly, as a reprojected image overlay or as XYZ tiles from geolattice.web.
  7. Use leafmap for quick maps and split-screen comparisons, and lonboard for large data.

Data

Data Source
District poverty, population and rice production, Bangladesh (64 districts) Data/00_shared/data_web_cloud_gis/08_03_outputs/districts.gpkg, made in Notebook 08_03 from Data/00_shared/vector_data/Bangladesh/
Upazila (sub-district) and union boundaries of Bangladesh Data/00_shared/vector_data/Bangladesh/Shapefiles/bd_upzila_GCS.shp, bd_union_GCS.shp
Arsenic in irrigation water, soil and rice grain at 263 rice fields Data/00_shared/vector_data/Bangladesh/bd_arsenic_data.csv
Soil pH and organic matter at 37,923 sampling points Data/00_shared/tabular_data/bd_soil_data.csv
Sentinel-2 NDVI over Syracuse, 23 July and 19 September 2025 Data/00_shared/data_web_cloud_gis/08_01_outputs/ndvi_syracuse_*.tif, made in Notebook 08_01

Run Notebooks 08_01 and 08_03 first; they write the NDVI rasters and the district table used here.

The mapping libraries are not GeoLattice dependencies; install them with pip install folium leafmap lonboard mapclassify.

Contents

  1. Setup
  2. How an interactive web map works
  3. Preparing vectors for the web
  4. Folium: a district map with tooltips, popups and layers
  5. Choropleth classes
  6. Points: from 263 fields to 37,923 samples
  7. Rasters on a web map
  8. leafmap: the same maps in fewer lines
  9. lonboard: GPU rendering of large data
  10. Sharing maps and choosing a library
  11. Summary and exercises

Setup

Installation. This notebook needs installation option 6 (every GeoLattice module): pip install "geolattice[all]". See “Installation options” in the GeoLattice README. It also uses lonboard, which no GeoLattice option installs: pip install lonboard.

Code
# Setup: imports, paths, output folder, and helpers for saving Folium/leafmap maps
%matplotlib inline
import os
import re
import shutil
import time
import warnings
from pathlib import Path

warnings.filterwarnings("ignore")

import numpy as np
import pandas as pd
import geopandas as gpd
import shapely
import matplotlib
import matplotlib.pyplot as plt
import mapclassify
import rasterio
from rasterio.warp import calculate_default_transform, reproject, Resampling, transform_bounds
import pyproj
import folium
import folium.plugins as plugins
import branca.colormap as bcm
import leafmap.foliumap as leafmap
import lonboard
from lonboard import Map as LonboardMap, PolygonLayer, ScatterplotLayer
from lonboard.colormap import apply_continuous_cmap
from IPython.display import IFrame, display

import geolattice
import geolattice.web as web

plt.rcParams.update({"figure.dpi": 110})
DATA = Path("../../../Data")
BD = DATA / "00_shared" / "vector_data" / "Bangladesh"
WEB = DATA / "00_shared" / "data_web_cloud_gis"
OUT = WEB / "08_04_outputs"
if OUT.exists():
    shutil.rmtree(OUT)
OUT.mkdir(parents=True)

for needed in [WEB / "08_03_outputs" / "districts.gpkg", WEB / "08_01_outputs" / "ndvi_syracuse_20250723.tif"]:
    if not needed.exists():
        raise FileNotFoundError(f"{needed} is missing: run Notebooks 08_01 and 08_03 first")

def mb(path):
    "File size in MB."
    return os.path.getsize(path) / 1e6

sizes = {}                                       # every HTML map we save, for Section 10

# Basemaps used below. Esri's light-gray canvas needs no API key (CARTO's tiles now do; see Section 4).
GRAY = "https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}"
GRAY_ATTR = "Tiles © Esri, HERE, Garmin, © OpenStreetMap contributors"
IMAGERY = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
IMAGERY_ATTR = "Tiles © Esri, Maxar, Earthstar Geographics"

def save(m, name):
    "Save a Folium or leafmap map to OUT and record its size."
    path = OUT / name
    (m.to_html(str(path)) if hasattr(m, "to_html") and not isinstance(m, folium.Map) else m.save(str(path)))
    sizes[name] = mb(path)
    return path

print("geolattice", geolattice.__version__, "| folium", folium.__version__, "| leafmap", leafmap.__version__ if hasattr(leafmap, "__version__") else __import__("leafmap").__version__,
      "| lonboard", lonboard.__version__, "| shapely", shapely.__version__)
geolattice 0.3.11 | folium 0.20.0 | leafmap 0.63.1 | lonboard 0.17.0 | shapely 2.2.0

How an interactive web map works

A web map is a web page. The browser downloads a JavaScript mapping library, then the data, then draws everything itself as the user pans and zooms. There are three ways to get geographic data into that page:

How the data travel What the browser receives Good for Limit
Vector overlay (GeoJSON) Every coordinate as text, inside the HTML or fetched once Up to a few thousand simple features; hover, click and style per feature Size grows with vertices; the browser keeps every feature in memory
Tiles (raster PNG/JPEG or vector MVT) Small pre-cut images or vector tiles, only for the area and zoom in view Basemaps, rasters, very large vector data Tiles must be made and hosted (Notebooks 08_01, 08_02, 08_05)
Binary columns (GeoArrow / Parquet) Compact typed arrays drawn on the GPU (WebGL) Hundreds of thousands to millions of features Needs WebGL; styling is per layer, through arrays

The basemap under the data is almost always tiles from a provider (OpenStreetMap, CARTO, Esri). All of them use the Web Mercator projection (EPSG:3857) and the XYZ tile grid from Notebook 08_00, while overlay coordinates are given in longitude and latitude (EPSG:4326). The mapping library projects them on the fly.

Library Draws with Output Strength
Folium Leaflet (SVG / Canvas) Standalone HTML Simple, rich plugins, maps work anywhere
ipyleaflet Leaflet Jupyter widget Two-way interaction with Python
leafmap Folium, ipyleaflet, MapLibre, deck.gl HTML or widget One-line helpers for GIS tasks
lonboard deck.gl (WebGL, GPU) Jupyter widget or HTML Millions of features from GeoArrow
pydeck, Plotly, kepler.gl deck.gl / Mapbox GL HTML or widget 3D, charts on maps, exploratory apps
geolattice.web Leaflet Tile folders, a Leaflet page, a tile and OGC API server Publishing rasters and vectors (Notebook 08_05)

Preparing vectors for the web

The district layer from Notebook 08_03 was dissolved from upazila boundaries, which were digitised in great detail. Before drawing it, look at how many coordinates a browser would have to receive.

Code
# Load districts and upazilas; compare vertex counts and embedded GeoJSON size
districts = gpd.read_file(WEB / "08_03_outputs" / "districts.gpkg")
upazila = gpd.read_file(BD / "Shapefiles" / "bd_upzila_GCS.shp")[["ADM3_EN", "ADM2_EN", "ADM1_EN", "geometry"]]

def payload(gdf):
    "Vertices and the size of the GeoJSON a web map would embed."
    return gdf.geometry.count_coordinates().sum(), len(gdf.to_json()) / 1e6

rows = []
for name, gdf in [("districts", districts), ("upazilas", upazila)]:
    v, size = payload(gdf)
    rows.append({"layer": name, "features": len(gdf), "vertices": v, "GeoJSON MB": round(size, 1),
                 "vertices per feature": round(v / len(gdf))})
pd.DataFrame(rows)
layer features vertices GeoJSON MB vertices per feature
0 districts 64 1063772 43.3 16621
1 upazilas 544 2847294 115.9 5234

The 64 districts carry 1.06 million vertices, about 16,600 per district, and would be embedded as a 43 MB GeoJSON; the 544 upazilas would be 116 MB. A browser asked to draw that freezes for many seconds, and on a phone it may give up. The detail is far finer than any screen: at the zoom that shows all of Bangladesh, one pixel covers about 1 km.

Simplifying a coverage without gaps

Simplification removes vertices while keeping the shape. The usual tool, the Douglas-Peucker algorithm (GeoSeries.simplify), works on one polygon at a time. Neighbouring polygons share a boundary, but each copy of it is simplified separately, so the two copies no longer match: thin gaps and overlaps (slivers) appear along every shared edge. A coverage simplifier (shapely.coverage_simplify, GEOS 3.12+) simplifies each shared edge once and gives both neighbours the same result. Its tolerance is an area-based (Visvalingam-Whyatt) threshold, so the two methods’ tolerances are not equivalent; we compare them by vertices kept.

We measure, in a metric projection (UTM zone 46N), the gaps that open inside the country, the overlaps between neighbours, and the largest boundary shift (Hausdorff distance).

Code
# Compare one-at-a-time vs coverage simplification at several tolerances
upz_m = upazila.to_crs(32646)
geoms = upz_m.geometry.values
U0 = shapely.union_all(geoms)

def interior_holes(u):
    "Total area and count of holes inside a (multi)polygon."
    rings = [r for p in shapely.get_parts(u) for r in p.interiors]
    return sum(shapely.Polygon(r).area for r in rings), len(rings)

holes0 = interior_holes(U0)
rows, simplified = [], {}
for method, tol in [("one polygon at a time", 100), ("one polygon at a time", 250),
                    ("coverage", 100), ("coverage", 250), ("coverage", 500)]:
    t0 = time.perf_counter()
    s = shapely.simplify(geoms, tol) if method.startswith("one") else shapely.coverage_simplify(geoms, tol)
    seconds = time.perf_counter() - t0
    U = shapely.union_all(s)
    holes = interior_holes(U)
    hd = np.array([shapely.hausdorff_distance(a, b) for a, b in zip(geoms, s)])
    simplified[(method, tol)] = s
    rows.append({"method": method, "tolerance": tol, "vertices": int(shapely.get_num_coordinates(s).sum()),
                 "new gaps": holes[1] - holes0[1], "gap km²": abs(round((holes[0] - holes0[0]) / 1e6, 1)),
                 "overlap km²": abs(round((shapely.area(s).sum() - U.area) / 1e6, 1)),
                 "median shift m": round(np.median(hd)), "max shift m": round(hd.max()),
                 "upazilas shifted > 1 km": int((hd > 1000).sum()),
                 "largest shift in": f"{upazila.ADM3_EN[hd.argmax()]} ({upazila.ADM2_EN[hd.argmax()]})",
                 "seconds": round(seconds, 1)})
simp_table = pd.DataFrame(rows)
simp_table
method tolerance vertices new gaps gap km² overlap km² median shift m max shift m upazilas shifted > 1 km largest shift in seconds
0 one polygon at a time 100 87778 8262 100.7 98.6 99 157 0 Magura Sadar (Magura) 1.7
1 one polygon at a time 250 45058 5555 291.4 281.0 247 468 0 Nageshwari (Kurigram) 1.8
2 coverage 100 154717 0 0.0 0.0 100 361 0 Dacope (Khulna) 3.0
3 coverage 250 70261 0 0.0 0.0 318 2268 9 Dacope (Khulna) 3.0
4 coverage 500 36931 0 0.0 0.0 624 5468 61 Shyamnagar (Satkhira) 3.1
Code
# Zoom on the largest gap left by one-at-a-time simplification
s = simplified[("one polygon at a time", 250)]
holes = [shapely.Polygon(r) for p in shapely.get_parts(shapely.union_all(s)) for r in p.interiors]
biggest = max(holes, key=lambda h: h.area)
print(f"largest gap: {biggest.area / 1e4:.0f} ha, {shapely.minimum_bounding_radius(biggest) * 2 / 1000:.1f} km long")
window = biggest.centroid.buffer(1500).envelope
sel = shapely.intersects(geoms, window)
fig, axes = plt.subplots(1, 3, figsize=(13, 4.8), sharex=True, sharey=True)
panels = [("original", geoms), ("one polygon at a time, 250 m", s), ("coverage, 250", simplified[("coverage", 250)])]
for ax, (title, gs) in zip(axes, panels):
    part = shapely.intersection(gs[sel], window)
    gpd.GeoSeries(part).plot(ax=ax, facecolor="#cfe3f3", edgecolor="#1f4e79", linewidth=0.8)
    gap = shapely.difference(window, shapely.union_all(part))
    if not gap.is_empty:
        gpd.GeoSeries([gap]).plot(ax=ax, color="red")
    pairs = [shapely.intersection(a, b) for i, a in enumerate(part) for b in part[i + 1:]]
    over = [g for p in pairs for g in shapely.get_parts(p) if g.area > 0]
    if over:
        gpd.GeoSeries(over).plot(ax=ax, color="orange")
    ax.set_title(title, fontsize=10); ax.set_xticks([]); ax.set_yticks([])
fig.suptitle("Gaps (red) and overlaps (orange) after simplification, 3 km window around the largest gap", fontsize=11)
plt.tight_layout(); plt.show()
largest gap: 231 ha, 17.3 km long

Simplifying one polygon at a time opened 8,262 gaps at 100 m and 5,555 at 250 m, with about as much overlap as gap (99 and 281 km² overlapping). The figure zooms on the largest gap at 250 m: a sliver of 231 ha, 17.3 km long, along a boundary between two upazilas. On a web map these slivers show as thin white lines between polygons, and a tooltip on an overlap belongs to two units at once.

Coverage simplification left no gaps and no overlaps at any tolerance. Because its tolerance is area-based, it keeps more vertices for the same number (154,717 at 100 against 87,778), and at the larger tolerances it can cut across long, narrow parts of a polygon: at 250, nine upazilas moved by more than 1 km somewhere, the largest in Dacope (Khulna) in the Sundarbans, where boundaries follow narrow river channels; at 500, 61 did. The median shift (318 m at 250) is what most boundaries experience. For a national map viewed at zooms 7 to 9, where a pixel covers about 1.1 km to 280 m, 250 is a sensible choice; for district-level zooms use 100 or less, or vector tiles (Notebook 08_02) that simplify per zoom.

Coordinate precision

GeoJSON writes coordinates as text, by default with 15 or more digits. A degree of latitude is about 111 km, so six decimals already resolve 0.11 m, far finer than these boundaries (or a screen pixel) can show. Rounding the coordinates shrinks the file further.

Code
# Measure how coordinate rounding (decimal places) shrinks GeoJSON size
cov = gpd.GeoDataFrame(upazila.drop(columns="geometry"),
                       geometry=gpd.GeoSeries(simplified[("coverage", 250)], crs=32646).to_crs(4326))
rows = []
for digits in [None, 6, 5, 4]:
    g = cov if digits is None else cov.set_geometry(shapely.set_precision(cov.geometry.values, 10.0 ** -digits))
    rows.append({"decimals": "full" if digits is None else digits,
                 "resolution m": "-" if digits is None else round(111_320 * 10.0 ** -digits, 2),
                 "GeoJSON MB": round(len(g.to_json()) / 1e6, 2),
                 "invalid polygons": int((~g.is_valid).sum())})
pd.DataFrame(rows)
decimals resolution m GeoJSON MB invalid polygons
0 full - 2.95 0
1 6 0.11 1.77 0
2 5 1.11 1.63 0
3 4 11.13 1.48 0

Rounding the coverage-simplified upazilas to six decimals cut the GeoJSON from 2.95 to 1.77 MB, and five decimals to 1.63 MB, with no invalid polygons. Four decimals (11 m) saves little more and starts to be visible at street zooms.

The web-ready layers used in the rest of the notebook are coverage-simplified and rounded to five decimals (about 1 m). Districts are simplified the same way.

Code
# Coverage-simplify in UTM, round lon/lat, and dissolve districts to divisions
def web_ready(gdf, tolerance=250, digits=5):
    "Coverage-simplify in UTM 46N, return to lon/lat and round coordinates."
    g = gdf.to_crs(32646)
    s = gpd.GeoSeries(shapely.coverage_simplify(g.geometry.values, tolerance), crs=32646).to_crs(4326)
    s = gpd.GeoSeries(shapely.set_precision(s.values, 10.0 ** -digits), crs=4326)
    return gpd.GeoDataFrame(gdf.drop(columns="geometry"), geometry=s.values, crs=4326)

districts_web = web_ready(districts)
upazila_web = web_ready(upazila)
divisions_web = districts_web.dissolve("division").reset_index()[["division", "geometry"]]
for name, before, after in [("districts", districts, districts_web), ("upazilas", upazila, upazila_web)]:
    (v0, s0), (v1, s1) = payload(before), payload(after)
    print(f"{name:9s}: {v0:>9,} -> {v1:>7,} vertices, GeoJSON {s0:6.1f} -> {s1:4.2f} MB")
districts: 1,063,772 ->  31,423 vertices, GeoJSON   43.3 -> 0.70 MB
upazilas : 2,847,294 ->  70,255 vertices, GeoJSON  115.9 -> 1.63 MB

Folium: a district map with tooltips, popups and layers

A Folium map is built from objects added to a folium.Map: tile layers, GeoJSON layers, markers and controls. GeoJson takes a GeoDataFrame directly. A style function colours each feature, a tooltip appears on hover and a popup on click. Each layer can be switched on and off in the layer control.

Poverty is the share of people below the upper poverty line (2016 estimates, aggregated from upazilas to districts in Notebook 08_03, weighted by population). One district has no poverty value after the join, so it is drawn in grey.

Code
# Folium choropleth of district poverty with basemaps, tooltips, and plugins
cmap = bcm.LinearColormap(["#ffffcc", "#fd8d3c", "#800026"], vmin=0, vmax=65, caption="Poverty (% of population)")
d = districts_web.assign(pop_m=(districts_web.population / 1e6).round(2), rice_kt=(districts_web.rice_t / 1e3).round())

m = folium.Map(location=[23.75, 90.3], zoom_start=7, tiles=None, control_scale=True)
folium.TileLayer(GRAY, attr=GRAY_ATTR, name="Light gray").add_to(m)
folium.TileLayer("OpenStreetMap", name="OpenStreetMap", show=False).add_to(m)
folium.TileLayer(IMAGERY, attr=IMAGERY_ATTR, name="Satellite", show=False).add_to(m)
folium.GeoJson(
    d[["district", "division", "poverty_pct", "pop_m", "rice_kt", "area_km2", "geometry"]],
    name="Poverty by district",
    style_function=lambda f: {"fillColor": "#bdbdbd" if f["properties"]["poverty_pct"] is None
                              else cmap(f["properties"]["poverty_pct"]),
                              "color": "white", "weight": 0.8, "fillOpacity": 0.8},
    highlight_function=lambda f: {"weight": 3, "color": "#333"},
    tooltip=folium.GeoJsonTooltip(["district", "poverty_pct"], aliases=["District", "Poverty %"]),
    popup=folium.GeoJsonPopup(["district", "division", "poverty_pct", "pop_m", "rice_kt", "area_km2"],
                              aliases=["District", "Division", "Poverty %", "Population (million)",
                                       "Rice 2018-19 (kt)", "Area km²"]),
).add_to(m)
folium.GeoJson(divisions_web, name="Division boundaries", interactive=False,
               style_function=lambda f: {"color": "#222", "weight": 2, "fill": False}).add_to(m)
cmap.add_to(m)
plugins.Fullscreen().add_to(m)
plugins.MiniMap(toggle_display=True).add_to(m)
plugins.MeasureControl(primary_length_unit="kilometers").add_to(m)
folium.LayerControl(collapsed=False).add_to(m)
path = save(m, "districts_poverty.html")
print(f"{path.name}: {mb(path):.2f} MB")
m
districts_poverty.html: 1.09 MB
Make this Notebook Trusted to load map: File -> Trust Notebook

Hover over a district for its name and poverty rate, click for details, switch basemaps in the layer control, and measure distances with the ruler. The map is also saved as a single HTML file that opens in any browser. It loads Leaflet and the basemap tiles from the internet, but the district data are inside the file.

Basemaps are someone else’s service. Folium’s built-in "CartoDB positron" basemap now draws an “API key required” watermark over every tile: CARTO began requiring a key, and xyzservices (the basemap catalogue behind Folium and leafmap) warns about it. Every saved map keeps loading tiles from its provider, so a provider’s change in terms can break published maps. This notebook uses Esri’s light-gray canvas, OpenStreetMap and Esri imagery, which work without a key; check each provider’s terms of use before publishing.

The whole interactive map, with three basemaps, two data layers, a legend and four controls, is a 1.09 MB file; the district data inside it is the 0.70 MB GeoJSON measured above. Unsimplified, the same file would have been over 43 MB.

Choropleth classes

The map above uses a continuous colour ramp. Most published choropleths use a few classes instead, and the choice of class breaks changes the story the map tells. mapclassify (used by GeoPandas, Folium helpers and leafmap) offers the common schemes. The goodness of variance fit (GVF, 0 to 1) measures how much of the variance the classes explain: higher means districts in the same class are more alike.

Code
# Compare classification schemes for poverty rates and goodness of variance fit
pov = districts_web.dropna(subset=["poverty_pct"])
y = pov.poverty_pct.values

def gvf(classifier, values):
    "Goodness of variance fit: 1 - (within-class squared deviations / total squared deviations)."
    sdam = ((values - values.mean()) ** 2).sum()
    sdcm = sum(((values[classifier.yb == c] - values[classifier.yb == c].mean()) ** 2).sum()
               for c in range(classifier.k) if (classifier.yb == c).any())
    return 1 - sdcm / sdam

schemes = {"Equal interval": mapclassify.EqualInterval(y, k=5),
           "Quantiles": mapclassify.Quantiles(y, k=5),
           "Natural breaks (Fisher-Jenks)": mapclassify.FisherJenks(y, k=5),
           "Head/tail breaks": mapclassify.HeadTailBreaks(y)}
pd.DataFrame([{"scheme": n, "classes": c.k, "upper bounds": ", ".join(f"{b:.1f}" for b in c.bins),
               "districts per class": ", ".join(map(str, c.counts)), "GVF": round(gvf(c, y), 3)}
              for n, c in schemes.items()])
scheme classes upper bounds districts per class GVF
0 Equal interval 5 15.5, 27.6, 39.6, 51.7, 63.7 5, 20, 20, 15, 3 0.909
1 Quantiles 5 23.9, 27.5, 34.9, 42.8, 63.7 13, 12, 13, 12, 13 0.908
2 Natural breaks (Fisher-Jenks) 5 20.2, 30.3, 38.7, 48.4, 63.7 12, 18, 15, 12, 6 0.928
3 Head/tail breaks 6 32.3, 42.6, 49.1, 53.9, 59.2, 63.7 33, 16, 8, 4, 1, 1 0.823
Code
# Plot the same poverty data under each classification scheme side by side
fig, axes = plt.subplots(1, 4, figsize=(15, 5.2))
for ax, (name, c) in zip(axes, schemes.items()):
    pov.assign(cls=c.yb).plot(column="cls", cmap="YlOrRd", ax=ax, edgecolor="white", linewidth=0.3)
    districts_web[districts_web.poverty_pct.isna()].plot(ax=ax, color="#bdbdbd")
    ax.set_title(f"{name}\nGVF {gvf(c, y):.2f}", fontsize=10); ax.set_axis_off()
plt.suptitle("The same 63 district poverty rates with four classification schemes (classes light to dark; grey = no data)", fontsize=11)
plt.tight_layout(); plt.show()

The four schemes tell different stories from the same 63 numbers:

  • Equal interval splits 3.5-63.7% into equal steps. Only 5 districts fall in the lowest class and 3 in the highest, so most of the map is mid-orange.
  • Quantiles put 12-13 districts in every class. The map looks evenly spread, but the top class spans 42.8 to 63.7%, joining very different districts.
  • Natural breaks (Fisher-Jenks) place breaks where the values jump and have the highest GVF (0.928): districts in one class are most alike. The poorest districts, in the north and in the centre-south, stand out.
  • Head/tail breaks, made for heavy-tailed data, put 33 districts in the lowest class here. Poverty rates are not heavy-tailed, and its GVF is the lowest (0.823).

Natural breaks suit this map. Whatever the scheme, state it in the legend.

The chosen breaks go into Folium as a step colour map, so the web map and the printed figure match:

Code
# Folium map colored with Fisher-Jenks natural breaks and a stepped legend
jenks = schemes["Natural breaks (Fisher-Jenks)"]
breaks = [float(np.floor(y.min()))] + [round(b, 1) for b in jenks.bins]
step = bcm.StepColormap(["#ffffb2", "#fecc5c", "#fd8d3c", "#f03b20", "#bd0026"], index=breaks,
                        vmin=breaks[0], vmax=breaks[-1], caption="Poverty %, natural breaks")
m = folium.Map(location=[23.75, 90.3], zoom_start=7, tiles=GRAY, attr=GRAY_ATTR)
folium.GeoJson(d[["district", "poverty_pct", "geometry"]],
               style_function=lambda f: {"fillColor": "#bdbdbd" if f["properties"]["poverty_pct"] is None
                                         else step(f["properties"]["poverty_pct"]),
                                         "color": "white", "weight": 0.6, "fillOpacity": 0.85},
               tooltip=folium.GeoJsonTooltip(["district", "poverty_pct"])).add_to(m)
step.add_to(m)
save(m, "districts_poverty_jenks.html")
m
Make this Notebook Trusted to load map: File -> Trust Notebook

Points: from 263 fields to 37,923 samples

Arsenic in rice fields

The 263 rice fields from Notebook 08_03 are few enough to draw one by one. Each CircleMarker is coloured by the arsenic concentration of its irrigation water, against the WHO guideline (0.01 mg/L) and the Bangladesh drinking-water standard (0.05 mg/L), and has a popup with the field’s water, soil and grain arsenic.

Code
# Load arsenic field points, bin water As, and map CircleMarkers on imagery
ars = pd.read_csv(BD / "bd_arsenic_data.csv")
fields = gpd.GeoDataFrame(ars[["ID", "WAs", "SAs", "GAs", "Variety", "Land_type"]],
                          geometry=gpd.points_from_xy(ars.Longitude, ars.Latitude), crs=4326)
bins = [0, 0.01, 0.05, 0.1, np.inf]
colors = ["#1a9850", "#fee08b", "#f46d43", "#a50026"]
labels = ["< 0.01 (below WHO)", "0.01-0.05", "0.05-0.10", "> 0.10 mg/L"]
fields["wclass"] = pd.cut(fields.WAs, bins, labels=labels, right=False)
print(fields["wclass"].value_counts().reindex(labels).to_string())

m = folium.Map(location=[fields.geometry.y.mean(), fields.geometry.x.mean()], zoom_start=12,
               tiles=IMAGERY, attr=IMAGERY_ATTR)
for r in fields.itertuples():
    color = colors[labels.index(r.wclass)]
    folium.CircleMarker([r.geometry.y, r.geometry.x], radius=5, color="black", weight=0.6,
                        fill=True, fill_color=color, fill_opacity=0.9,
                        tooltip=f"Field {r.ID}: water As {r.WAs:.3f} mg/L",
                        popup=folium.Popup(f"<b>Field {r.ID}</b> ({r.Variety}, {r.Land_type})<br>"
                                           f"Water As: {r.WAs:.3f} mg/L<br>Soil As: {r.SAs:.1f} mg/kg<br>"
                                           f"Grain As: {r.GAs:.3f} mg/kg", max_width=250)).add_to(m)
legend = "".join(f'<div><span style="background:{c};width:12px;height:12px;display:inline-block;margin-right:5px;border:1px solid #333"></span>{l}</div>'
                 for c, l in zip(colors, labels))
m.get_root().html.add_child(folium.Element(
    f'<div style="position:fixed;bottom:30px;left:30px;z-index:9999;background:white;padding:8px;'
    f'font:12px sans-serif;border-radius:4px;box-shadow:0 1px 4px #0005"><b>Irrigation water arsenic</b>{legend}</div>'))
save(m, "arsenic_fields.html")
m
wclass
< 0.01 (below WHO)      0
0.01-0.05              40
0.05-0.10              65
> 0.10 mg/L           158
Make this Notebook Trusted to load map: File -> Trust Notebook

No field’s irrigation water is below the WHO guideline. 40 fields lie between 0.01 and 0.05 mg/L, 65 between 0.05 and 0.10, and 158, three in five, above 0.10 mg/L. The low values cluster in the north-east of the study area. On satellite imagery the fields can be read in context: rice paddies, villages and water channels. The 263 markers and their popups make a 0.36 MB file.

Soil samples: 37,923 points

The national soil database has 37,923 georeferenced samples with pH and organic matter. Drawn as individual markers they would bury the map, and every marker becomes a line of JavaScript. Folium offers several alternatives; we save each one and compare file sizes.

Code
# Load soil samples and compare Folium point-rendering methods for large layers
soil_df = pd.read_csv(DATA / "00_shared" / "tabular_data" / "bd_soil_data.csv")
soil = gpd.GeoDataFrame(soil_df[["PH", "SOM", "DISTRICT_NAME", "LT"]],
                        geometry=gpd.points_from_xy(soil_df.x, soil_df.y), crs=4326)
lat, lon = soil.geometry.y.round(5).values, soil.geometry.x.round(5).values
print(f"{len(soil):,} samples, pH {soil.PH.min():.1f}-{soil.PH.max():.1f} (median {soil.PH.median():.1f})")
by_district = soil.groupby("DISTRICT_NAME").PH.median().sort_values()
print("most acid districts (median pH):", ", ".join(f"{d} {v:.1f}" for d, v in by_district.head(4).items()))
print("most alkaline districts (median pH):", ", ".join(f"{d} {v:.1f}" for d, v in by_district.tail(4).items()))

def base():
    return folium.Map(location=[23.75, 90.3], zoom_start=7, tiles=GRAY, attr=GRAY_ATTR)

variants = {}
t0 = time.perf_counter()
m = base()
for la, lo, ph in zip(lat, lon, soil.PH.values):
    folium.CircleMarker([la, lo], radius=2, weight=0, fill=True, fill_opacity=0.7,
                        fill_color=matplotlib.colors.to_hex(matplotlib.colormaps["RdYlBu"]((np.clip(ph, 4, 8) - 4) / 4))).add_to(m)
variants["one CircleMarker per sample"] = (m, time.perf_counter() - t0)

t0 = time.perf_counter(); m = base()
folium.GeoJson(soil.assign(geometry=gpd.points_from_xy(lon, lat))[["PH", "geometry"]],
               marker=folium.CircleMarker(radius=2, weight=0, fill=True, fill_opacity=0.7)).add_to(m)
variants["one GeoJSON layer"] = (m, time.perf_counter() - t0)

t0 = time.perf_counter(); m = base()
plugins.MarkerCluster(list(zip(lat, lon))).add_to(m)
variants["MarkerCluster"] = (m, time.perf_counter() - t0)

t0 = time.perf_counter(); m = base()
plugins.FastMarkerCluster(list(zip(lat, lon))).add_to(m)
variants["FastMarkerCluster"] = (m, time.perf_counter() - t0)

t0 = time.perf_counter(); m = base()
plugins.HeatMap(list(zip(lat, lon)), radius=6, blur=4).add_to(m)
variants["HeatMap (density only)"] = (m, time.perf_counter() - t0)

rows = []
for name, (m, build_s) in variants.items():
    t0 = time.perf_counter()
    p = save(m, "soil_" + re.sub(r"[^a-z]+", "_", name.lower()).strip("_") + ".html")
    rows.append({"method": name, "HTML MB": round(mb(p), 2), "build + save s": round(build_s + time.perf_counter() - t0, 1)})
point_table = pd.DataFrame(rows)
point_table
37,923 samples, pH 3.2-9.6 (median 5.6)
most acid districts (median pH): MAULVIBAZAR 4.6, NETROKONA 4.9, SYLHET 4.9, HABIGANJ 5.0
most alkaline districts (median pH): JHENAIDAHA 7.8, KUSHTIA 7.8, FARIDPUR 8.0, RAJBARI 8.2
method HTML MB build + save s
0 one CircleMarker per sample 18.08 14.3
1 one GeoJSON layer 6.83 1.6
2 MarkerCluster 7.96 7.4
3 FastMarkerCluster 0.83 0.1
4 HeatMap (density only) 0.83 0.1

Writing one CircleMarker per sample produced an 18 MB file, because each marker is a separate block of JavaScript; it also took the longest to build (14 s). One GeoJSON layer holds the same points in 6.8 MB. MarkerCluster was larger still (8.0 MB) because it, too, creates one marker object per point. FastMarkerCluster and HeatMap pass the coordinates as a plain array, 0.83 MB, and build in a tenth of a second. They show where samples are, but a heat map shows only density, not pH. To show the value of every sample, use GPU rendering (Section 9).

The clustered map is small enough to show here; zoom in and the clusters split into samples:

Code
# Display the FastMarkerCluster map (usually the best size/speed trade-off)
variants["FastMarkerCluster"][0]
Make this Notebook Trusted to load map: File -> Trust Notebook

Rasters on a web map

A web map shows rasters in one of two ways: one image stretched over a box (an image overlay), or tiles cut for each zoom level. Either way the pixels must be in Web Mercator, because that is the projection of the map underneath.

The corner-coordinate trap

The Syracuse NDVI image from Notebook 08_01 is in UTM zone 18N with 10 m pixels. Leaflet’s ImageOverlay takes only two corners in latitude and longitude and stretches the image between them in Web Mercator. Feeding it the UTM image with its longitude/latitude bounds looks plausible, but the UTM grid is rotated relative to north here, by the meridian convergence. We compute where each pixel would be drawn and how far that is from where it really is.

Code
# Quantify how ImageOverlay corner bounds misplace UTM pixels on Web Mercator
ndvi_path = WEB / "08_01_outputs" / "ndvi_syracuse_20250723.tif"
with rasterio.open(ndvi_path) as src:
    W, H, T, crs = src.width, src.height, src.transform, src.crs
    west, south, east, north = transform_bounds(crs, 4326, *src.bounds)
print(f"{W} x {H} pixels, {crs}, {T.a:.0f} m; lon/lat box {west:.4f}, {south:.4f}, {east:.4f}, {north:.4f}")

to_ll = pyproj.Transformer.from_crs(crs, 4326, always_xy=True)
to_utm = pyproj.Transformer.from_crs(4326, crs, always_xy=True)
jj, ii = np.meshgrid(np.arange(0, W, 10) + 0.5, np.arange(0, H, 10) + 0.5)
x, yy = T.c + jj * T.a, T.f + ii * T.e                               # true pixel centres, UTM
merc = lambda la: np.log(np.tan(np.pi / 4 + np.radians(la) / 2))      # Web Mercator y (radians)
lon_drawn = west + jj / W * (east - west)                            # where ImageOverlay draws them
lat_drawn = np.degrees(2 * np.arctan(np.exp(merc(north) + ii / H * (merc(south) - merc(north)))) - np.pi / 2)
xd, yd = to_utm.transform(lon_drawn, lat_drawn)
shift = np.hypot(xd - x, yd - yy)
conv = pyproj.Proj(crs).get_factors(*to_ll.transform(T.c + W / 2 * T.a, T.f + H / 2 * T.e)).meridian_convergence
print(f"meridian convergence at the centre: {conv:.2f} degrees")
print(f"pixel misplacement with corner bounds: median {np.median(shift):.0f} m, max {shift.max():.0f} m "
      f"({shift.max() / T.a:.0f} pixels)")
1485 x 1354 pixels, EPSG:32618, 10 m; lon/lat box -76.2225, 42.9781, -76.0380, 43.1018
meridian convergence at the centre: -0.77 degrees
pixel misplacement with corner bounds: median 108 m, max 200 m (20 pixels)

At Syracuse the UTM grid is rotated by 0.77° from true north. Stretched between its lon/lat corners, the image would be drawn with pixels 108 m out of place on average and up to 200 m (20 pixels): roads, fields and the lake shore would not line up with the basemap. The longitude/latitude box is also larger than the image, because it must contain the rotated footprint.

Reprojected image overlay

The fix is to warp the raster to EPSG:3857 first. Then a linear stretch between its corners is exact. The image is coloured with a fixed NDVI range and embedded in the HTML as a PNG.

Code
# Warp NDVI to Web Mercator, colorize, and add as a Folium ImageOverlay
def to_web_mercator(path):
    "Warp a single-band raster to EPSG:3857; return array and lon/lat bounds."
    with rasterio.open(path) as src:
        tr, w, h = calculate_default_transform(src.crs, 3857, src.width, src.height, *src.bounds)
        dst = np.full((h, w), np.nan, dtype="float32")
        reproject(rasterio.band(src, 1), dst, dst_transform=tr, dst_crs=3857, resampling=Resampling.bilinear,
                  dst_nodata=np.nan)
        b = rasterio.transform.array_bounds(h, w, tr)
    return dst, transform_bounds(3857, 4326, b[1], b[0], b[3], b[2])

def colorize(a, vmin=-0.1, vmax=0.9, cmap="RdYlGn"):
    rgba = matplotlib.colormaps[cmap]((np.clip(a, vmin, vmax) - vmin) / (vmax - vmin))
    rgba[..., 3] = np.where(np.isnan(a), 0, 0.85)
    return (rgba * 255).astype("uint8")

ndvi_3857, (w3, s3, e3, n3) = to_web_mercator(ndvi_path)
print(f"warped to {ndvi_3857.shape[1]} x {ndvi_3857.shape[0]} pixels")
m = folium.Map(location=[(s3 + n3) / 2, (w3 + e3) / 2], zoom_start=12, tiles=GRAY, attr=GRAY_ATTR)
folium.raster_layers.ImageOverlay(colorize(ndvi_3857), bounds=[[s3, w3], [n3, e3]], name="NDVI 23 Jul 2025",
                                  mercator_project=False).add_to(m)
bcm.LinearColormap(["#a50026", "#ffffbf", "#006837"], vmin=-0.1, vmax=0.9, caption="NDVI").add_to(m)
folium.LayerControl().add_to(m)
p = save(m, "ndvi_image_overlay.html")
print(f"{p.name}: {mb(p):.1f} MB, all of it sent before anything is drawn")
m
warped to 1501 x 1377 pixels
ndvi_image_overlay.html: 3.4 MB, all of it sent before anything is drawn
Make this Notebook Trusted to load map: File -> Trust Notebook

XYZ tiles with geolattice.web

web.make_xyz_tiles renders the raster into a {z}/{x}/{y}.png pyramid (warping to Web Mercator for each tile) and writes a TileJSON file. A map then requests only the tiles in view. We make pyramids for both dates with the same colour range, so they can be compared.

Code
# Build XYZ tile pyramids for two NDVI dates and summarize tiles per zoom
tile_runs = {}
for date in ["20250723", "20250919"]:
    t0 = time.perf_counter()
    r = web.make_xyz_tiles(WEB / "08_01_outputs" / f"ndvi_syracuse_{date}.tif", OUT / f"ndvi_tiles_{date}",
                           zooms=range(9, 15), colormap="RdYlGn", rescale=[(-0.1, 0.9)], viewer=False)
    tile_runs[date] = r
    print(f"{date}: {r['tiles']} tiles at zooms {r['zooms'][0]}-{r['zooms'][-1]} in {time.perf_counter() - t0:.1f} s")

tdir = OUT / "ndvi_tiles_20250723"
per_zoom = pd.DataFrame([{"zoom": int(z.name), "tiles": len(list(z.rglob("*.png"))),
                          "MB": round(sum(f.stat().st_size for f in z.rglob("*.png")) / 1e6, 2),
                          "m per pixel": round(web.tile_resolution(int(z.name), latitude=43.04), 1)}
                         for z in sorted(tdir.iterdir(), key=lambda p: int(p.name)) if z.is_dir()])
# tiles a 1000 x 700 pixel map window needs, centred on Syracuse, at each zoom
cx, cy = -76.13, 43.04
def window_tiles(z, w=1000, h=700):
    res = web.tile_resolution(z, latitude=cy) / np.cos(np.radians(cy))        # metres per pixel in Mercator units
    X, Y = pyproj.Transformer.from_crs(4326, 3857, always_xy=True).transform(cx, cy)
    (lo0, la0), (lo1, la1) = [pyproj.Transformer.from_crs(3857, 4326, always_xy=True).transform(X + sx * w / 2 * res, Y + sy * h / 2 * res)
                              for sx, sy in [(-1, -1), (1, 1)]]
    return [t for t in web.tiles_for_bounds(lo0, la0, lo1, la1, z) if (tdir / str(t.z) / str(t.x) / f"{t.y}.png").exists()]
per_zoom["tiles in a 1000x700 view"] = [len(window_tiles(z)) for z in per_zoom.zoom]
per_zoom["view MB"] = [round(sum((tdir / str(t.z) / str(t.x) / f"{t.y}.png").stat().st_size for t in window_tiles(z)) / 1e6, 2)
                       for z in per_zoom.zoom]
per_zoom
20250723: 117 tiles at zooms 9-14 in 2.5 s
20250919: 117 tiles at zooms 9-14 in 2.5 s
zoom tiles MB m per pixel tiles in a 1000x700 view view MB
0 9 2 0.02 223.5 2 0.02
1 10 2 0.05 111.7 2 0.05
2 11 4 0.19 55.9 4 0.19
3 12 9 0.68 27.9 9 0.68
4 13 23 2.42 14.0 20 2.41
5 14 77 7.81 7.0 20 2.85

The full pyramid of one date holds 117 tiles at zooms 9 to 14, 11.2 MB in total, most of it at zoom 14, where tiles reach Sentinel-2’s 10 m resolution (7.0 m per pixel). A 1000 × 700 pixel map window never needs more than 20 tiles: at zoom 14 that is 2.85 MB of the 7.81 MB at that level, and at zoom 12 the whole area fits in 9 tiles (0.68 MB). The image overlay sends 3.4 MB before anything appears, at a single resolution. Tiles are sent only for the area in view, so they scale to rasters of any size, which is why every basemap is tiled.

Tiles must be served over HTTP. web.static_server (Notebook 08_02) serves the output folder; the map below shows both dates as tile layers, with Folium’s side-by-side slider. The saved HTML uses relative tile paths, so the folder (HTML file plus tile folders) can be copied as is to any static host such as GitHub Pages or an S3 bucket.

Code
# Serve tiles locally and build a Folium side-by-side NDVI comparison map
server = web.static_server(OUT)
print("serving", OUT, "at", server.url)

def ndvi_compare(prefix):
    m = folium.Map(location=[43.04, -76.13], zoom_start=12, tiles=GRAY, attr=GRAY_ATTR, max_zoom=16)
    left = folium.TileLayer(f"{prefix}ndvi_tiles_20250723/{{z}}/{{x}}/{{y}}.png", attr="Sentinel-2, ESA/Copernicus",
                            name="23 Jul 2025", max_native_zoom=14, max_zoom=16, overlay=True)
    right = folium.TileLayer(f"{prefix}ndvi_tiles_20250919/{{z}}/{{x}}/{{y}}.png", attr="Sentinel-2, ESA/Copernicus",
                             name="19 Sep 2025", max_native_zoom=14, max_zoom=16, overlay=True)
    left.add_to(m); right.add_to(m)
    plugins.SideBySideLayers(left, right).add_to(m)
    return m

save(ndvi_compare(""), "ndvi_side_by_side.html")              # relative tile paths, for hosting
ndvi_compare(server.url.rstrip("/") + "/")                    # served by this notebook's kernel
serving ../../../data/data_web_cloud_gis/08_04_outputs at http://127.0.0.1:40089
Make this Notebook Trusted to load map: File -> Trust Notebook

Drag the slider to compare July (left) with September (right). The inline map loads tiles from the server running in this notebook’s kernel, so it goes blank when the kernel stops; the saved ndvi_side_by_side.html works from any web server, for example python -m http.server -d Data/00_shared/data_web_cloud_gis/08_04_outputs.

What does the slider show? The two rasters share one grid, so the change can be measured directly:

Code
# Summarize pixel-wise NDVI change between the July and September dates
with rasterio.open(WEB / "08_01_outputs" / "ndvi_syracuse_20250723.tif") as a, \
     rasterio.open(WEB / "08_01_outputs" / "ndvi_syracuse_20250919.tif") as b:
    jul, sep = a.read(1), b.read(1)
ok = np.isfinite(jul) & np.isfinite(sep)
diff = sep[ok] - jul[ok]
print(f"pixels valid on both dates: {ok.mean():.1%}")
print(f"median NDVI: July {np.median(jul[ok]):.2f}, September {np.median(sep[ok]):.2f}")
print(f"pixels that fell by more than 0.2: {(diff < -0.2).mean():.1%}; rose by more than 0.2: {(diff > 0.2).mean():.1%}")
pixels valid on both dates: 96.6%
median NDVI: July 0.62, September 0.66
pixels that fell by more than 0.2: 1.3%; rose by more than 0.2: 2.0%

96.6% of pixels are valid on both dates. The median NDVI rose slightly, from 0.62 on 23 July to 0.66 on 19 September, and few pixels changed by more than 0.2 (1.3% fell and 2.0% rose). In the slider the differences are small, scattered patches; the city centre (low NDVI) and Onondaga Lake (red, negative NDVI) look the same on both dates.

leafmap: the same maps in fewer lines

leafmap wraps these steps in GIS-style helpers. leafmap.foliumap produces Folium maps (static HTML); import leafmap gives the ipyleaflet version with two-way interaction in Jupyter, and leafmap.maplibregl a MapLibre (WebGL) version with 3D and vector tiles. The calls are the same.

A classified choropleth with a legend and hover information is one call, add_data:

Code
# leafmap choropleth of poverty with Fisher-Jenks classes and division outlines
m = leafmap.Map(center=[23.75, 90.3], zoom=7, draw_control=False, measure_control=False)
m.add_basemap("Esri.WorldGrayCanvas")
m.add_data(districts_web.dropna(subset=["poverty_pct"])[["district", "division", "poverty_pct", "geometry"]],
           column="poverty_pct", scheme="FisherJenks", k=5, cmap="YlOrRd",
           legend_title="Poverty (%)", layer_name="Poverty, natural breaks")
m.add_gdf(divisions_web, layer_name="Divisions", style={"color": "#222", "weight": 2, "fill": False})
save(m, "leafmap_poverty.html")
m

A split-screen comparison of the two NDVI dates takes one call too. leafmap accepts a tile URL, a basemap name, or (with localtileserver installed) a local GeoTIFF directly.

Code
# leafmap split map of July vs September NDVI XYZ tiles
def leafmap_split(prefix):
    m = leafmap.Map(center=[43.04, -76.13], zoom=12, draw_control=False, measure_control=False)
    m.split_map(left_layer=f"{prefix}ndvi_tiles_20250723/{{z}}/{{x}}/{{y}}.png",
                right_layer=f"{prefix}ndvi_tiles_20250919/{{z}}/{{x}}/{{y}}.png",
                left_label="NDVI 23 Jul 2025", right_label="NDVI 19 Sep 2025",
                left_args={"max_native_zoom": 14}, right_args={"max_native_zoom": 14})
    return m

save(leafmap_split(""), "leafmap_ndvi_split.html")
leafmap_split(server.url.rstrip("/") + "/")
Task Folium leafmap
Classified choropleth with legend mapclassify + StepColormap + GeoJson + style function (Section 5) m.add_data(gdf, column, scheme=...)
Basemaps Tile URL and attribution 100+ names (xyzservices), e.g. "Esri.WorldGrayCanvas"
Split map SideBySideLayers with two layers m.split_map(left, right)
Local GeoTIFF Reproject + ImageOverlay, or make tiles m.add_raster(path) (needs localtileserver)
Cloud-Optimized GeoTIFF / STAC Tile URL from a tile server m.add_cog_layer(url), m.add_stac_layer(...) (via a TiTiler endpoint)

leafmap is the quicker route for exploration; Folium gives full control over every style and element. Both produce the same Leaflet maps.

lonboard: GPU rendering of large data

Leaflet draws each feature as an SVG or canvas shape, managed by JavaScript. That is flexible but slows down beyond a few tens of thousands of features. lonboard sends data from Python to the browser as GeoArrow columns inside a compressed Parquet buffer, and draws them with deck.gl on the GPU. Colours, radii and line widths are given as arrays, one value per feature.

The 37,923 soil samples, coloured by pH:

Code
# Lonboard GPU scatterplot of soil pH for a large point layer
t0 = time.perf_counter()
ph_scaled = ((soil.PH.clip(4, 8) - 4) / 4).values
soil_layer = ScatterplotLayer.from_geopandas(
    soil[["PH", "SOM", "DISTRICT_NAME", "geometry"]],
    get_fill_color=apply_continuous_cmap(ph_scaled, matplotlib.colormaps["RdYlBu"]),
    get_radius=400, radius_min_pixels=1.5, opacity=0.8, pickable=True)
soil_map = LonboardMap(soil_layer, view_state={"longitude": 90.3, "latitude": 23.75, "zoom": 6.3})
print(f"layer built in {time.perf_counter() - t0:.2f} s")
soil_map
layer built in 0.05 s

Click a point to see its attributes. pH runs from red (acid, pH 4) to blue (alkaline, pH 8). The pattern is clear at once: acid soils (red) in the north-east and east, where Maulvibazar (median pH 4.6), Netrokona, Sylhet and Habiganj are the most acid districts, and alkaline soils (blue) in the west-central districts on the Ganges floodplain, where Rajbari (8.2), Faridpur, Kushtia and Jhenaidah have median pH near 8. Building the layer took 0.05 s.

Next, all 5,160 unions. With Leaflet this many detailed polygons would not be practical; with lonboard we compare the full-resolution layer (7.8 million vertices) with a coverage-simplified one.

Code
# Coverage-simplify unions and compare Lonboard HTML size full vs simplified
unions = gpd.read_file(BD / "Shapefiles" / "bd_union_GCS.shp")[["ADM4_EN", "ADM3_EN", "ADM2_EN", "geometry"]]
t0 = time.perf_counter()
unions_web = web_ready(unions, tolerance=100)
print(f"coverage-simplified {len(unions):,} unions in {time.perf_counter() - t0:.1f} s: "
      f"{unions.geometry.count_coordinates().sum():,} -> {unions_web.geometry.count_coordinates().sum():,} vertices")

def union_layer(gdf):
    area = gdf.to_crs(32646).area.values / 1e6
    shade = (np.log10(area).clip(0, 2.5)) / 2.5                    # union size, 1 to ~300 km²
    return PolygonLayer.from_geopandas(gdf, get_fill_color=apply_continuous_cmap(shade, matplotlib.colormaps["viridis"], alpha=0.7),
                                       get_line_color=[255, 255, 255, 160], line_width_min_pixels=0.3, pickable=True)

rows = []
for name, gdf in [("full resolution", unions), ("coverage-simplified, 100", unions_web)]:
    t0 = time.perf_counter()
    html = LonboardMap(union_layer(gdf)).to_html()
    rows.append({"unions layer": name, "vertices": gdf.geometry.count_coordinates().sum(),
                 "HTML MB": round(len(html) / 1e6, 1), "seconds": round(time.perf_counter() - t0, 1)})
empty_html = LonboardMap(ScatterplotLayer.from_geopandas(soil.iloc[:1][["geometry"]])).to_html()
rows.append({"unions layer": "(lonboard page with one point)", "vertices": 1,
             "HTML MB": round(len(empty_html) / 1e6, 1), "seconds": np.nan})
lonboard_table = pd.DataFrame(rows)
lonboard_table
coverage-simplified 5,160 unions in 11.5 s: 7,768,324 -> 433,126 vertices
unions layer vertices HTML MB seconds
0 full resolution 7768324 155.1 3.5
1 coverage-simplified, 100 433126 9.1 0.4
2 (lonboard page with one point) 1 4.6 NaN

A lonboard HTML page carries the deck.gl bundle (4.6 MB, the page with a single point) plus the data as Parquet. The simplified unions add about 4.5 MB of data, giving a 9.1 MB page; at full resolution the page is 155 MB, too large to share, even though lonboard could draw it in a live notebook. Simplification still matters with GPU rendering: it decides how much has to travel. In a notebook, lonboard streams the same binary data to the browser through the Jupyter connection instead of embedding it in HTML.

For comparison, the soil-pH page (lonboard_soil.html) is 5.7 MB, about 1.1 MB more than the empty page, for 37,923 points with a colour each. In Folium, the GeoJSON version without colours was 6.8 MB.

The simplified unions and the soil samples together, saved as one HTML file:

Code
# Combine simplified unions and soil points in one Lonboard map; save HTML
soil_small = ScatterplotLayer.from_geopandas(
    soil[["PH", "geometry"]], get_fill_color=apply_continuous_cmap(ph_scaled, matplotlib.colormaps["RdYlBu"]),
    get_radius=150, radius_min_pixels=0.8, opacity=0.9, pickable=True)
union_map = LonboardMap([union_layer(unions_web), soil_small],
                        view_state={"longitude": 90.3, "latitude": 23.75, "zoom": 6.3})
union_map.to_html(OUT / "lonboard_unions_soil.html", title="Bangladesh unions and soil samples")
sizes["lonboard_unions_soil.html"] = mb(OUT / "lonboard_unions_soil.html")
soil_map.to_html(OUT / "lonboard_soil.html", title="Bangladesh soil pH")
sizes["lonboard_soil.html"] = mb(OUT / "lonboard_soil.html")
print({k: round(v, 1) for k, v in sizes.items() if k.startswith("lonboard")})
union_map
{'lonboard_unions_soil.html': 10.2, 'lonboard_soil.html': 5.7}

Sharing maps and choosing a library

Every map in this notebook was saved as an HTML file. Their sizes, and the external resources each one still loads from the internet:

Code
# Inventory external hosts each saved HTML map depends on (scripts, CSS, tiles)
def external(path):
    "Distinct external hosts a saved map loads scripts, styles or tiles from."
    text = open(path, encoding="utf-8").read()
    urls = [u for u in re.findall(r"https?://[^\s\"'\\<>]+", text)
            if re.search(r"\.(js|css)(\?|$)|\{z\}|style\.json", u) and "github.com" not in u]   # code, tiles, map styles
    return sorted({re.sub(r"^https?://([^/]+).*", r"\1", u) for u in urls})

share = pd.DataFrame([{"file": n, "kB": round(s * 1000), "external hosts": len(external(OUT / n)),
                       "hosts": ", ".join(external(OUT / n))} for n, s in sizes.items()])
with pd.option_context("display.max_colwidth", 200):
    display(share.sort_values("kB"))
file kB external hosts hosts
9 ndvi_side_by_side.html 5 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
11 leafmap_ndvi_split.html 7 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, tile.openstreetmap.org
2 arsenic_fields.html 359 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
1 districts_poverty_jenks.html 724 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
6 soil_fastmarkercluster.html 830 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
7 soil_heatmap_density_only.html 830 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
10 leafmap_poverty.html 1057 6 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com, tile.openstreetmap.org
0 districts_poverty.html 1093 6 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com, tile.openstreetmap.org
8 ndvi_image_overlay.html 3365 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
13 lonboard_soil.html 5742 3 basemaps.cartocdn.com, cdn.jsdelivr.net, cdnjs.cloudflare.com
4 soil_one_geojson_layer.html 6832 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
5 soil_markercluster.html 7959 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com
12 lonboard_unions_soil.html 10192 3 basemaps.cartocdn.com, cdn.jsdelivr.net, cdnjs.cloudflare.com
3 soil_one_circlemarker_per_sample.html 18084 5 cdn.jsdelivr.net, cdnjs.cloudflare.com, code.jquery.com, netdna.bootstrapcdn.com, server.arcgisonline.com

Every saved map depends on outside servers: Folium maps load Leaflet, jQuery and Bootstrap from four content-delivery networks plus the basemap host, and lonboard pages load the widget manager from two CDNs and the CARTO vector basemap style. A map opened offline shows the data only if the scripts can load, so for offline use, save the scripts locally or render a static image. Sizes range from 5 kB (the tile maps, whose tiles live in their own folders) to 18 MB (one marker per sample).

Where the maps display

Place Folium / leafmap.foliumap ipyleaflet, leafmap (default) lonboard
Jupyter, VS Code, Colab Yes (HTML output) Yes, with a live kernel Yes, with a live kernel
Saved notebook on nbviewer Yes Only if widget state was saved Only if widget state was saved
Notebook preview on GitHub No (GitHub strips the embedded map) No No
Saved .html file Yes m.to_html() m.to_html()
Web site, Quarto, Jupyter Book Embed the HTML (iframe) As HTML export As HTML export

Choosing a library

Situation Choice
A map to email, embed in a report or put on a web page Folium (or leafmap.foliumap)
Quick exploration with basemaps, rasters, STAC and split views leafmap
Maps that react to Python (draw a polygon, then run an analysis) ipyleaflet or leafmap’s default backend
More than ~50,000 features, or millions of points lonboard
3D extrusions, arcs, hexagon bins pydeck or lonboard
A map inside a dashboard or app Notebook 08_07 (Streamlit, Panel, Solara)
Publishing tiles and APIs for many users Notebook 08_05 (geolattice.web.create_app, PMTiles)
Code
# Stop the static server and report total output size
server.stop()
print("static server stopped; outputs in", OUT, f"({sum(f.stat().st_size for f in OUT.rglob('*') if f.is_file()) / 1e6:.0f} MB)")
static server stopped; outputs in ../../../data/data_web_cloud_gis/08_04_outputs (80 MB)

Summary and exercises

Key ideas

  • A web map sends its data to the browser. Measure that payload before publishing: vertices and coordinate digits, not the number of features, decide the size.
  • Simplify polygon coverages with a coverage-aware method (shapely.coverage_simplify); simplifying polygons one at a time opens gaps and overlaps between neighbours.
  • Five decimal places (about 1 m) are enough coordinates for almost any web map.
  • Class breaks change what a choropleth says; report the scheme, and check it with the GVF.
  • Thousands of points need clustering, heat maps or GPU rendering; per-marker objects do not scale.
  • Rasters must be in Web Mercator before they meet a web map; never place a projected image by its lon/lat corners. Tiles send only what is in view.
  • Folium and leafmap make portable Leaflet maps; lonboard draws large data from GeoArrow on the GPU.

What we measured

  • 64 districts carried 1.06 million vertices (43 MB of GeoJSON); coverage simplification and five decimals reduced them to 31,423 vertices and 0.70 MB.
  • One-at-a-time simplification of 544 upazilas opened 5,555-8,262 gaps; coverage simplification opened none.
  • Natural breaks gave the best class fit for district poverty (GVF 0.928, against 0.823 for head/tail breaks).
  • 37,923 points: 18 MB as individual markers, 6.8 MB as one GeoJSON layer, 0.83 MB as a fast cluster or heat map, 5.7 MB as a lonboard page (4.6 MB of it the library).
  • A UTM image placed by its lon/lat corners was misplaced by up to 200 m; reprojected tiles fixed this, and a map view needed at most 20 tiles (2.85 MB) instead of a 3.4 MB overlay.
  • CARTO basemap tiles now need an API key; check basemap terms before publishing.

Exercises

  1. Map union-level data with Folium: join poverty_clean from Notebook 08_03 to the coverage-simplified unions through ADM3_PCODE. How large is the HTML at tolerances 100, 250 and 500?
  2. Simplify the district layer one polygon at a time with tolerance=500 and draw it with Folium on satellite imagery. Find the largest gap and measure it with the measure control.
  3. Make a choropleth of rice production per km² with quantiles and with natural breaks. Which districts change class, and which map would you publish?
  4. Colour the lonboard soil map by soil organic matter (SOM) instead of pH, and add a HeatmapLayer. Where are organic-rich soils concentrated?
  5. Make XYZ tiles of the NDVI difference (September minus July) with a diverging colour map, and show it with leafmap over satellite imagery.

References

  • Folium documentation. https://python-visualization.github.io/folium/
  • Wu, Q. (2021). leafmap: A Python package for interactive mapping and geospatial analysis with minimal coding in a Jupyter environment. Journal of Open Source Software, 6(63), 3414.
  • lonboard documentation. https://developmentseed.org/lonboard/
  • Leaflet documentation. https://leafletjs.com
  • Jenks, G. F. (1967). The data model concept in statistical mapping. International Yearbook of Cartography, 7, 186-190.
  • Rey, S. J., Arribas-Bel, D. & Wolf, L. J. (2023). Geographic Data Science with Python, ch. 5 (choropleth mapping). CRC Press.
  • GEOS CoverageSimplifier and Shapely coverage_simplify. https://shapely.readthedocs.io
Back to top