Getting coordinates out of KML files

I am going to explain (a) how to retrieve (and print) coordinates of all spatial features in a feature collection, and (b) how to find the nearest point out of a list of features compared to a given point. This tutorial presumes understanding of the Tutorial Parsing KML into the Feature Model. It also helps to have some basic knowledge about the  Java Topology Suite (JTS) and the concept of  Geodetic (Great Circle) Distances.

Getting the coordinates

The following sample code expects a FeatureCollection (e.g. see Tutorial parsing KML Streams), prints all Points as a pair of x and y coordinates and searches for the nearest coordinate of the given Point.

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.PrecisionModel;

import sapience.features.Feature;
import sapience.features.FeatureCollection;
import sapience.features.factories.GeometryFactory;
import sapience.features.operations.GeodeticDistance;

At first there are some imports. The classes which cannot be resolved are left to yourself.

GeometryFactory geomFactory = new GeometryFactory(new PrecisionModel(PrecisionModel.FLOATING), 4326);

//com.vividsolutions.jts.geom.Point givenPoint = geomFactory.createPoint(...)

double shortestDistance = Double.MAX_VALUE;
Point nearestPoint = null;
Point actualPoint = null;
                
for(Feature f : features.listFeaturesRecursively()){
        Geometry geom = f.getGeometry();
        Coordinate[] coordinates = geom.getCoordinates();
        for (int i = 0; i < coordinates.length; i++) {
        System.out.println("x = "+coordinates[i].x+" - y = "+coordinates[i].y);
                actualPoint = geomFactory.createPoint(coordinates[i]);
                if (new GeodeticDistance().betweenGeometries(givenPoint, actualPoint)<shortestDistance) {
                        shortestDistance = new GeodeticDistance().betweenGeometries(givenPoint, actualPoint);
                        nearestPoint = actualPoint;
                }
        }
}

After creating a GeometryFactory, we iterate over all Features given by the FeatureCollection. To get every coordinate, you have to iterate over the array of the coordinates. In this case, it doesn't necessarily matter what type of Geometry we have. If it is a Point, only one coordinate pair would be returned, in all other cases it's an array. One coordinate consists at least of the X and Y value, an additional Z value is supported by JTS (but not considered for operations like a distance calculation). In the next step we print the current coordinate and create a new array of coordinates (needed later for the comparison). In the next line we compare the current shortest distance to the given point with the distance of the current point and the given point.

In the next step, you could for example work with the annotations.

Written by:  Henry