Java – Remove/Fill Holes in Polygons from a MultiPolygon Using JTS Topology Suite

javajts-topology-suite

There are several questions/answers using ERIS,etc.
like:
Remove holes from polygon

But I am having a challenge applying the solution programmatically using the JTS Topology suite only.

Below is an example of MultiPolygon.. I want to remove/fill the holes.

enter image description here

Best Answer

OpenJUMP has a "remove holes" tool (and an advanced "remove small holes" tool as well). OpenJUMP often uses JTS rather directly but I am not sure about this case. The source code of the function is at https://sourceforge.net/p/jump-pilot/code/HEAD/tree/core/trunk/src/com/vividsolutions/jump/workbench/ui/plugin/analysis/GeometryFunction.java

The idea seems to be simple: Get the list of polygons, get the exterior rings and create new polygons from those. Inner rings disappear and job is done.

  // added on 2016-11-11 by mmichaud
  private static class RemoveHolesFunction extends GeometryFunction {
    public RemoveHolesFunction() {
      super(I18N.get("ui.plugin.analysis.GeometryFunction.Remove-Holes"), 1, 0);
    }

    public Geometry execute(Geometry[] geom, double[] param)
    {
      AbstractGeometryProcessor removeHoleProcessor = new AbstractGeometryProcessor() {
        public void process(Polygon polygon, List<Geometry> list) {
          list.add(polygon.getFactory().createPolygon((LinearRing)polygon.getExteriorRing()));
        }
      };
      return removeHoleProcessor.process(geom[0]);
    }
  }