aboutsummaryrefslogtreecommitdiff
path: root/src/geojson2kml.py
blob: 8c116f0c27dcab9ed9f8f1a55d068d4dd5f3d512 (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
import argparse
import json
import xml.etree.ElementTree as ET

from kml_utils import add_placemark, add_polygon, new_document, write_kml


def geojson_to_kml(geojson: dict) -> ET.Element:
    """Convert a GeoJSON FeatureCollection into a KML tree.

    Only MultiPolygon features are supported; other geometry types are skipped.

    Args:
        geojson (dict): Parsed GeoJSON FeatureCollection.
    Returns:
        ET.Element: The root <kml> element.
    """
    root, document = new_document(geojson.get("name", "Unnamed"))

    for feature in geojson.get("features", []):
        geometry_type = feature["geometry"]["type"]
        if geometry_type != "MultiPolygon":
            print(f"Skipping feature with unsupported geometry type: {geometry_type}")
            continue

        placemark = add_placemark(document)
        for ring in feature["geometry"]["coordinates"][0]:
            add_polygon(placemark, ring)

    return root


def main():
    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", 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 or args.input_file.rsplit(".", 1)[0] + ".kml"

    root = geojson_to_kml(geojson)
    write_kml(root, output_file)


if __name__ == "__main__":
    main()