Created
October 18, 2025 06:31
-
-
Save docuracy/323632213a194dbf11796b1528f64a58 to your computer and use it in GitHub Desktop.
Convert GeometryCollections to MultiPolygons to facilitate visualisation in QGIS. Any Point or Line geometries are dropped.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import json | |
| import requests | |
| from shapely.geometry import shape, mapping, MultiPolygon, GeometryCollection | |
| # --- Fetch JSON from GitHub --- | |
| URL = "https://raw.githubusercontent.com/periodo/periodo-places/2b0e7c9db27ada2fa9a73ab7e9a222b27ee827f2/gazetteers/subregions.json" | |
| print(f"Fetching data from {URL} ...") | |
| r = requests.get(URL) | |
| r.raise_for_status() | |
| data = r.json() | |
| # --- Function to convert GeometryCollections to MultiPolygons --- | |
| def convert_geom(feature): | |
| geom = feature.get("geometry") | |
| if geom is None: | |
| return feature # no geometry to convert | |
| g = shape(geom) | |
| if isinstance(g, GeometryCollection): | |
| # extract polygons only | |
| polygons = [p for p in g.geoms if p.geom_type == "Polygon" or p.geom_type == "MultiPolygon"] | |
| if polygons: | |
| # combine into a single MultiPolygon | |
| combined = MultiPolygon([p for poly in polygons for p in (poly.geoms if poly.geom_type == "MultiPolygon" else [poly])]) | |
| feature["geometry"] = mapping(combined) | |
| else: | |
| # no polygons, keep as empty geometry collection | |
| feature["geometry"] = mapping(g) | |
| return feature | |
| # --- Apply conversion to all features --- | |
| features = data.get("features", []) | |
| converted_features = [convert_geom(f) for f in features] | |
| data["features"] = converted_features | |
| # --- Write out the new GeoJSON --- | |
| OUTPUT = "subregions_qgis_ready.json" | |
| with open(OUTPUT, "w", encoding="utf-8") as f: | |
| json.dump(data, f, ensure_ascii=False, indent=2) | |
| print(f"Converted {len(features)} features. Output written to {OUTPUT}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment