package business;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Point;
import org.geotools.geometry.jts.JTS;
import org.geotools.graph.build.line.LineStringGraphGenerator;
import org.geotools.graph.structure.Graph;
import org.geotools.graph.structure.Node;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
public class NodeHelper {
private Node nearestNode = null;
private Double distanceFromGraphNode = 0.0;
// Compiles successfully when using geotools-2.7-RC2
// http://sourceforge.net/projects/geotools/files/GeoTools%202.7%20Releases/
// function to ge t the closest node to the location of interest (specified using a Point geometry)
public Node getNearestGraphNode(LineStringGraphGenerator lineStringGraphGenerator, Graph graph,
Point destinationPoint,
CoordinateReferenceSystem coordinateReferenceSystem) throws TransformException {
// init the distance
double dist = 999999999;
// Loops through the nodes of the graph and finds the node closest to the point of interest
for (Object object:graph.getNodes()) {
Node node = (Node) object;
Point point = ((Point) node.getObject());
//Logger.d(this.getClass().getSimpleName() + " node: " + node + ", point: " + point);
double nodeDist = calculateDistance(destinationPoint.getX(), destinationPoint.getY(), point.getCoordinate().x,
point.getCoordinate().y,
coordinateReferenceSystem);
//Logger.d(this.getClass().getSimpleName() + " nodeDist: " + nodeDist);
if (nodeDist < dist) {
dist = nodeDist;
//Logger.d(this.getClass().getSimpleName() + " Nearest node: " + nearestNode);
nearestNode = node;
}
}
//returns the node closest to the location of interest
//Node source = (BasicNode) lineStringGraphGenerator.getNode(new Coordinate(((Point)nearestNode.getObject()).getCoordinate().x,
// ((Point)nearestNode.getObject()).getCoordinate().y));
//stores the distance between node and location of interest, can be accessed by calling the getDistanceFromGraphNode() function
distanceFromGraphNode = dist;
return nearestNode;
}
public Double getDistanceFromGraphNode() {
//returns the distance between node and location of interest in Metres(depends on the projection system of course!!)
return distanceFromGraphNode;
}
private double calculateDistance(double xOrig, double yOrig, double xDest, double yDest,
CoordinateReferenceSystem coordinateReferenceSystem) throws TransformException {
//calculates straight line distance
Coordinate start = new Coordinate(xOrig, yOrig);
Coordinate end = new Coordinate(xDest, yDest);
return JTS.orthodromicDistance(start, end, coordinateReferenceSystem);
}
}