Help

Integrate traffic data into your route planner

Update: there is a new blog post which shows integration of real time traffic info into GraphHopper from a real world example, including a simple UI based on HTML5 canvas.

There are several companies having its own traffic data e.g. those companies having an own fleet or fetching it from an external source. Often on the GraphHopper mailing list people ask how they can integrate this into GraphHopper and until now there was only descriptive information but no code example. This post will change this, where I’ve created a little demo project at github for this task. The demo is easy to use and provides a simple web service where you can POST your own JSON data influencing the routing. If you look at the Readme there are only three steps involved:

  • Start the route planner server with the area of your choice: ./td.sh datasource=your-osm-file.pbf
  • Visit http://localhost:8989 to try the routing
  • Now feed some data and try routing again:
    curl -H "Content-Type: application/json" --data @traffic.json http://localhost:8989/datafeed
    

The simulated traffic jam is marked red. The routing therefore tries to avoid it.

The necessary code is very minimal: just take the double value from JSON and use it as speed for the identified street:

edge.setFlags(carEncoder.setSpeed(edge.getFlags(), value));

A street is a so called ‘edge’ in GraphHopper, read more about internals e.g. in this presentation or in the official documentation. But how to find this GraphHopper edge from the coordinates (list of latitude,longitude)? Currently we just take the very first coordinate of the provided points list in the JSON:

Point point = entry.getPoints().get(0);
QueryResult qr = locationIndex.findClosest(point.lat, point.lon, EdgeFilter.ALL_EDGES);
EdgeIteratorState edge = graph.getEdgeProps(qr.getClosestEdge().getEdge(), Integer.MIN_VALUE);

But in reality this can get more complex and could be improved by using our map matching component. So we just hope here no other edge can be mixed up with a close but completely different edge. Such problems are possible if you get the data from external none-OpenStreetMap data sources or from vehicles on the road without a high precision coordinate information. Other important points on the TODO-list for this demo are that the routing should be locked while updating the graph and that stopping the server should flush the graph to make the newly received data persistent. Nevertheless this shows nicely how easy it is to feed GraphHopper with your own data where the possibilities are endlessly to e.g. block complete roads or prefer roads for routing and more. Let us know about your use case!