Python – Convert KML to GPX Programmatically or with Command

gdalgpxkmlogr2ogrpython

I have a KML file I downloaded from Google Maps "My Maps". This KML has many layers, each layer with many POIs.
I would like to convert the KML with tools like ogr2ogr from the GDAL library or some python scripts, but I find it very hard.

So far:

  • ogr2ogr -f GPX my_file.gpx my_file.kml
    • gives ERROR 6: Cannot create GPX layer MY_LAYER_XYZ with unknown geometry type
  • ogr2ogr -nlt POINT -f GPX my_file.gpx my_file.kml
    • gives many errors on various fields (which I guess come from how Google builds the KML) similar to ERROR 6: Field of name 'description' is not supported in GPX schema. Use GPX_USE_EXTENSIONS creation option to allow use of the <extensions> element.
    • then it also gives ERROR 1: Features without geometry or with non-ponctual geometries not supported by GPX writer in waypoints layer.
      ERROR 1: Unable to write feature 2 from layer MY_LAYER_XYZ.
  • ogr2ogr -nlt POINT -f GPX -dsco GPX_USE_EXTENSIONS=YES my_file.gpx my_file.kml
    • gives ERROR 1: Features without geometry or with non-ponctual geometries not supported by GPX writer in waypoints layer.
      ERROR 1: Unable to write feature 2 from layer MY_LAYER_XYZ.
  • ogr2ogr -nlt POINT -f GPX -dsco GPX_USE_EXTENSIONS=YES -lco FORCE_GPX_TRACK=YES my_file.gpx my_file.kml
    • gives ERROR 1: Features without geometry or with non-ponctual geometries not supported by GPX writer in waypoints layer.
      ERROR 1: Unable to write feature 2 from layer MY_LAYER_XYZ.

I've tried this python script kml2gpx.py at https://gist.github.com/timabell/8791116 which looking at the code should iterate through the KML processing it as "normal XML" content (using stuff like import xml.sax), but the output does not contain any of the POIs in the orginal KML.

I am not familiar with the KML and the GPX standard, I just wished there was a handy script to convert one to the other. Is it possible at all?

Best Answer

I've ended up using gpsbabel which provides a GUI along with the command.

On ubuntu/debian:

sudo apt-get install gpsbabel-gui

This will install the command gpsbabel as well.

You can follow the GUI settings, it's easy, in my case I removed all the extra options to convert tracks and routes (I was interested only in waypoints). Otherwise the command is the following one:

gpsbabel -w -i kml -f <INPUT_FILE_NAME.kml> -o gpx -F <OUTPUT_FILE_NAME.gpx>