Search code examples
pythongeolocationgisgeojsonkml

Converting Geojson to kml using Python


I can convert it kml/kmz to geojson also, creating kml from geojson..

I tried with the below libraries

Shapely
kml2geojson
geojson

Source code below..

import json
import simplekml


with open('file.geojson') as f:
    data = json.load(f)
kml = simplekml.Kml()
for feature in data['features']:
    if feature['geometry']['type'] == 'Polygon':
        kml.newpolygon(name=name,
                       description='test',
                       outerboundaryis=feature['geometry']['coordinates'][0])
    elif feature['geometry']['type'] == 'LineString':
        kml.newlinestring(name=name,
                          description='test',
                          coords=feature['geometry']['coordinates'])

    elif feature['geometry']['type'] == 'Point':
        kml.newpoint(name=name,
                     description='test',
                     coords=[feature['geometry']['coordinates']])
kml.save('file.kml')

Solution

  • Finally can able to convert geojson file to kml using

    import simplekml
    
    import simplekml
    import json
    
    with open("myfile.geojson") as f:
        data = json.load(f)
    kml = simplekml.Kml()
    for feature in data['features']:
        geom = feature['geometry']
        geom_type = geom['type']
        if geom_type == 'Polygon':
            kml.newpolygon(name='test',
                           description='test',
                           outerboundaryis=geom['coordinates'][0])
        elif geom_type == 'LineString':
            kml.newlinestring(name='test',
                              description='test',
                              coords=geom['coordinates'])
        elif geom_type == 'Point':
            kml.newpoint(name='test',
                         description='test',
                         coords=[geom['coordinates']])
        else:
            print("ERROR: unknown type:", geom_type)
    kml.save('kml_file.kml')
    

    This working fine to me..