简体   繁体   中英

How can i extract coordinates from a kml file using Java

I have a KML file https://files.fm/u/nbwf3trv and i need to fetch all coordinates and add it to a list.

Example: Required coordinates from KML file. 11.651548147201538,48.249088525772095,0 9.20654296875,50.00086069107056,0 7.010795159396929,51.45182674763414,0".

Please suggest. Thanks.

JAK (Java API for KML) is a simple Java API to parse and/or create KML files from scratch.

https://github.com/micromata/javaapiforkml

Here is a snippet of Java code to extract the coordinates from a KML file. In this case it's a placemark and a polygon geometry. If the KML file had multiple placemarks then you would iterate over all the placemarks.

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());
}

If the first feature in the KML is a Folder then you can cast a Folder to the object then iterate over the features.

Folder doc = (Folder) kml.getFeature();
List<Feature> features = doc.getFeature();
for(Feature f : features) {
  ...
}

You can also use the Java Topology Suite (JTS). An example reading a kml file is posted here . JTS is an active open source project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM