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()