Skip to content

Instantly share code, notes, and snippets.

@phargogh
Created February 5, 2020 03:10
Show Gist options
  • Select an option

  • Save phargogh/b7670ad37266221eefc53124d8fb0906 to your computer and use it in GitHub Desktop.

Select an option

Save phargogh/b7670ad37266221eefc53124d8fb0906 to your computer and use it in GitHub Desktop.
Demo: Fixing invalid geometries
# encoding=UTF-8
"""fix_geometry.py"""
def doit(original_geometry):
if not original_geometry.IsValid():
if 'POLYGON' in original_geometry.GetGeometryName():
# Geometries that are only self-intersecting can be fixed by
# Buffering by 0.
buffered_geom = original_geometry.Buffer(0)
if buffered_geom is None:
# If a geometry does not form a closed linear ring,
# buffering by 0 will return ``None``. If this happens,
# we can close the ring and then buffer by 0 again.
closed_ring_geom = original_geometry.Clone()
closed_ring_geom.CloseRings()
if not closed_ring_geom.IsValid():
buffered_geom = closed_ring_geom.Buffer(0)
else:
buffered_geom = closed_ring_geom
fixed_geometry = buffered_geom
if not fixed_geometry.IsValid():
LOGGER.warn(
'Attempted repair of invalid geometry of feature '
'%s failed. Using as-is.', feature.GetFID())
else:
LOGGER.warn(
'Geometry of feature %s is invalid but no repair method '
'implemented. Using as-is.', feature.GetFID())
fixed_geometry = original_geometry
else:
fixed_geometry = original_geometry
return fixed_geometry
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment