""" Generates `lib/geo/language-map.ts`: the language regions of Switzerland and the Swiss German dialect areas, as SVG paths. python3 scripts/build-language-map.py The output is COMMITTED; this script is the record of where every border came from, so nobody edits coordinates by hand. GEOMETRY swissBOUNDARIES3D, Federal Office of Topography swisstopo, release 2025-04 (tlm_hoheitsgebiet: the 2128 municipal areas, LV95). https://data.geo.admin.ch/ch.swisstopo.swissboundaries3d/swissboundaries3d_2025-04/swissboundaries3d_2025-04_2056_5728.gpkg.zip Free geodata: may be processed and used commercially; the source must be named ("©swisstopo"). https://www.swisstopo.admin.ch/de/nutzungsbedingungen-kostenlose-geodaten-und-geodienste LANGUAGE Federal Statistical Office (BFS), Raumgliederungen der Schweiz, «Sprachgebiete 2020», municipalities as of 1.1.2025: the result page of https://www.agvchapp.bfs.admin.ch/de/typologies/query saved as HTML (1 German, 2 French, 3 Italian, 4 Romansh). Both opened 2026-11-26. WHAT IS DRAWN. A municipality takes the language region the BFS gives it. Inside the German-speaking region, municipalities are grouped by canton into the pack's dialect areas (`AREAS` below) — a handle, not an isogloss: dialect borders do not follow canton borders, and the page says so. Lakes that belong to no municipality stay empty. Three Ticino areas missing from the BFS table (two shared territories and Lema, merged in 2025) take Italian, the only language region of their canton besides one German village. Dissolved and simplified with mapshaper 0.6 (`-dissolve area -simplify 1.2% keep-shapes weighted -filter-islands min-area=4000000`), then scaled to a 1000-unit-wide viewBox with north up. """ import subprocess, tempfile, os import sqlite3, struct, json, re, sys GPKG, BFS_HTML = sys.argv[1], sys.argv[2] c = sqlite3.connect(GPKG) # language per commune, BFS Raumgliederungen (Sprachgebiete 2020), Gemeindestand 1.1.2025 t = open(BFS_HTML, encoding='utf8').read() lang = {} for r in re.findall(r'', t, flags=re.S): cells = [re.sub(r'<[^>]+>', '', x).strip() for x in re.findall(r'', r, flags=re.S)] if len(cells) >= 7 and cells[1].isdigit(): lang[int(cells[1])] = (int(cells[-1]), cells[3]) print('communes with language', len(lang), file=sys.stderr) # The counts `lib/config/languages.ts` states (LANGUAGE_FACTS.communes, .cantons): # printed here so a new table is one run away from new figures. from collections import Counter print('communes per region (1 de, 2 fr, 3 it, 4 rm):', dict(Counter(v[0] for v in lang.values())), file=sys.stderr) print('cantons per region:', {r: sorted({v[1] for v in lang.values() if v[0] == r}) for r in (2, 3, 4)}, file=sys.stderr) def wkb(buf, o): bo = '<' if buf[o] == 1 else '>' (typ,) = struct.unpack_from(bo + 'I', buf, o + 1); o += 5 hasz = typ >= 1000 and typ < 2000 or (typ & 0x80000000) != 0 hasm = typ >= 2000 base = typ % 1000 if typ < 0x80000000 else typ & 0xff dim = 2 + (1 if (1000 <= typ < 2000 or 3000 <= typ < 4000 or typ & 0x80000000) else 0) + (1 if 2000 <= typ < 4000 else 0) def ring(o): (n,) = struct.unpack_from(bo + 'I', buf, o); o += 4 pts = [] for i in range(n): x, y = struct.unpack_from(bo + 'dd', buf, o); o += 8 * dim pts.append([round(x, 1), round(y, 1)]) return pts, o if base == 3: (n,) = struct.unpack_from(bo + 'I', buf, o); o += 4 rings = [] for i in range(n): r, o = ring(o); rings.append(r) return [rings], o if base == 6: (n,) = struct.unpack_from(bo + 'I', buf, o); o += 4 polys = [] for i in range(n): p, o = wkb(buf, o); polys += p return polys, o raise Exception('type %d' % typ) def geom(blob): flags = blob[3] env = {0: 0, 1: 32, 2: 48, 3: 48, 4: 64}[(flags >> 1) & 7] return wkb(blob, 8 + env)[0] KT = {1:'ZH',2:'BE',3:'LU',4:'UR',5:'SZ',6:'OW',7:'NW',8:'GL',9:'ZG',10:'FR',11:'SO',12:'BS',13:'BL',14:'SH',15:'AR',16:'AI',17:'SG',18:'GR',19:'AG',20:'TG',21:'TI',22:'VD',23:'VS',24:'NE',25:'GE',26:'JU'} AREAS = {'ZH':'zueriduetsch','BE':'baerndueuetsch','BS':'baseldytsch','BL':'baseldytsch','LU':'innerschwyzertuetsch','UR':'innerschwyzertuetsch','SZ':'innerschwyzertuetsch','OW':'innerschwyzertuetsch','NW':'innerschwyzertuetsch','ZG':'innerschwyzertuetsch','SG':'ostschwiizertuetsch','TG':'ostschwiizertuetsch','AR':'ostschwiizertuetsch','AI':'ostschwiizertuetsch','SH':'ostschwiizertuetsch','AG':'aargauerdueuetsch','GL':'glarnertueuetsch','SO':'solothurnerdueuetsch','FR':'seyslerdueuetsch','GR':'buendnerdueuetsch','VS':'wallisertitsch'} feats = [] for bfs, kt, name, art, icc, blob in c.execute("select bfs_nummer,kantonsnummer,name,objektart,icc,geom from tlm_hoheitsgebiet"): if icc != 'CH': continue code = lang.get(bfs, (0,))[0] if code == 0 and KT.get(kt) == 'TI' and art != 'Kantonsgebiet': code = 3 area = {0: 'water', 2: 'fr', 3: 'it', 4: 'rm'}.get(code) or AREAS.get(KT.get(kt), 'de-other') feats.append({'type': 'Feature', 'properties': {'area': area}, 'geometry': {'type': 'MultiPolygon', 'coordinates': geom(blob)}}) tmp = tempfile.mkdtemp() json.dump({'type': 'FeatureCollection', 'features': feats}, open(os.path.join(tmp, 'in.json'), 'w')) subprocess.run(['npx', '--yes', 'mapshaper@0.6', os.path.join(tmp, 'in.json'), '-dissolve', 'area', '-simplify', '1.2%', 'keep-shapes', 'weighted', '-filter-islands', 'min-area=4000000', '-o', 'precision=1', os.path.join(tmp, 'out.json')], check=True) d = json.load(open(os.path.join(tmp, 'out.json'))) def polys(g): return g['coordinates'] if g['type'] == 'MultiPolygon' else [g['coordinates']] xs = [x for f in d['features'] for p in polys(f['geometry']) for r in p for x, y in r] ys = [y for f in d['features'] for p in polys(f['geometry']) for r in p for x, y in r] minx, maxx, miny, maxy = min(xs), max(xs), min(ys), max(ys) W = 1000; s = W / (maxx - minx); H = round((maxy - miny) * s) paths = {}; marks = {} for f in d['features']: parts = []; best = None for p in polys(f['geometry']): ring = [(round((x - minx) * s), round((maxy - y) * s)) for x, y in p[0]] # the area's mark sits at the centroid of its largest piece a2 = sum(ring[i][0] * ring[i + 1][1] - ring[i + 1][0] * ring[i][1] for i in range(len(ring) - 1)) if a2 and (best is None or abs(a2) > abs(best[0])): cx = sum((ring[i][0] + ring[i + 1][0]) * (ring[i][0] * ring[i + 1][1] - ring[i + 1][0] * ring[i][1]) for i in range(len(ring) - 1)) / (3 * a2) cy = sum((ring[i][1] + ring[i + 1][1]) * (ring[i][0] * ring[i + 1][1] - ring[i + 1][0] * ring[i][1]) for i in range(len(ring) - 1)) / (3 * a2) best = (a2, round(cx), round(cy)) for r in p: pts = [(round((x - minx) * s), round((maxy - y) * s)) for x, y in r] ded = [pts[0]] for q in pts[1:]: if q != ded[-1]: ded.append(q) if len(ded) < 4: continue px, py = ded[0]; seg = f'M{px} {py}' for x, y in ded[1:-1]: seg += f'l{x - px} {y - py}'; px, py = x, y parts.append(seg + 'z') paths[f['properties']['area']] = ''.join(parts) marks[f['properties']['area']] = best[1:] out = ['/**', ' * GENERATED by `scripts/build-language-map.py` — do not edit by hand.', ' *', ' * Geometry: swissBOUNDARIES3D 2025-04, ©swisstopo. Language regions: BFS,', ' * Raumgliederungen der Schweiz, «Sprachgebiete 2020» (municipalities 1.1.2025).', ' * Dialect areas are cantons inside the German-speaking region: a handle for', ' * the reader, not a claim about where a dialect ends.', ' */', f'export const LANGUAGE_MAP = {{', f' width: {W},', f' height: {H},', ' shapes: {'] for k in sorted(paths): out.append(f' {json.dumps(k)}: {{ at: [{marks[k][0]}, {marks[k][1]}], d: {json.dumps(paths[k])} }},') out += [' },', '} as const;', '', 'export type MapShapeId = keyof typeof LANGUAGE_MAP.shapes;', ''] open('lib/geo/language-map.ts', 'w').write('\n'.join(out)) print('wrote lib/geo/language-map.ts', sum(len(v) for v in paths.values()), 'path bytes', file=sys.stderr)