Skip to content

Instantly share code, notes, and snippets.

@nishadhka
Forked from mazzma12/kml_io.py
Created January 30, 2021 06:18
Show Gist options
  • Save nishadhka/be38f1b925fa80aaa46eea4179b77276 to your computer and use it in GitHub Desktop.
Save nishadhka/be38f1b925fa80aaa46eea4179b77276 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))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment