diff options
| author | gdamms <damguillotin@gmail.com> | 2026-07-24 12:44:20 +0200 |
|---|---|---|
| committer | gdamms <damguillotin@gmail.com> | 2026-07-24 12:44:20 +0200 |
| commit | 77aed43a99a295f3202063edefcb7ce01e011958 (patch) | |
| tree | e34a042a75cdb52e2d30afc11dc82660c22f36d5 /src/geojson2kml.py | |
| download | dog-friendly-data-77aed43a99a295f3202063edefcb7ce01e011958.tar.gz dog-friendly-data-77aed43a99a295f3202063edefcb7ce01e011958.zip | |
first commit
Diffstat (limited to 'src/geojson2kml.py')
| -rw-r--r-- | src/geojson2kml.py | 61 |
1 files changed, 61 insertions, 0 deletions
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() |
