Skip to contents

g_make_valid() attempts to make an invalid geometry valid without losing vertices. Already-valid geometries are cloned without further intervention. Wrapper of OGR_G_MakeValid()/OGR_G_MakeValidEx() in the GDAL Vector C API.

Usage

g_make_valid(
  geom,
  method = "LINEWORK",
  keep_collapsed = FALSE,
  as_wkb = TRUE,
  as_iso = FALSE,
  byte_order = "LSB",
  quiet = FALSE
)

Arguments

geom

Either a raw vector of WKB or list of raw vectors, or a character vector containing one or more WKT strings.

method

Character string. One of "LINEWORK" (the default) or "STRUCTURE" (requires GEOS >= 3.10 and GDAL >= 3.4). See Details.

keep_collapsed

Logical, applies only to the STRUCTURE method. Defaults to FALSE. See Details.

as_wkb

Logical, TRUE to return the output geometry in WKB format (the default), or FALSE to return as WKT.

as_iso

Logical, TRUE to export as ISO WKB/WKT (ISO 13249 SQL/MM Part 3), or FALSE (the default) to export as "Extended WKB/WKT".

byte_order

Character string specifying the byte order when output is WKB. One of "LSB" (the default) or "MSB" (uncommon).

quiet

Logical, TRUE to suppress warnings. Defaults to FALSE.

Value

A geometry as WKB raw vector or WKT string, or a list/character vector of geometries as WKB/WKT with length equal to length(geom). NA is returned with a warning if an input geometry cannot be converted into an OGR geometry object, or if an error occurs in the call to MakeValid() in the underlying OGR API.

Details

LINEWORK is the default method, which combines all rings into a set of noded lines and then extracts valid polygons from that linework. The STRUCTURE method (requires GEOS >= 3.10 and GDAL >= 3.4) first makes all rings valid, then merges shells and subtracts holes from shells to generate a valid result. Assumes that holes and shells are correctly categorized.

KEEP_COLLAPSED only applies to the STRUCTURE method:

  • FALSE (the default): collapses are converted to empty geometries

  • TRUE: collapses are converted to a valid geometry of lower dimension

Note

This function is built on the GEOS >= 3.8 library, check it for the definition of the geometry operation. If OGR is built without GEOS >= 3.8, this function will return a clone of the input geometry if it is valid, or NA if it is invalid.

Examples

# requires GEOS >= 3.8, otherwise is only a validity test (see Note)
geos_version()
#> $name
#> [1] "3.10.2"
#> 
#> $major
#> [1] 3
#> 
#> $minor
#> [1] 10
#> 
#> $patch
#> [1] 2
#> 

# valid
wkt <- "POINT (0 0)"
g_make_valid(wkt, as_wkb = FALSE)
#> [1] "POINT (0 0)"

# invalid to valid
wkt <- "POLYGON ((0 0,10 10,0 10,10 0,0 0))"
g_make_valid(wkt, as_wkb = FALSE)
#> [1] "MULTIPOLYGON (((10 0,0 0,5 5,10 0)),((10 10,5 5,0 10,10 10)))"

# invalid - error
wkt <- "LINESTRING (0 0)"
g_make_valid(wkt)  # NA
#> Warning: OGR MakeValid() gave NULL geometry, NA returned
#> [1] NA