/* Css In-Brief */
| Key Points | Details to Remember |
|---|---|
| 📦 Installation | Add the Maven or Gradle dependency |
| 🗺️ Data | Extract the necessary OpenStreetMap extracts |
| ⚙️ Configuration | Customize routing profiles and options |
| 🚀 Execution | Load graphs and calculate routes |
| 🔍 Optimization | Reduce response time and memory size |
Customizing a route calculation within a Java application may seem complex, especially when dealing with road graphs and OSM data. Yet, GraphHopper offers an elegant and modular API, ready to be integrated into your project. In this guide, you will discover each phase – from installation to performance tuning – with concrete examples and tips to master the subtleties of configuration.
Sommaire
Introduction to GraphHopper
GraphHopper is an open-source library designed to provide offline road routing. It relies on OpenStreetMap (OSM) data and allows calculating optimized routes according to several criteria: distance, time, vehicle profile (car, bike, on foot). In reality, GraphHopper is not limited to a simple shortest path calculation: you can define constraints, use voice instructions, and even exploit surfaces for bikes and specialized road vehicles.
Origin and Use Cases
Initially launched for web geolocation services, GraphHopper quickly attracted desktop and embedded Java developers. Delivery applications, trip planning tools, and fleet management software rely on its engine. For example, GraphHopper can be integrated into an Android application, but also into a backend service that exposes routes via a REST API.
Prerequisites and Initial Installation
Creating a Java Project
Start by creating a Maven or Gradle project if you don’t already have one. In Eclipse or IntelliJ IDEA, select a standard Java project and ensure you use Java 8 or newer. GraphHopper benefits from streams and some modern Java APIs, so a JDK 11 or 17 is often recommended to enjoy performance and stability.
Adding the GraphHopper Dependency
In your pom.xml file, add:
<dependency>
<groupId>com.graphhopper</groupId>
<artifactId>graphhopper-core</artifactId>
<version>8.3</version>
</dependency>If you use Gradle:
implementation "com.graphhopper:graphhopper-core:8.3"This single dependency includes the routing engine, as well as modules for reading PBF files from OSM.
Preparing OpenStreetMap Data
For a router to work, it needs an OSM extract covering the targeted geographic area. You can download a .pbf file from Geofabrik or another mirror. One tip: limit yourself to the precise area (for example, a department) to reduce processing time and memory consumption.
Before importing, it is sometimes useful to clean or slightly edit the OSM file. In collaborative projects, we compare édition OpenStreetMap tools to adjust tags.
Step-by-step Integration
1. Load the data
Instantiate a GraphHopper object and specify the path to your PBF:
GraphHopper hopper = new GraphHopper()
.setGraphHopperLocation("data/graph-cache")
.setOSMFile("data/map.osm.pbf");
hopper.importOrLoad();The first run will create an optimized graph cache, while subsequent calls will load these files directly.
2. Initialize the router
Before sending a request, you can adjust the vehicle profiles:
hopper.setProfiles(
new Profile("car").setVehicle("car").setWeighting("fastest"),
new Profile("bike").setVehicle("bike").setWeighting("shortest")
);Each profile controls the routing strategy and the type of road GraphHopper should prioritize. It is possible to create profiles for trucks, pedestrians, or even scooters.
3. Execute a routing request
To get a route, build a request:
GHRequest req = new GHRequest(48.8566, 2.3522, 43.6047, 1.4442)
.setProfile("car")
.setLocale(Locale.FRENCH);
GHResponse resp = hopper.route(req);The result contains the distance, time, and a list of geographic points. You can also request detailed turn-by-turn instructions.
4. Handle the results
The GHResponse class offers several methods:
- getBest() to retrieve the best path
- getPoints() for the geometry
- getInstructions() for the list of actions
This data is suitable for display on an interactive map or GeoJSON export.

Advanced Optimizations
Once the basic flow is operational, two major levers are available to you:
- Memory compression: enable the
dataAccessoption in MMap mode for lighter loading. - Multi-threading: instantiate multiple threads on the routing module to process several requests simultaneously.
You can also adjust the granularity of OSM data (keeping only main roads) or generate pruning scripts to remove small irrelevant paths.
Practical Examples and Perspectives
Imagine you want to display a route on a national road map of France. After calculation, you export your points in GeoJSON and overlay the trace on a Leaflet or Mapbox layer. This integration gives you the flexibility to add waypoints, recalculate the route in real time, or display distance and elevation statistics.
In another case, you can run GraphHopper in server mode (standalone jar) and send requests via HTTP, turning your Java application into a routing microservice capable of serving thousands of calls per second.
FAQ
Q: Which version of Java should be used with GraphHopper?
A: GraphHopper recommends Java 11 or higher to benefit from recent APIs and better memory management.
Q: Can points of interest (POI) be integrated into the calculations?
A: Yes, simply add your POIs as waypoints in the GHRequest query, or customize the graph by adding specific nodes.
Q: How to reduce the size of the graph in memory?
A: Use the configuration.setDataAccessType(DataAccessType.MMAP)and limit the OSM area to the essentials by using a targeted PBF extract.
Q: Does GraphHopper handle traffic restrictions?
A: Yes, OSM properties such asaccess=noor tagsmotor_vehicle=noare taken into account during import.