Saturday, 13 June 2015

java - How to parse KML data using geotools?


Geotools contains some packages dealing with KML: org.geotools.kml and org.geotools.kml.bindings. I assume it was designed to parse KML data.


Do you know how to use it?



Answer




The KML support is tied into the XML facilities for encoding and parsing geometry.


The GeoTools user guide has replaced the wiki links provided by Ian above - with a nice clear page devoted to wrangling geometry and XML:


http://docs.geotools.org/latest/userguide/library/xml/geometry.html


One of the headings on that page is devoted to KML.


Site policy here asks that we include the answer rather than just provide links. With that in mind:


Encoder encoder = new Encoder(new KMLConfiguration());
encoder.setIndenting(true);

encoder.encode(featureCollection, KML.kml, outputstream );


Or to parse KML you need to consider geometry and style as KML includes both. Here is an example that fetches a collection of features back.


Parser parser = new Parser(new KMLConfiguration());
SimpleFeature f = (SimpleFeature) parser.parse( inputStream );
Collection placemarks = (Collection) f.getAttribute("Feature");

You can also ask it for a stream of results (incase the file is bigger than memory):


StreamingParser parser = new StreamingParser( inputStream, KML.Placemark);
SimpleFeature f = null;

while ((f = (SimpleFeature) parser.parse()) != null) {

FeatureTypeStyle style = (FeatureTypeStyle) f.getAttribute("Style");

Symbolizer[] syms = style.getRules()[0].getSymbolizers();
assertEquals(3, syms.length);

count++;
}

Best of luck (and if in doubt review the test cases).


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...