From 77aed43a99a295f3202063edefcb7ce01e011958 Mon Sep 17 00:00:00 2001 From: gdamms Date: Fri, 24 Jul 2026 12:44:20 +0200 Subject: first commit --- src/geojson2kml.py | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/geojson2kml.py (limited to 'src/geojson2kml.py') diff --git a/src/geojson2kml.py b/src/geojson2kml.py new file mode 100644 index 0000000..b923d98 --- /dev/null +++ b/src/geojson2kml.py @@ -0,0 +1,61 @@ +import json +import xml.etree.ElementTree as ET + + +KML_NS = "http://www.opengis.net/kml/2.2" +ET.register_namespace("", KML_NS) + + +def geojson_to_kml(geojson: dict) -> ET.ElementTree[ET.Element]: + root = ET.Element(f"kml", xmlns=KML_NS) + document = ET.SubElement(root, f"Document") + + ET.SubElement(document, f"name").text = geojson.get("name", "Unnamed") + + for feature in geojson.get("features", []): + placemark = ET.SubElement(document, f"Placemark") + + ET.SubElement(placemark, f"name").text = "" + ET.SubElement(placemark, f"description").text = "" + + # TODO: Handle other geometry types if needed + if feature["geometry"]["type"] != "MultiPolygon": + print(f"Skipping feature with unsupported geometry type: {feature['geometry']['type']}") + continue + + for polygon in feature["geometry"]["coordinates"][0]: + polygon_el = ET.SubElement(placemark, f"Polygon") + + outer = ET.SubElement(polygon_el, f"outerBoundaryIs") + ring = ET.SubElement(outer, f"LinearRing") + + coords = ET.SubElement(ring, f"coordinates") + coords.text = "\n".join( + f"{lon},{lat}" + for lon, lat in polygon + ) + + ET.indent(root) + + return ET.ElementTree(root) + + +def main(): + import argparse + + parser = argparse.ArgumentParser(description="Convert GeoJSON to KML") + parser.add_argument("input_file", help="Path to the input GeoJSON file") + parser.add_argument("-o", "--output_file", help="Path to the output KML file") + args = parser.parse_args() + + with open(args.input_file, "r") as geojson_file: + geojson = json.load(geojson_file) + + output_file = args.output_file or args.input_file.rsplit(".", 1)[0] + ".kml" + + kml = geojson_to_kml(geojson) + kml.write(output_file, encoding="utf-8", xml_declaration=True) + + +if __name__ == "__main__": + main() -- cgit v1.3.1