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)