1

I just discovered JTS through this stack exchange. I'm looking for a Java solution to cut an abitrary polygon into two by a line. I've implemented one that does fine on convex polygons, but it messes up on concave ones.

Can anyone give an example on how to use JTS to cut a convex polygon by a line segment? I know that sometimes you can end up with more than two polygons depending on the shape.

2

I finally found an answer to this hidden away in a tutorial on WPS processes.

There isn't much explanation! But it seems to work.

public class PolygonTools {

  public static Geometry polygonize(Geometry geometry) {
      List lines = LineStringExtracter.getLines(geometry);
      Polygonizer polygonizer = new Polygonizer();
      polygonizer.add(lines);
      Collection polys = polygonizer.getPolygons();
      Polygon[] polyArray = GeometryFactory.toPolygonArray(polys);
      return geometry.getFactory().createGeometryCollection(polyArray);
  }

  public static Geometry splitPolygon(Geometry poly, Geometry line) {
      Geometry nodedLinework = poly.getBoundary().union(line);
      Geometry polys = polygonize(nodedLinework);

      // Only keep polygons which are inside the input
      List output = new ArrayList();
      for (int i = 0; i < polys.getNumGeometries(); i++) {
          Polygon candpoly = (Polygon) polys.getGeometryN(i);
          if (poly.contains(candpoly.getInteriorPoint())) {
              output.add(candpoly);
          }
      }
      return poly.getFactory().createGeometryCollection(GeometryFactory.toGeometryArray(output));
  }
} 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.