4

I am writing a Python script to reproject a KML file to WGS 84 and then to convert it to a GeoJSON. I am aware of and use the GDAL command line tool ogr2ogr (which was the answer to this question in this post from 2012).

I can use subprocess to use the ogr2ogr from my script, but I was wondering if there are any libraries out there that might handle this better/make it easier for me. Is there anything else out there? Or is ogr2ogr my best option?

1
  • 2
    There is no need to reproject KML into WGS84 because it is the only coordinate system that KML standard supports.
    – user30184
    Aug 9, 2018 at 9:38

2 Answers 2

5

Many GDAL utilities are nowadays librarified and there is no need to call the executables as subprocess. The librarified version of ogr2ogr is "Vector.Translate" and minimal Python code to convert data from KML into GeoJSON is like

from osgeo import gdal, ogr

 srcDS = gdal.OpenEx('input.kml')
 ds = gdal.VectorTranslate('output.json', srcDS, format='GeoJSON')
3
  • I am aware of gdal.org/python, is there any other resource I can use to learn the 'librarified' versions? thanks
    – dave
    Aug 9, 2018 at 11:07
  • 2
    I tend to use the GDAL autotest suite for finding examples with correct syntax. Tests for librarified utilities are in github.com/OSGeo/gdal/tree/master/autotest/utilities, named as *_lib.py
    – user30184
    Aug 9, 2018 at 11:23
  • Its worth noting that you need to close the file by adding del ds, which will remove the python reference to the object and let the underlying C library clean up the open file. See gis.stackexchange.com/a/255168 .
    – DaveA
    Sep 13, 2020 at 4:08
0

I believe you can use this library, but you need python 3.4+:

https://pypi.org/project/kml2geojson/

Also you might be able to convert KMl to WKT/WKB and then convert it to GeoJSONthat could be done with shapely, but I believe you would loose all the attributes and keep only geometry:

Converting KML files for use with Python library Shapely

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.