[GIS] Combining several polygon objects in one polygon object with GeoTools

geotoolsjts-topology-suitepolygon-creation

I have several polygon objects and I need to "merge (or combine or dissolve)" them toghether into one polygon object. With a GIS tool like QGIS, I do this with processing option "Combine selected spatial objects" and the result is what I expect but doing programmatically with Java and GeoTools library, I'm not able to get this behaviour.

To give you an idea, I have two polygons in one layer like this:

enter image description here

Each square is an independent polygon in my shapefile (an independent object with its attributes).

Now I want to transform them into one object. I tried with "union" method of Geometry class in this way:

    //polygon1 and polygon2 are Polygon objects (the squares in the above image)
    Geometry combine = polygon1.union(polygon2);

And this is the result when I visualize the union in the GIS:

enter image description here

As you can see, a line is added between the two figures (although the union is made succesfully and I have only one entity as I wish) but I want this without the line connecting them. The polygons are well formed because by doing with QGIS the operation is made right.

Anyone know if is it possible?

I'm looking for some time and I'm concluding that maybe my approach to achieve this is bad.

Best Answer

Assuming that your polygons never overlap then you can generate a multipolygon from them using something like:

    Polygon[] polygons = new Polygon[]{poly1,poly2};
    GeometryFactory factory = new GeometryFactory(....);
    MultiPolygon combined = new MultiPolygon(polygons, factory);

If they might overlap then you will need to test them for intersects and then union the ones that do overlap and replace the two polygons with the new result before you build the multipolygon. This is left as an exercise!

You might also want to read this note

Related Question