state map

This commit is contained in:
chrisbell committed 2026-11-22 13:39:20 -06:00
1 parent 1c38a7bdb0
commit 8e2fa637bc
8 files changed
+183 -9

No files matched your search

+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env python3
"""Generate static/assets/alabama-counties.svg from Census cartographic boundaries.
Source: U.S. Census Bureau 2024 cartographic boundary file, counties, 1:500,000
(CC0 / public domain). Needs `pyshp` (import name: shapefile) and internet access.
Run from the repo root, after make_county_stubs.py:
python scripts/make_county_map.py
Each county becomes a real link to /act/<slug>-county/, so the map works without
JavaScript. The download (~11 MB) is cached in .cache/ (add it to .gitignore).
"""
import io
import math
import urllib.request
import zipfile
from pathlib import Path
import shapefile # pyshp
import yaml
URL = "https://www2.census.gov/geo/tiger/GENZ2024/shp/cb_2024_us_county_500k.zip"
CACHE = Path(".cache/cb_2024_us_county_500k.zip")
OUT = Path("static/assets/alabama-counties.svg")
HEIGHT = 800 # SVG units; width follows from the state's aspect ratio
# Our county records, keyed by FIPS
counties = {}
for p in Path("data/counties").glob("*.yaml"):
c = yaml.safe_load(p.read_text(encoding="utf-8"))
counties[str(c["fips"]).zfill(5)] = c
assert len(counties) == 67, "run scripts/make_county_stubs.py first"
# Download once
if not CACHE.exists():
CACHE.parent.mkdir(exist_ok=True)
print("Downloading Census county boundaries (~11 MB)...")
urllib.request.urlretrieve(URL, CACHE)
with zipfile.ZipFile(CACHE) as z:
def member(ext):
return io.BytesIO(z.read(next(n for n in z.namelist() if n.endswith(ext))))
reader = shapefile.Reader(
shp=member(".shp"), shx=member(".shx"), dbf=member(".dbf")
)
fields = [f[0] for f in reader.fields[1:]]
shapes = {}
for sr in reader.iterShapeRecords():
rec = dict(zip(fields, sr.record))
if rec["STATEFP"] == "01":
shapes[rec["GEOID"]] = sr.shape
assert set(shapes) == set(counties), set(shapes) ^ set(counties)
# Simple projection: equirectangular, scaled by cos(latitude) so shapes look right
lons = [pt[0] for s in shapes.values() for pt in s.points]
lats = [pt[1] for s in shapes.values() for pt in s.points]
min_lon, max_lon, min_lat, max_lat = min(lons), max(lons), min(lats), max(lats)
k = math.cos(math.radians((min_lat + max_lat) / 2))
scale = HEIGHT / (max_lat - min_lat)
width = round((max_lon - min_lon) * k * scale)
def project(pt):
return (
round((pt[0] - min_lon) * k * scale, 1),
round((max_lat - pt[1]) * scale, 1),
)
def path_d(shape):
parts = list(shape.parts) + [len(shape.points)]
rings = []
for start, end in zip(parts, parts[1:]):
pts = []
for pt in shape.points[start:end]:
xy = project(pt)
if not pts or xy != pts[-1]: # drop points that round to the same spot
pts.append(xy)
if len(pts) >= 3:
rings.append("M" + "L".join(f"{x:g},{y:g}" for x, y in pts) + "Z")
return "".join(rings)
links = []
for fips in sorted(counties, key=lambda f: counties[f]["name"]):
c = counties[fips]
label = f"{c['name']} County"
links.append(
f'<a href="/act/{c["slug"]}-county/" aria-label="{label}">'
f'<path id="county-{c["slug"]}" d="{path_d(shapes[fips])}"><title>{label}</title></path></a>'
)
svg = (
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {HEIGHT}" '
f'role="group" aria-label="Map of Alabama counties">\n'
+ "\n".join(links)
+ "\n</svg>\n"
)
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(svg, encoding="utf-8")
print(f"Wrote {OUT} ({OUT.stat().st_size / 1024:.0f} KB, {len(links)} counties)")