Wednesday, 13 September 2017

geotools - What is the best way to convert WKT String to GML String


What is the best way to programatically convert WKT String to GML String? Every reasonable library (at best available in some Maven repository) can be used.


Till now I came up with this solution using JTS. Its written in Java:


public String wktToGml(String wktGeometry) {
WKTReader wktR = new WKTReader();
Geometry geom = wktR.read(wktGeometry);

// write JTS to string
GMLWriter gmlW = new GMLWriter(true);

String gml = gmlW.write(geom);
return gml;
}

But I'm not sure if it's correct and most effective way. There are probably some problems with LF (linefeed) symbols. Probably there should be also solution using geotools library.


I'm new to this field, I'm trying to gain some overview.



Answer



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:


1.0,0.0 1.0,1.0 0.0,1.0 0.0,0.0 1.0,0.0
1.0 0.0 1.0 1.0 0.0 1.0 0.0 0.0 1.0 0.0

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...