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:
- Implement the Weighting class
- Create a subclass of GraphHopper and override
createWeighting
Or use the CustomWeighting feature explained in profiles.
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.
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(weightingStr)) {
return new MyCustomWeighting(encoder);
} else {
return super.createWeighting(hintsMap, encoder, graph);
}
}
}