aboutsummaryrefslogtreecommitdiff
path: root/src/geojson2kml.py
blob: b923d988a1501429a718535ca41b2e27c88db3c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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()