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.

1 Answer 1


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

  • Hey iant, thanks for the response. I tried doing UNION in the ways specified in the note and result is the same. And I tried with the multipolygon object and the line is added between the two squares even though the don't overlap (as the image) I'll keep investigating...
    – elguime
    Commented Sep 16, 2013 at 12:50
  • 1
    static Geometry combineIntoOneGeometry( Collection<Geometry> geometryCollection ){ GeometryFactory factory = FactoryFinder.getGeometryFactory( null ); // note the following geometry collection may be invalid (say with overlapping polygons) GeometryCollection geometryCollection = (GeometryCollection) factory.buildGeometry( geometryCollection ); return geometryCollection.union(); }
    – Ian Turton
    Commented Sep 16, 2013 at 12:52
  • Okay! I forgot changing datatype to "MultiPolygon" in SimpleFeatureType createType. Thankx a lot!
    – elguime
    Commented Sep 16, 2013 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.