user1298426
user1298426

Reputation: 3717

How to split a JTS polygon

I have a big polygon and I want to find intersecting features with the polygon but since polygon is too big, I am getting timeout exception.

I was trying to look into JTS methods but couldn't get how to use it.

final List<Coordinate> coordinates = List.of(new Coordinate(0, 0), new Coordinate(-1, 1),
        new Coordinate(1, 3), new Coordinate(2, 3), new Coordinate(3, 1), new Coordinate(0, 0));
final GeometryFactory factory = new GeometryFactory();
final Polygon polygon = factory.createPolygon(coordinates.toArray(new Coordinate[0]));
final Geometry envelope = polygon.getEnvelope();

Can someone give me pointers on how to split the polygon object?

Upvotes: 3

Views: 2078

Answers (1)

Ian Turton
Ian Turton

Reputation: 10976

There are many (an infinite number) ways to split a polygon, but this is how I would do it, by calculating the mid lines of the envelope and intersecting the new envelopes against the polygon.

public List<Geometry> split(Polygon p) {
    List<Geometry> ret = new ArrayList<>();
    final Envelope envelope = p.getEnvelopeInternal();
    double minX = envelope.getMinX();
    double maxX = envelope.getMaxX();
    double midX = minX + (maxX - minX) / 2.0;
    double minY = envelope.getMinY();
    double maxY = envelope.getMaxY();
    double midY = minY + (maxY - minY) / 2.0;

    Envelope llEnv = new Envelope(minX, midX, minY, midY);
    Envelope lrEnv = new Envelope(midX, maxX, minY, midY);
    Envelope ulEnv = new Envelope(minX, midX, midY, maxY);
    Envelope urEnv = new Envelope(midX, maxX, midY, maxY);
    Geometry ll = JTS.toGeometry(llEnv).intersection(p);
    Geometry lr = JTS.toGeometry(lrEnv).intersection(p);
    Geometry ul = JTS.toGeometry(ulEnv).intersection(p);
    Geometry ur = JTS.toGeometry(urEnv).intersection(p);
    ret.add(ll);
    ret.add(lr);
    ret.add(ul);
    ret.add(ur);

    return ret;
  }

This gives this for your polygon:

enter image description here

And if you call it again on that output:

enter image description here

In a production setting you'd want some error checking to make sure you can handle the point that's generated.

Upvotes: 7

Related Questions