## Trouble finding union of MultiPolygons document.SUBSCRIPTION_OPTIONS = { "thing": "thread", "subscribed": false, "url": "subscribe", "icon": { "css": "fa fa-envelope-o" } };

Help
Ross
2012-02-21
2012-12-12
• Ross - 2012-02-21

Hello,

I'm trying to take the union of two multipolygons, and then store it in a third multipolygon. However, for some reason not specified in the Javadoc, the Polygon2DUtils.union method returns a SimplePolygon2D instead of just a Polygon2D. Obviously I can't caste this to MultiPolygon2D, so the union operation is unable to handle polygons with holes.

Code:
double s1x = {105, 97, 89, 97};
double s1y = {100, 102, 100, 98};

double s2x = {113, 123, 133, 123};
double s2y = {100, 102, 100, 98};

LinearRing2D s1 = new LinearRing2D(s1x, s1y);
LinearRing2D s2 = new LinearRing2D(s2x, s2y);

MultiPolygon2D mp1 = new MultiPolygon2D(s1);
MultiPolygon2D mp2 = new MultiPolygon2D(s2);

double hole1x = {102, 97, 92, 97};
double hole1y = {100, 101, 100, 99};

LinearRing2D holeRing = new LinearRing2D(hole1x, hole1y);

AffineTransform2D sca1 = AffineTransform2D.createScaling(mp1.getCentroid(),10, 10);
AffineTransform2D sca2 = AffineTransform2D.createScaling(mp2.getCentroid(),10, 10);

mp1 = mp1.transform(sca1);
mp2 = mp2.transform(sca2);

MultiPolygon2D intersect = (MultiPolygon2D)Polygon2DUtils.union(mp1, mp2);

Error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: math.geom2d.polygon.SimplePolygon2D cannot be cast to math.geom2d.polygon.MultiPolygon2D

• David - 2012-02-22

Hi,

when computing a boolean operation on polygons, the result is converted to a simple- or multi-polygon, depending if there are holes or multi components.

SimplePolygon2D and MultiPolygon2D are implementation classes, but both are implementation of the Polygon2D interface. I would suggest using the type "Polygon2D" for storing the result, this should work in all cases.

If you really need to use a MultiPolygon as result, you can create a new one, using a syntax similar to:
MultiPolygon mpoly = new MultiPolygon2D(Polygon2DUtils.union(mp1, mp2).getRings());

hope this helps ?

Regards,
David