Iterate over points in GEOS Polygon using C API
Question
How can I iterate over the points in a GEOS Polygon without turning it into a WKT string? Currently we're doing something like this:
GEOSGeometry *geom = GEOSGeomFromWKT("POLYGON ((1 1, 2 1, 2 2, 1 2, 11))");
char geomAsWKT[900] = GEOSGeomToWKT(geom);
/* Iterate over the geomAsWKT to get the points */
All the functions I've tried (GEOSGeomGetPointN
, GEOSGeom_getCoordSeq
, and some others) only work on a LinearRing
.
Solution
To iterate over the points of a polygon, you have to get the LinearRing
by calling GEOSGetExteriorRing
, as demonstrated below.
This example works for MultiPolygon
s or Polygon
s. This example prints all the x,y coordinates of the points in a the LinearRings that make up a multipolygon. It also works if the inputGeom is a Polygon.
GEOSGeometry *inputGeom = GEOSGeomFromWKT("MULTIPOLYGON (((30 20, 45 40, 10 40, 30 20)), ((15 5, 40 10, 10 20, 5 10, 15 5)))");
const GEOSGeometry *linearRing;
const GEOSCoordSequence *coordSeq;
int numGeom = GEOSGetNumGeometries(inputGeom);
int n;
for (n=0; n < numGeom; n++) {
linearRing = GEOSGetExteriorRing(GEOSGetGeometryN(inputGeom, n));
printf("%s\n", GEOSGeomToWKT(linearRing));
unsigned int numPoints, p;
numPoints = GEOSGeomGetNumPoints(linearRing);
for (p=0; p < numPoints; p++) {
double xCoord, yCoord;
coordSeq = GEOSGeom_getCoordSeq(linearRing);
GEOSCoordSeq_getX(coordSeq, p, &xCoord);
GEOSCoordSeq_getY(coordSeq, p, &yCoord);
printf("%f, %f\n", xCoord, yCoord);
}
}
For my purposes, the Polygons never had holes in them, so this was all I needed.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow