Search code examples
javageometryjts

Combining WKT geometries via union in JTS


I am trying to read WKT polygons (hundreds of thousands of them) and combine them to larger, "containing" polygons to reduce data size. I've left out the loop I would use, for brevity, so the two polygons should serve as an example.

I have never worked with JTS, so my naive approach is this:

static Geometry combineIntoOneGeometry()
{
       WKTReader wkt = new WKTReader();
       Geometry[] geometries;
       try
       {
              Geometry polygon1 = (Geometry) wkt.read("...");
              Geometry polygon2 = (Geometry) wkt.read("...");
              geometries = new Geometry[] {  }; //add them here ?
              geometries.add(polygon1, polygon2); //add doesn't exist, of course...
       }
       catch (ParseException e)
       {
              e.printStackTrace();
       }

       GeometryCollection gc = new GeometryFactory().createGeometryCollection(geometries); //can't instantiate GeometryFactory
       return gc.union();
}

There are several problems:

  1. I can't instantiate a GeometryCollection
  2. GeometryCollection doesn't seem to have a method for accepting/adding Geometries - how can I "populate" the GeometryCollection with Geometries ?
  3. An array of Geometries can't be added to, and I haven't found a way to do it via the constructor
  4. I can't call union on a Geometry

Aside question: if some of the polygons I am looking to union are disjunct, would that result in a multipolygon ? That would be fine, just curious.

Thanks !


Solution

  • This works for me:

    static Geometry combineIntoOneGeometry()
    {
        WKTReader wkt = new WKTReader();
        GeometryFactory geoFac = new GeometryFactory();
        ArrayList<Geometry> geometries = new ArrayList<>();
    
        try
        {
            Geometry polygon1 = wkt.read("POLYGON ((...))");
            Geometry polygon2 = wkt.read("POLYGON ((...))");
            Geometry polygon3 = wkt.read("POLYGON ((...))");
            Geometry polygon4 = wkt.read("POLYGON ((...))");
            geometries.add(polygon1);
            geometries.add(polygon2);
            geometries.add(polygon3);
            geometries.add(polygon4);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        GeometryCollection geometryCollection = (GeometryCollection) geoFac.buildGeometry(geometries);
    
        return geometryCollection.union();
    }