Search code examples
javakmljak

Parsing kml in java


How to determine the latitude and longitude of a point in a polygon?

<Polygon>
<extrude>0</extrude>
<tessellate>1</tessellate>
<altitudeMode>clampToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>-88.346745,30.390702,0.0 -88.346823,30.389936,0.0 -88.345543,30.389914,0.0 -88.344316,30.389981,0.0 -88.342645,30.390004,0.0 -88.340765,30.390161,0.0 -88.335731,30.388969,0.0 -88.33412,30.388741,0.0 -88.33289,30.389146,0.0 -88.333095,30.389878,0.0 -88.335702,30.389727,0.0 -88.340504,30.391513,0.0 -88.341235,30.391738,0.0 -88.342384,30.391468,0.0 -88.343507,30.391445,0.0 -88.345047,30.3914,0.0 -88.346745,30.390702,0.0</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>`

Solution

  • Using Java API for KML (JAK), you can parse a KML file then extract its coordinates.

    Here is a snippet of Java code to extract the coordinates from a KML file.

    JAXBContext jc = JAXBContext.newInstance(Kml.class);
    
    // create KML reader to parse arbitrary KML into Java Object structure
    Unmarshaller u = jc.createUnmarshaller();
    Kml kml = (Kml) u.unmarshal(new File("test.kml"));
    
    Placemark placemark = (Placemark) kml.getFeature();
    Polygon geom = (Polygon) placemark.getGeometry();
    LinearRing linearRing = geom.getOuterBoundaryIs().getLinearRing();
    List<Coordinate> coordinates = linearRing.getCoordinates();
    for (Coordinate coordinate : coordinates) {
        System.out.println(coordinate.getLongitude());
        System.out.println(coordinate.getLatitude());
        System.out.println(coordinate.getAltitude());
    }