Last active
February 22, 2024 17:01
-
-
Save mazzma12/0a32ce693bb42b742252caabb98519db to your computer and use it in GitHub Desktop.
IO / Read and write KML file with geopandas and fiona driver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
) | |
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
Hi @mazzma12 - this is helpful and really demonstrates how Fiona does all of the heavy lifting for ogr. However I created a KML file from a GPKG using this method and ran into an issue - it seems somewhere along the line the field names get screwed up (the KML
<name>
was taken from the feature 'date' field for example). If I do it the hard way using ogr the naming is correct. Have you seen this and do you know a way around it? Or is this a question for the Fiona team?