A slightly cleaner way of doing this with the option of GML 2 or 3 output is:
public class WKTToGML {
public static void main(String[] args) throws IOException, ParseException {
System.out.println(WKTToGML2("POLYGON((1 0,1 1,0 1,0 0,1 0))"));
System.out.println(WKTToGML3("POLYGON((1 0,1 1,0 1,0 0,1 0))"));
}
static public String WKTToGML2(String wkt) throws IOException, ParseException {
WKTReader wktR = new WKTReader();
Geometry geom = wktR.read(wkt);
org.geotools.xml.Configuration configuration = new org.geotools.gml2.GMLConfiguration();
org.geotools.xml.Encoder encoder = new org.geotools.xml.Encoder( configuration );
ByteArrayOutputStream out = new ByteArrayOutputStream();
encoder.encode(geom, GML._Geometry,out);
return out.toString();
}
static public String WKTToGML3(String wkt) throws IOException, ParseException {
WKTReader wktR = new WKTReader();
Geometry geom = wktR.read(wkt);
org.geotools.xml.Configuration configuration = new org.geotools.gml3.GMLConfiguration();
org.geotools.xml.Encoder encoder = new org.geotools.xml.Encoder( configuration );
ByteArrayOutputStream out = new ByteArrayOutputStream();
encoder.encode(geom, org.geotools.gml3.GML.geometryMember,out);
return out.toString();
}
}
gives the following output:
<?xml version="1.0" encoding="UTF-8"?><gml:Polygon xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml" xmlns:xlink="http://www.w3.org/1999/xlink"><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>1.0,0.0 1.0,1.0 0.0,1.0 0.0,0.0 1.0,0.0</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon>
<?xml version="1.0" encoding="UTF-8"?><gml:geometryMember xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gml="http://www.opengis.net/gml" xmlns:sch="http://www.ascc.net/xml/schematron" xmlns:xlink="http://www.w3.org/1999/xlink"><gml:Polygon srsDimension="2"><gml:exterior><gml:LinearRing srsDimension="2"><gml:posList>1.0 0.0 1.0 1.0 0.0 1.0 0.0 0.0 1.0 0.0</gml:posList></gml:LinearRing></gml:exterior></gml:Polygon></gml:geometryMember>
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
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: