[GIS] Remove intersect/touch from polygons, to making one with JTS/GeoTools

geotoolsjts-topology-suite

Is there a way to remove an overlap from multiple polygons to make one final polygon?..programmatically, I am using the GeoTools or/and OpenGIS/JTS.. any ideas to put me on the right path…

example initialenter image description here:

final:
enter image description here

Best Answer

You need to create a GeometryCollection of the polygons that you wish to join and then call .union() on it.

So you'll need some code like:

String lines = "/tmp/ian.shp";
GeometryFactory factory = new GeometryFactory();
Map<String, Object> params = new HashMap<>();
params.put("url", URLs.fileToUrl(new File(lines)));
DataStore ds = DataStoreFinder.getDataStore(params);
String name = ds.getTypeNames()[0];
SimpleFeatureSource source = ds.getFeatureSource(name);
SimpleFeatureCollection features = source.getFeatures();
try (SimpleFeatureIterator itr = features.features()) {
  ArrayList<Geometry> geometries = new ArrayList<>();

  while (itr.hasNext()) {
    SimpleFeature f = itr.next();
    Geometry geom = (Geometry) f.getDefaultGeometry();
    geometries.add(geom);
    SimpleFeatureCollection others = source
        .getFeatures(ECQL.toFilter("intersects(the_geom," + geom.toText() + ")"));

    try (SimpleFeatureIterator oiter = others.features()) {
      while (oiter.hasNext()) {
        geometries.add((Geometry) oiter.next().getDefaultGeometry());
      }
    }

    GeometryCollection geometryCollection = (GeometryCollection) factory.buildGeometry(geometries);

    Geometry union = geometryCollection.union();
    System.out.println(union);

  }
}