After two hard days getting through the unit tests and snippets of graphhopper on GitHub and the JavaDocs, thinking that I might be able to put all together in a very basic java app, I have to come to the conclusion, that I am not able :(
All I want to do is:
- Build a graph
- Init graphhopper and configure it correctly
- Load the graph
- Route on it
Thats my code so far:
package javaapplication1;
import com.graphhopper.*;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.storage.GraphBuilder;
import com.graphhopper.storage.GraphStorage;
public class JavaApplication1 {
protected static String location = "./tmp/graphstorage";
protected static String defaultGraph = "./tmp/graphstorage/default";
private static final EncodingManager encodingManager = new EncodingManager("CAR");
public static GraphStorage createGraph() {
GraphStorage graph = new GraphBuilder(encodingManager).setLocation(location).create();
graph.setNode(0, 42, 10);
graph.setNode(1, 42.1, 10.1);
graph.setNode(2, 42.1, 10.2);
graph.setNode(3, 42, 10.4);
graph.setNode(4, 41.9, 10.2);
graph.edge(0, 1, 10, true);
graph.edge(1, 2, 10, false);
graph.edge(2, 3, 10, true);
graph.edge(0, 4, 40, true);
graph.edge(4, 3, 40, true);
return graph;
}
public static void main(String[] args) {
double fromLat = 42;
double fromLon = 10.4;
double toLat = 42;
double toLon = 10;
GraphStorage gs = createGraph();
GraphHopperAPI instance = new GraphHopper()
.setEncodingManager(encodingManager)
.setGraphHopperLocation(location)
.disableCHShortcuts();
GraphHopper hopper = (GraphHopper) instance;
//hopper.setGraph(createGraph()); // protected because only for testing?
hopper.load(location);
GHResponse ph = hopper.route(new GHRequest(fromLat, fromLon, toLat, toLon));
if(ph.isFound()) {
System.out.println(ph.getDistance());
System.out.println(ph.getPoints().getSize());
} else {
System.out.println("No Route found!");
}
}
}
Java says: "Exception in thread "main" java.lang.IllegalStateException: Call load or importOrLoad before routing". But I am calling .load() on hopper, which unfortunately returns 'false', but I am not able to figure out why.
My goal for this thread is to provide a very basic working code example of the GH Components and how to wire them up to solve the use case "Route on a graph, not loaded from OSM".