javajtsjava-15

Java JTS Polygon contains Another Polgyon


I am trying to use JTS to tell if one Polygon contains another Polygon.

I have resources here. How do I utilize the syntax? this is giving me errors. The next step is to apply contains. If anyone has experience with JTS, it would be helpful.

https://gis.stackexchange.com/questions/368520/jts-geometry-contains-not-detecting-point-of-an-inner-polygon-on-edge-of-outer

https://gis.stackexchange.com/questions/262751/how-to-determine-if-one-polygon-is-contained-in-another

https://locationtech.github.io/jts/javadoc/org/locationtech/jts/geom/Polygon.html

Polygon item1 = ((0 0, 1000 0, 1000 1000, 0 1000, 0 0))
Polygon item2 = ((500 500, 1000 500, 600 600, 500 600, 500 500))

enter image description here

enter image description here


Solution

  • You cannot create a polygon just like that. JTS is a rather heavy framework, so you need to go the full route.

    1. Everything starts with GeometryFactorydocs. It is responsible for creating all geometries, it is necessary because it takes into account a few things like PrecisionModel for example.
    2. You need to understand the hierarchy of geometries, Polygon is described by a line - LineRig or LineString (the difference is out of the scope for this question).
    3. You need to realize that every line consists of points, which can be described either by Point or Coordinate. So if you want to create a Polygon

    The code would look like this:

     GeometryFactory factory = new GeometryFactory(); //default
     Coordinate[] coordinates1 = {
            new CoordinateXY(0,0),
            new CoordinateXY(1000,0),
            new CoordinateXY(1000, 1000),
            new CoordinateXY(0, 1000),
            new CoordinateXY(0, 0)
     };
     Coordinate[] coordinates2 = {
            new CoordinateXY(500,500),
            new CoordinateXY(1000,500),
            new CoordinateXY(600, 600),
            new CoordinateXY(500, 600),
            new CoordinateXY(500, 500)
     };
     LinearRing linearRing1 = factory.createLinearRing(coordinates1);
     LinearRing linearRing2 = factory.createLinearRing(coordinates2);
     Polygon polygon1 = factory.createPolygon(linearRing1);
     Polygon polygon2 = factory.createPolygon(linearRing2);
     assertTrue(polygon1.contains(polygon2));