Geotools 计算所需的两个几何之间的交叉区域

Geotools calculate intersection area between two geometries needed

我是 Geotools 的新手,我创建了两个几何图形(例如两个多边形),我想计算其中一个几何图形的交叉面积百分比。

    //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);

有人知道如何计算 polygon1(或圆)内的 polygon2 的百分比吗?有什么算法可以计算几何图形之间的交集面积吗?

您将需要计算交点,然后计算其面积,最后计算比率

Geometry intersect = polygon1.intersection(polygon2);
double areaRatio = 100.0*intersect.getArea() / polygon2.getArea();

System.out.println("ratio: "+areaRatio + "%");

也就是说,在计算交集之前,您需要使用 polygon1.isValid()polygon2.isValid() 确保几何图形有效。 polygon2 的示例数据是自相交的,因此相交操作失败

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) ]