/** * If validation is requested, scan the geometries and build valid polygons (in case they * aren't) by also removing holes. * * @param geometriesList * @return */ private List<Polygon> validateGeometries(List<Polygon> geometriesList) { if (forceValid && (geometriesList.size() > 0)) { List<Polygon> validated = new ArrayList<Polygon>(geometriesList.size()); for (int i = 0; i < geometriesList.size(); i++) { Polygon polygon = geometriesList.get(i); if (!polygon.isValid()) { List<Polygon> validPolygons = JTS.makeValid(polygon, true); validated.addAll(validPolygons); } else { validated.add(polygon); } } geometriesList = validated; } return geometriesList; }
@Test public void testMakeValid() throws Exception { // An invalid polygon similar to this one // // *----* // | | // *----*----* // | | // *----* // // Will be split into 2 separate polygons through the makeValid method final int[] xPoints = {0, 5, 5, 5, 10, 10, 5, 0}; final int[] yPoints = {0, 0, 5, 10, 10, 5, 5, 5}; final int nPoints = xPoints.length; final Shape shape = new java.awt.Polygon(xPoints, yPoints, nPoints); final LinearRing geom = (LinearRing) JTS.toGeometry(shape); final GeometryFactory factory = new GeometryFactory(); final org.locationtech.jts.geom.Polygon polygon = factory.createPolygon(geom); assertFalse(polygon.isValid()); final List<org.locationtech.jts.geom.Polygon> validPols = JTS.makeValid(polygon, false); assertEquals(2, validPols.size()); org.locationtech.jts.geom.Polygon polygon1 = validPols.get(0); org.locationtech.jts.geom.Polygon polygon2 = validPols.get(1); assertEquals(5, polygon1.getNumPoints()); assertEquals(5, polygon2.getNumPoints()); } }