From 90251b41d9e92c3330b0edbf59b9ef304e863961 Mon Sep 17 00:00:00 2001 From: GuilhermeStrice Date: Fri, 5 Sep 2025 18:36:41 +0000 Subject: [PATCH] Add geojson_to_poly.py --- geojson_to_poly.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 geojson_to_poly.py diff --git a/geojson_to_poly.py b/geojson_to_poly.py new file mode 100644 index 0000000..0df4499 --- /dev/null +++ b/geojson_to_poly.py @@ -0,0 +1,58 @@ +import json +import sys +import os + +def write_polygon(f, coords): + """Write a single polygon ring to the poly file.""" + # Close polygon if not already closed + if coords[0] != coords[-1]: + coords.append(coords[0]) + for lon, lat in coords: + f.write(f" {lon} {lat}\n") + f.write("END\n") + +def geojson_to_poly(geojson_file): + base_name = os.path.splitext(os.path.basename(geojson_file))[0] + poly_file = f"{base_name}.poly" + + with open(geojson_file, 'r', encoding='utf-8') as f: + data = json.load(f) + + with open(poly_file, 'w', encoding='utf-8') as f: + f.write(f"{base_name}\n") + feature_index = 1 + + for feature in data["features"]: + geom_type = feature["geometry"]["type"] + coords = feature["geometry"]["coordinates"] + + if geom_type == "Polygon": + # Handle flat array: [ [lon, lat], ... ] + if isinstance(coords[0][0], float): + coords = [coords] + for ring in coords: + f.write(f"{feature_index}\n") + write_polygon(f, ring) + feature_index += 1 + + elif geom_type == "MultiPolygon": + for poly in coords: + # Each poly is [ [ [lon, lat], ... ] ] + ring = poly[0] # use outer ring only + f.write(f"{feature_index}\n") + write_polygon(f, ring) + feature_index += 1 + else: + print(f"Skipping unsupported geometry type: {geom_type}") + + f.write("END\n") + + print(f"Created .poly file: {poly_file}") + +if __name__ == "__main__": + if len(sys.argv) < 2: + print("Usage: python geojson_to_poly.py ") + sys.exit(1) + + geojson_file = sys.argv[1] + geojson_to_poly(geojson_file) \ No newline at end of file