Skip to content

Instantly share code, notes, and snippets.

@mazzma12
Last active February 22, 2024 17:01
Show Gist options
  • Save mazzma12/0a32ce693bb42b742252caabb98519db to your computer and use it in GitHub Desktop.
Save mazzma12/0a32ce693bb42b742252caabb98519db to your computer and use it in GitHub Desktop.
IO / Read and write KML file with geopandas and fiona driver
import fiona
import geopandas as gpd
# Enable fiona driver
gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = 'rw'
# Read file
df = gpd.read_file(path, driver='KML')
# Write file
with fiona.drivers():
# Might throw a WARNING - CPLE_NotSupported in b'dataset sample_out.kml does not support layer creation option ENCODING'
df.to_file('sample_out.kml', driver='KML')
# Drop Z dimension of polygons that occurs often in kml
import shapely
import fiona
import geopandas as gpd
# Enable fiona driver
fiona.supported_drivers['KML'] = 'rw'
# Read file
df = gpd.read_file(path, driver='KML')
# Write file
with fiona.drivers():
# Might throw a WARNING - CPLE_NotSupported in b'dataset sample_out.kml does not support layer creation option ENCODING'
df.to_file('sample_out.kml', driver='KML') # You may change driver to GeoJSON
# Drop Z dimension of polygons that occurs often in kml - * expansion handles xy anx xyz cases
import shapely
df = df.set_geometry(
df.geometry.map(
lambda polygon: shapely.ops.transform(lambda x, y, *_: (x, y), polygon)
)
)
# Orient the shape counter clockwise to be Vega conform
df = df.set_geometry(
df.geometry.map(lambda geom: shapely.geometry.polygon.orient(geom))
)
@mazzma12
Copy link
Author

I have really a few experiences with Linestring, sorry... It works fine on Polygon and Point type for me. The only constraint is that it does not work with nested KML as you could have in Google Earth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment