How can I find the set of polygons created by a set of lines in JTS?

138 views Asked by At

I have a set of line segments and I want to find what polygons are formed by the intersection of those lines. For example, suppose I have the following two line sequences:

(-0.5, 0.5) to (0, -0.5) to (0, 1) to (1, 1) to (1, 0) to (-0.5, 0)

and

(0, 2) to (0.5, 0) to (1, 2)

How can I find the 4 polygon shapes as identified by the red arrows in the following diagram: Diagram showing lines in cartesian plane

1

There are 1 answers

0
Mark On

OK here's the solution I found. It requires using a 'noder' to find all the line intersections.

import org.locationtech.jts.algorithm.RobustLineIntersector;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.noding.*;
import org.locationtech.jts.operation.polygonize.Polygonizer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class TestJts {
    public static void main(String[] args) {
        try {
            List<SegmentString> segmentStrings = new ArrayList<>();
            segmentStrings.add(new NodedSegmentString(
                    new Coordinate[]{
                            new Coordinate(-0.5, 0.5),
                            new Coordinate(0, -0.5),
                            new Coordinate(0, 1),
                            new Coordinate(1, 1),
                            new Coordinate(1, 0),
                            new Coordinate(-0.5, 0)
                    }, null));

            segmentStrings.add(new NodedSegmentString(
                    new Coordinate[]{
                            new Coordinate(0, 2),
                            new Coordinate(0.5, 0),
                            new Coordinate(1, 2)
                    }, null));


            Collection<Polygon> polygons = getPolygons(segmentStrings);
            for (Polygon polygon : polygons) {
                System.out.println(polygon);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Collection<Polygon> getPolygons(List<SegmentString> segmentStrings) {
        GeometryFactory factory = new GeometryFactory();
        MCIndexNoder noder = new MCIndexNoder();
        noder.setSegmentIntersector(new IntersectionAdder(new RobustLineIntersector()));
        noder.computeNodes(segmentStrings);

        Collection<NodedSegmentString> nodedSubstrings = noder.getNodedSubstrings();

        List<LineString> lineStrings = new ArrayList<>();
        for (NodedSegmentString nss : nodedSubstrings) {
            lineStrings.add(factory.createLineString(nss.getCoordinates()));
        }

        Polygonizer polygonizer = new Polygonizer();
        polygonizer.add(lineStrings);

        return polygonizer.getPolygons();
    }
}