[GIS] geotools parsing kml with multigeometry only gives me first geometry

geotoolsjavakml

I'm trying to parse the states.kml file (http://docs.geotools.org/latest/userguide/_downloads/states.kml) on the geotools website using the following code:

Parser parser = new Parser(new KMLConfiguration());
SimpleFeature f = (SimpleFeature) parser.parse( is );
@SuppressWarnings("unchecked")
Collection<SimpleFeature> placemarks = (Collection<SimpleFeature>) f.getAttribute("Feature");

for (SimpleFeature fe : placemarks) {
    Geometry g = (Geometry) fe.getAttribute("Geometry");
    for (int i = 0; i < g.getNumGeometries(); i++) {
        System.out.println(g.getGeometryN(i));
    }
}

Each of the geometry fields for each placemark in that file is a MultiGeometry made up of a Point and a Polygon. When I run through my for loop and print out though, only the points are printed. Does anyone know how I can access the Polygon also? Is it accessible, or did it get dropped in parsing?

Thanks

Best Answer

Is it accessible, or did it get dropped in parsing?

No, it is very much possible to access any node in a KML file provided you don't miss out on the JAXB hierarchy: You may try something like below:

final Kml kml = Kml.unmarshal(new File("C:\\"YOUR DIRECTORY"\\Sample_2013_q3.kml"));
    final Document document = (Document)kml.getFeature();
    System.out.println(document.getName());
    List<Feature> t = document.getFeature();
    System.out.println(t.size());

 //for each loop for iterating through the folders
    for(Object o : t){
        Folder f = (Folder)t;

        System.out.println(f.getName());

        List<Feature> tg = f.getFeature();

        String folderName=f.getName();
        System.out.println(folderName);

 //Iterating through placemarks inside all folders
        for(Object ftg : tg){
            Placemark g = (Placemark)ftg;

 //check if the node under placemark is MultiGeometry
            if ((g.getGeometry() instanceof MultiGeometry))
            {

                 MultiGeometry mpg=(MultiGeometry)g.getGeometry();
                List<Geometry> gmList= mpg.getGeometry();
 //Get all the geometries and traverse them one by one
                for(Geometry geoItr: gmList)
                {
                     Polygon multiGeoPoly=(Polygon)geoItr;
                     List coordList = multiGeoPoly.getOuterBoundaryIs().getLinearRing().getCoordinates();

                      for(Object point: coordList)
                      {
                          System.out.println(point);
                      }
                   }

                }
Related Question