GraphBuilder low-level-api in Java

Version 1.0 seems to use a different usage from .setLocation

Can someone please link or let me know to implement this in Java with the new version?

So I think I should be using GraphBuilder gb = new GraphBuilder(em).setRAM(ghLocation, true);

I cannot use the following as there is no method to load;

// Load and use the graph
GraphStorage graph = gb.load();

It results in java.lang.IllegalStateException: There is no CHGraph
It gets as far as:

PrepareContractionHierarchies pch = 
PrepareContractionHierarchies.fromGraphHopperStorage(graph, chConfig);

My Code:

        FlagEncoder encoder = new CarFlagEncoder();
        EncodingManager em = EncodingManager.create(encoder);
        GraphBuilder gb = new GraphBuilder(em).setRAM(ghLocation, true);
        Weighting weighting = new FastestWeighting(encoder);
        
        GraphHopperStorage graph = gb.create();

        
        TraversalMode tMode = TraversalMode.NODE_BASED;
        CHConfig chConfig = CHConfig.nodeBased("car", weighting);
        PrepareContractionHierarchies pch = PrepareContractionHierarchies.fromGraphHopperStorage(graph, chConfig);
        pch.doWork();
        // flush after preparation!
        //graph.flush();

         // Load index
        LocationIndex index = new LocationIndexTree(graph.getBaseGraph(), new RAMDirectory("graphhopper_folder", true));
        if (!index.loadExisting())
            throw new IllegalStateException("location index cannot be loaded!");

        // calculate path is identical
        QueryResult fromQR = index.findClosest(-41.26230044, 174.89648184, EdgeFilter.ALL_EDGES);
        QueryResult toQR = index.findClosest(-41.1393359, 174.77875032, EdgeFilter.ALL_EDGES);
        QueryGraph queryGraph = QueryGraph.create(graph, fromQR, toQR);

        // create the algorithm using the PrepareContractionHierarchies object
        AlgorithmOptions algoOpts = AlgorithmOptions.start().
           algorithm(Parameters.Algorithms.DIJKSTRA_BI).traversalMode(tMode).weighting(weighting).
           build();
        RoutingAlgorithm algorithm = pch.getRoutingAlgorithmFactory().createAlgo(queryGraph, algoOpts);
        Path path = algorithm.calcPath(fromQR.getClosestNode(), toQR.getClosestNode());
        System.out.println(path.getDistance());

You need to setup the CHGraph already when creating the graph initially. Actually this is rather ugly in my opinion and sooner or later we should be able to add CHGraphs to an existing storage.

I just updated the (indeed outdated) low-level-api.md here: https://github.com/graphhopper/graphhopper/commit/2207576a56b62da5a80fb4960fcac2096bdefb73

2 Likes

Thanks easbar, appreciate it.