5

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?

3

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

  • Thanks a lot for the follow-up. Nevertheless, I have developed my own KML parser, using JAXB (opencarto.svn.sourceforge.net/viewvc/opencarto/trunk/…) – julien Oct 7 '11 at 7:45
  • Can you tell me which maven dependency contains the org.geotools.kml.KMLConfiguration class? – Zoltán Jun 26 '13 at 8:11
  • The maven artifact is org.geotools.xsd gt-xsd-kml – Tim Aug 9 '13 at 3:22
3

There is a KMLExample at http://svn.osgeo.org/geotools/trunk/demo/example/src/main/java/org/geotools/demo/xml/KMLExample.java which shows the KML bindings in use for writing. From other discussions on the user list it seems that the KML bindings work in a similar way to the GML bindings so look at http://docs.codehaus.org/display/GEOTDOC/GML+XML+Support for more clues.

When you get a solution feel free to post it to the GeoTools wiki.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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