Skip to content

Instantly share code, notes, and snippets.

@afabri
Created October 7, 2024 08:54
Show Gist options
  • Save afabri/edc9e3a0906ddfc9165b6ffe76d31604 to your computer and use it in GitHub Desktop.
Save afabri/edc9e3a0906ddfc9165b6ffe76d31604 to your computer and use it in GitHub Desktop.
Structural Repair with GEOS
#include <stdio.h>
#include <stdarg.h>
#include <geos_c.h>
/*
* GEOS requires two message handlers to return
* error and notice message to the calling program.
*
* typedef void(* GEOSMessageHandler) (const char *fmt,...)
*
* Here we stub out an example that just prints the
* messages to stdout.
*/
static void
geos_message_handler(const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vprintf (fmt, ap);
va_end(ap);
}
int main()
{
/* Send notice and error messages to our stdout handler */
initGEOS(geos_message_handler, geos_message_handler);
GEOSMakeValidParams* params = GEOSMakeValidParams_create();
GEOSMakeValidParams_setKeepCollapsed(params, 0);
GEOSMakeValidParams_setMethod(params, GEOS_MAKE_VALID_STRUCTURE);
const char* wkt = "MULTIPOLYGON( ((0 0 , 10 0, 10 10, 0 10, 0 0), ( 8 6, 8 8, 12 8, 12 6, 8 6) ), (( 11 0, 15 0, 15 10, 11 10, 11 0))) "; // hole sticks out over other polygon
/* Read the WKT into geometry objects */
GEOSWKTReader* reader = GEOSWKTReader_create();
GEOSGeometry* geom = GEOSWKTReader_read(reader, wkt);
GEOSGeometry* geom_repaired = GEOSMakeValidWithParams(geom, params);
/* Convert result to WKT */
GEOSWKTWriter* writer = GEOSWKTWriter_create();
/* Trim trailing zeros off output */
GEOSWKTWriter_setTrim(writer, 1);
/* Print answer */
char* wkt_repaired = GEOSWKTWriter_write(writer, geom_repaired);
printf("Repaired: %s\n", wkt_repaired);
/* Clean up everything we allocated */
GEOSWKTReader_destroy(reader);
GEOSWKTWriter_destroy(writer);
GEOSGeom_destroy(geom);
GEOSGeom_destroy(geom_repaired);
GEOSFree(wkt_repaired);
/* Clean up the global context */
finishGEOS();
/* Done */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment