How to convert from kml to GeoJson with python3

To do it, you can import ogr from osgeo

from osgeo import ogr

def kml2geojson(kml_file):
    drv = ogr.GetDriverByName('KML')
    kml_ds = drv.Open(kml_file)
    for kml_lyr in kml_ds:
        for feat in kml_lyr:
            print feat.ExportToJson()

kml2geojson('/path/to/your.kml')

But, if you try to run it, maybe you will see the following error:

ImportError: No module named 'osgeo'

This means that you need gdal libraries. If you try to install it with pip3 you will see the following:

pip3 install gdal
...
cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++
    extensions/gdal_wrap.cpp:3168:22: fatal error: cpl_port.h: No such file or directory
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

We search which pakage includes cpl_port.h:

apt-file search cpl_port.h   
libgdal-dev: /usr/include/gdal/cpl_port.h

After install python3-gdal and libgdal-dev you will see that you get the same error.
This occurs because you have an older gdal version (you can see your gdal version with apt-cache show python3-gdal | grep Version)
To upgrade to a newer version, you need to do the following steps:

sudo add-apt-repository ppa:ubuntugis/ppa
sudo apt-get update
sudo apt-get install python-gdal

Enjoy it!

UPDATE:
The python3 example, doesn't provide a full funtional file.
If you want a simple solution, you can use togeojson, just run this command:

npm install -g @mapbox/togeojson
togeojson file.kml > file.geojson

You can test the geojson file in http://geojson.io 

Comments

Popular posts from this blog

from: can't read /var/mail/ in Python scripts

Fix "Set scan parameters failed: Input/output error" on Ubuntu 16.04

How to install a WhatsApp bot based on Python