Hello KML - Quickstart

A short tutorial

Download the Java API for KML JAR at GitHub and add the JAR to your classpath. If there are any dependencies, resolve them and add JAXB to your classpath, too. Version 2.1.xx should be fine.

Important (or NoClassDefFoundError?)

JAK only works if all dependencies are resolved! That is mainly JAXB
JAXB needed to be downloaded and the containing JARs put into the classpath. For further instructions Check out the FAQ.

Alternatively JAK can be found in the official dev.java.net Maven 2 repository: 

   <!-- The Java API for KML -->
      <name>Java.net Maven 2 Repository</name>

This tutorial shows how to create a KML file that displays a placemark in Google Earth as seen in this Figure:

An example of a placemark element.

The next listing shows the usage of JAK:

final Kml kml = new Kml();
   .withName("London, UK").withOpen(Boolean.TRUE)
   .createAndSetPoint().addToCoordinates(-0.126236, 51.500152);
kml.marshal(new File("HelloKml.kml"));

Listing 1 outputs this KML document:

A KML document that shows the usage of the Placemark element with a point.

Result is shown in Figure 1.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" xmlns:gx="http://www.google.com/kml/ext/2.2">
        <name>London, UK</name>

The unmarshal methods transform a given KML as a file object or string into a graph of Java objects. Since each unmarshal method returns a new Kml object, they are all static.

Unmarshal the previous saved HelloKml.kml and print its coordinates to the console:

final Kml kml = Kml.unmarshal(new File("HelloKml.kml"));
final Placemark placemark = (Placemark) kml.getFeature();
Point point = (Point) placemark.getGeometry();
List<Coordinate> coordinates = point.getCoordinates();
for (Coordinate coordinate : coordinates) {

A more detailed introduction is given in KML in the Java world and Usage.
Implementation explains what it takes to create the Java API for KML.

Direct Example Download

  • HelloKML.zip - HelloKML as Eclipse project.
    (Important: The HelloKML Eclipse project doesn't contain JAK's JAR file. JAK's JAR file needed to be downloaded separately (as well as JAKs dependencies)
  • Download JAK from GitHub