Search code examples
javageometrypolygongeotools

Geotools calculate intersection area between two geometries needed


I'm new to Geotools and I created two geometries (two polygons for example) and I want to compute the percentage of the intersection area over one of the geometries.

    //First polygon
        GeometryFactory geometryFactory1 = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] coords1  =
           new Coordinate[] {new Coordinate(4, 0), new Coordinate(2, 2),
                             new Coordinate(4, 4), new Coordinate(6, 2), new Coordinate(4, 0) };

        LinearRing ring1 = geometryFactory.createLinearRing( coords );
        LinearRing holes[] = null; 
        Polygon polygon1 = geometryFactory.createPolygon(ring1, holes );
    // Second polygon
        GeometryFactory geometryFactory2 = JTSFactoryFinder.getGeometryFactory();

        Coordinate[] coords2  =
           new Coordinate[] {new Coordinate(2, 0), new Coordinate(2, 2),
                             new Coordinate(1, 1), new Coordinate(4, 2), new Coordinate(2, 0) };

        LinearRing ring2 = geometryFactory.createLinearRing( coords );
        LinearRing holes[] = null; 
        Polygon polygon2 = geometryFactory.createPolygon(ring2, holes );
    // test if polygon2 is inside polygon1
        boolean test = polygon1.contains(polygon2);

Does someone know how to calculate the percentage of polygon2 inside polygon1 (or a circle)? there is any algorithm to calculate the area of intersection between geometries?


Solution

  • You will need to compute the intersection, then its area, and a last compute the ratio

    Geometry intersect = polygon1.intersection(polygon2);
    double areaRatio = 100.0*intersect.getArea() / polygon2.getArea();
    
    System.out.println("ratio: "+areaRatio + "%");
    

    That being said, you will want to ensure the geometries are valid before computing the intersection, using polygon1.isValid() and polygon2.isValid(). The sample data for polygon2 is self-intersecting, so the intersection operation fails with

    com.vividsolutions.jts.geom.TopologyException: found non-noded intersection between LINESTRING ( 2.0 0.0, 2.0 2.0 ) and LINESTRING ( 1.0 1.0, 2.5 1.5 ) [ (2.0, 1.3333333333333333, NaN) ]