/** * Removes collinear vertices from the provided {@link Geometry}. * * <p>For the moment this implementation only accepts, {@link Polygon}, {@link LineString} and * {@link MultiPolygon} It will throw an exception if the geometry is not one of those types * * @param g the instance of a {@link Geometry} to remove collinear vertices from. * @return a new instance of the provided {@link Geometry} without collinear vertices. */ public static Geometry removeCollinearVertices(final Geometry g) { if (g == null) { throw new NullPointerException("The provided Geometry is null"); } if (g instanceof LineString) { return removeCollinearVertices((LineString) g); } else if (g instanceof Polygon) { return removeCollinearVertices((Polygon) g); } else if (g instanceof MultiPolygon) { MultiPolygon mp = (MultiPolygon) g; Polygon[] parts = new Polygon[mp.getNumGeometries()]; for (int i = 0; i < mp.getNumGeometries(); i++) { Polygon part = (Polygon) mp.getGeometryN(i); part = removeCollinearVertices(part); parts[i] = part; } return g.getFactory().createMultiPolygon(parts); } throw new IllegalArgumentException( "This method can work on LineString, Polygon and Multipolygon: " + g.getClass()); }
/** * Removes collinear vertices from the provided {@link Polygon}. * * @param polygon the instance of a {@link Polygon} to remove collinear vertices from. * @return a new instance of the provided {@link Polygon} without collinear vertices. */ static Polygon removeCollinearVertices(final Polygon polygon) { if (polygon == null) { throw new NullPointerException("The provided Polygon is null"); } // reuse existing factory final GeometryFactory gf = polygon.getFactory(); // work on the exterior ring LineString exterior = polygon.getExteriorRing(); LineString shell = removeCollinearVertices(exterior); if ((shell == null) || shell.isEmpty()) { return null; } // work on the holes List<LineString> holes = new ArrayList<LineString>(); final int size = polygon.getNumInteriorRing(); for (int i = 0; i < size; i++) { LineString hole = polygon.getInteriorRingN(i); hole = removeCollinearVertices(hole); if ((hole != null) && !hole.isEmpty()) { holes.add(hole); } } return gf.createPolygon((LinearRing) shell, holes.toArray(new LinearRing[holes.size()])); }
return removeCollinearVertices((LineString) geometry); } else if (geometry instanceof Polygon) { return removeCollinearVertices((Polygon) geometry); } else if (geometry instanceof MultiPolygon) { MultiPolygon mp = (MultiPolygon) geometry; for (int i = 0; i < mp.getNumGeometries(); i++) { Polygon part = (Polygon) mp.getGeometryN(i); part = removeCollinearVertices(part); parts[i] = part;
JTS.removeCollinearVertices( polygon); JTS.removeCollinearVertices( polygon);
final Shape shape = new java.awt.Polygon(xPoints, yPoints, nPoints); final Geometry original = JTS.toGeometry(shape); final Geometry reduced = JTS.removeCollinearVertices(original); assertEquals(10, original.getNumPoints()); assertEquals(5, reduced.getNumPoints());