Skip to content
Permalink
Branch: master
Find file Copy path
46 lines (35 sloc) 3.11 KB

Weighting

A weighting allows to create a "weight" for an edge. The weight of an edge reflects the cost of travelling along this edge. All implementations of RoutingAlgorithm in GraphHopper calculate the shortest path, which means the path with the lowest overall cost from A to B. The definition of the cost function is up to you, so you can create a cost function (we call this weighting) for the fastest path. GraphHopper will still calculate the path with the lowest cost, but you can define the cost as a mix of distance speed, as shown in the FastestWeighting.

In order to create a custom weighting you need to do the following:

  1. Implement the Weighting class
  2. Create a subclass of GraphHopper and overwrite createWeighting

Implement your own weighting

A simple weighting is the ShortestWeighting, it calculates the shortest path. You could go from there and create your own weighting.

If you only want to change small parts of an existing weighting, it might be a good idea to extend the AbstractAdjustedWeighting, a sample can be found in the AvoidEdgesWeighting. If your weights change on a per-request base, like the BlockAreaWeighting, you cannot use the 'speed mode', but have to use the 'hybrid mode' or 'flexible mode' (more details here). If you haven't disabled the 'speed mode' in your config, you have to disable it for the requests by appending ch.disable=true in the request url.

Extend GraphHopper

For general information on how to extend GraphHopper have a look here.

Extending GraphHopper is easy, just need to override the createWeighting method of the GraphHopper class. We return a new instance of our custom weighting if the string my_custom_weighting is given. Otherwise let the super class handle it:

class MyGraphHopper extends GraphHopper {

    @Override
    public Weighting createWeighting(HintsMap hintsMap, FlagEncoder encoder, Graph graph) {
        String weightingStr = hintsMap.getWeighting().toLowerCase();
        if ("my_custom_weighting".equals(weighting)) {
            return new MyCustomWeighting(encoder);
        } else {
            return super.createWeighting(hintsMap, encoder, graph);
        }
    }
}
You can’t perform that action at this time.