GraphHopper Directions API (1.0.0)

Download OpenAPI specification:Download

With the GraphHopper Directions API you can integrate A-to-B route planning, turn-by-turn navigation, route optimization, isochrone calculations, location clustering and other tools in your application.

The GraphHopper Directions API consists of the following RESTful web services:

Explore our APIs

Get started

  1. Sign up for GraphHopper and get a standard package for 2 weeks for free
  2. Create an API key

Each API part has its own documentation. Jump to the desired API part and learn about the API through the given examples and tutorials.

API Explorer

You can also try all API parts without registration in our API explorer.

API Explorer example showing the isochrone

API Client Libraries

To speed up development and make coding easier, we offer a JavaScript client and a Java client.

Optimize Response Speed

  1. Reuse SSL/TLS sessions

    You should utilize the SSL session to speed up responses after the initial response or use a library that does this. E.g. for Java the OkHttp library automatically reuses SSL/TLS sessions and also the browser takes care of this automatically. For python you can use the requests library: first you create a session (session = requests.Session()) and then do requests only with this session instead of directly using "requests".

  2. Bandwidth reduction

    If you create your own client, make sure it supports http/2 and gzipped responses for best speed. If you use the Matrix, the Route Optimization API or the and want to solve large problems, we recommend you to reduce bandwidth by compressing your POST request and specifying the header as follows: Content-Encoding: gzip. This will also avoid the HTTP 413 error "Request Entity Too Large".

Contact Us

If you have problems or questions, please read the following information:

To stay informed about the latest developments, you can

Map Data and Routing Profiles

The default data source is OpenStreetMap and as an alternative we have also integrated TomTom.

OpenStreetMap

Geographical Coverage

OpenStreetMap covers the whole world. If you want to see for yourself if we can provide data suitable for your region, please visit GraphHopper Maps. You can edit and modify OpenStreetMap data if you find that important information is missing, e.g. a weight limit for a bridge. Here is a beginner's guide that shows how to add data. If you have edited data, we usually consider your data after 1 week at the latest.

Standard Routing Profiles

The Routing, Matrix and Route Optimization APIs support the following profiles. But also see the section about customized profiles below the table.

Name Description Restrictions Icon
car Car mode car access, weight=2500kg, width=2m, height=2m car image
car_avoid_motorway Car mode like car that heavily penalizes motorways car image
car_avoid_ferry Car mode like car that heavily penalizes ferries car image
car_avoid_toll Car mode like car that heavily penalizes tolls and ferries car image
small_truck Small truck like a Mercedes Sprinter, Ford Transit or Iveco Daily height=2.7m, width=2+0.28m, length=5.5m, weight=2080+1400 kg small truck image
truck Truck like a MAN or Mercedes-Benz Actros height=3.7m, width=2.6+0.34m, length=12m, weight=13000+13000 kg, hgv=yes, 3 Axes truck image
scooter Moped mode Fast inner city, often used for food delivery, is able to ignore certain bollards, maximum speed of roughly 50km/h. weight=300kg, width=1m, height=2m scooter image
foot Pedestrian or walking without dangerous SAC-scales foot access foot image
hike Pedestrian or walking with priority for more beautiful hiking tours and potentially a bit longer than foot. Walking duration is influenced by elevation differences. foot access hike image
bike Trekking bike avoiding hills bike access Bike image
mtb Mountainbike bike access Mountainbike image
racingbike Bike preferring roads bike access Racingbike image
ecargobike Similar to racingbike but a bit faster and with width constraints. Currently only available upon request. bike access but without steps and footways Racingbike image
as_the_crow_flies Only available for the Cluster API. Uses the straight-line (or "direct") distance. This allows to use 5x more customers than the contractual "locations" limit defines. - -

Please note:

  • the free package supports only the routing profiles car, bike or foot
  • up to 3 different routing profiles can be used in a single request towards the Route Optimization API. The number of vehicles is unaffected and depends on your subscription.
  • we offer custom routing profiles with different properties, different speed profiles or different access options. To find out more about custom profiles, see the documentation and contact us.
  • a sophisticated motorcycle profile is available up on request. It is powered by the Kurviger Routing API and favors curves and slopes while avoiding cities and highways.

Customized Routing Profiles

You can also adjust the speeds, access options and much more by using customized routing profiles. We offer this for the Routing API (see the section about Custom Models). For interested customers we offer the Profiles API that can be used for matrix calculations and route optimiztion as well.

TomTom

If you want to include traffic, you can purchase the TomTom Add-on. This Add-on only uses TomTom's road network and historical traffic information. Live traffic is not yet considered. If you are interested to learn how we consider traffic information, we recommend that you read this article.

Please note the following:

Contact us if you want to buy this TomTom add-on.

Geographical Coverage

We offer

  • Europe including Russia
  • North, Central and South America
  • Saudi Arabia and United Arab Emirates
  • South Africa
  • Southeast Asia
  • Australia

Supported Vehicle Profiles

Name Description Restrictions Icon
car Car mode car access car image
small_truck Small truck like a Mercedes Sprinter, Ford Transit or Iveco Daily height=2.7m, width=2+0.28m, length=5.5m, weight=2080+1400 kg small truck image

Route Optimization API

Quickstart

The Route Optimization API can be used to solve traveling salesman or vehicle routing problems. Solve your first problem by following these steps. If you already have a GraphHopper account, start with step 2.

  1. Sign up for GraphHopper

  2. Create an API key

  3. Download simple traveling salesman problem and save it in a local folder

  4. Open your command line, go to that local folder and use cURL (What is cURL?) as follows:

    curl -X POST -H "Content-Type: application/json"   "https://graphhopper.com/api/1/vrp?key=YOUR_CREATED_API_KEY" --data "@tsp.json"
    

Alternatively, you can use our API Explorer to explore the Route Optimization API:

  1. Select 'Route Optimization API' in the left drop down
  2. Paste an existing JSON or select one from the examples
  3. Click 'Send' and analyze the solution on the map, in the table or as raw JSON output

If you have successfully solved the first problem, we recommend this tutorial - Getting Started with the Optimization API. It shows and describes the essential elements to model your vehicle routing problem.

To explore the full specification, we recommend that you either use our API explorer which will give you the output as JSON, in a table and directly on a map.

POST route optimization problem

Start by reading the introduction to the Route Optimization API.

To solve a new vehicle routing problem, make a HTTP POST to this URL

https://graphhopper.com/api/1/vrp?key=<your_key>

It returns the solution to this problem in the JSON response.

Please note that this URL is very well suited to solve minor problems. Larger vehicle routing problems, which take longer than 10 seconds to solve, cannot be solved. To solve them, please use the batch mode URL instead.

Securityapi_key
Request
Request Body schema: application/json
required

The request that contains the vehicle routing problem to be solved.

Array of objects (Vehicle) non-empty

Specifies the available vehicles.

Array of objects (VehicleType)

Specifies the available vehicle types. These types can be assigned to vehicles.

Array of objects (Service)

Specifies the orders of the type "service". These are, for example, pick-ups, deliveries or other stops that are to be approached by the specified vehicles. Each of these orders contains only one location.

Array of objects (Shipment)

Specifies the available shipments. Each shipment consists of a pickup and a delivery. For a single shipment, the pickup must always occur before the delivery. However, pickups and deliveries from multiple shipments can be sequenced independently.

Array of JobRelation (object) or GroupRelation (object)

Defines additional relationships between orders.

object (Algorithm)
Deprecated

Use objectives instead.

Array of objects (Objective)

Specifies an objective function. The vehicle routing problem is solved in such a way that this objective function is minimized.

Array of objects (CostMatrix)

Specifies your own tranport time and distance matrices.

object (Configuration)

Specifies general configurations.

Responses
200

A response containing the solution

400

Error occurred when reading the request. Request is invalid.

500

Error occurred on server side.

post/vrp
Request samples
application/json
{
  • "vehicles": [
    ],
  • "vehicle_types": [
    ],
  • "services": [
    ],
  • "shipments": [
    ],
  • "objectives": [
    ],
  • "configuration": {
    }
}
Response samples
application/json
{
  • "copyrights": [
    ],
  • "job_id": "d62fcadd-c84a-4298-90b5-28550125bec5",
  • "status": "finished",
  • "waiting_time_in_queue": 0,
  • "processing_time": 459,
  • "solution": {
    }
}

POST route optimization problem (batch mode)

To solve a vehicle routing problem, perform the following steps:

1.) Make a HTTP POST to this URL

https://graphhopper.com/api/1/vrp/optimize?key=<your_key>

It returns a job id (job_id).

2.) Take the job id and fetch the solution for the vehicle routing problem from this URL:

https://graphhopper.com/api/1/vrp/solution/<job_id>?key=<your_key>

We recommend to query the solution every 500ms until it returns 'status=finished'.

Note: Since the workflow is a bit more cumbersome and since you lose some time in fetching the solution, you should always prefer the synchronous endpoint. You should use the batch mode only for long running problems.

Securityapi_key
Request
Request Body schema: application/json
required

The request that contains the problem to be solved.

Array of objects (Vehicle) non-empty

Specifies the available vehicles.

Array of objects (VehicleType)

Specifies the available vehicle types. These types can be assigned to vehicles.

Array of objects (Service)

Specifies the orders of the type "service". These are, for example, pick-ups, deliveries or other stops that are to be approached by the specified vehicles. Each of these orders contains only one location.

Array of objects (Shipment)

Specifies the available shipments. Each shipment consists of a pickup and a delivery. For a single shipment, the pickup must always occur before the delivery. However, pickups and deliveries from multiple shipments can be sequenced independently.

Array of JobRelation (object) or GroupRelation (object)

Defines additional relationships between orders.

object (Algorithm)
Deprecated

Use objectives instead.

Array of objects (Objective)

Specifies an objective function. The vehicle routing problem is solved in such a way that this objective function is minimized.

Array of objects (CostMatrix)

Specifies your own tranport time and distance matrices.

object (Configuration)

Specifies general configurations.

Responses
200

A jobId you can use to retrieve your solution from the server - see solution endpoint.

400

Error occurred when reading client request. Request is invalid.

500

Error occurred on server side.

post/vrp/optimize
Request samples
application/json
{
  • "vehicles": [
    ],
  • "vehicle_types": [
    ],
  • "services": [
    ],
  • "shipments": [
    ],
  • "objectives": [
    ],
  • "configuration": {
    }
}
Response samples
application/json
{
  • "job_id": "44886560-b584-4da5-b245-768151dacd8f"
}

GET the solution (batch mode)

Take the job id and fetch the solution for the vehicle routing problem from this URL:

https://graphhopper.com/api/1/vrp/solution/<job_id>?key=<your_key>

You get the job id by sending a vehicle routing problem to the batch mode URL.

Securityapi_key
Request
path Parameters
jobId
required
string

Request solution with jobId

Responses
200

A response containing the solution

400

Error occurred on client side such as invalid input.

404

Requested solution could not be found.

500

Error occurred on server side.

get/vrp/solution/{jobId}
Request samples
curl -X GET "https://graphhopper.com/api/1/vrp/solution/job_id?key=api_key"
Response samples
application/json
{
  • "copyrights": [
    ],
  • "job_id": "d62fcadd-c84a-4298-90b5-28550125bec5",
  • "status": "finished",
  • "waiting_time_in_queue": 0,
  • "processing_time": 459,
  • "solution": {
    }
}

Routing API

Introduction

Routing screenshot

The Routing API calculates the best path connecting two or more points, where the meaning of ''best'' depends on the vehicle profile and use case. Besides path coordinates it can return turn-by-turn instructions, elevation, path details and other useful information about the route.

Use our API Explorer to explore the Routing API.

Tutorials

GET Route Endpoint

For the GET request you specify the parameters in the URL and can try it directly in every browser. However, it has some disadvantages when using many points (URL length limit) and the custom_model Feature cannot be used. Therefore, our recommended endpoint is the POST route endpoint.

Securityapi_key
Request
query Parameters
profile
string (VehicleProfileId)
Default: "car"

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

point
required
Array of strings

The points for which the route should be calculated. Format: latitude,longitude. Specify at least an origin and a destination. Via points are possible. The maximum number depends on your plan.

Example: point=51.131,12.414&point=48.224,3.867
point_hint
Array of strings

The point_hint is typically a road name to which the associated point parameter should be snapped to. Specify no point_hint parameter or the same number as you have point parameters.

snap_prevention
Array of strings

Optional parameter. 'Snapping' is the process of finding the closest road location for GPS coordinates provided in the point parameter. The snap_prevention parameter allows you to prevent snapping to specific types of roads. For example, if snap_prevention is set to bridge, the routing engine will avoid snapping to a bridge, even if it is the closest road for the given point. Current supported values: motorway, trunk, ferry, tunnel, bridge and ford. Multiple values are specified like snap_prevention=ferry&snap_prevention=motorway. Note that once snapped the routing algorithm can still route over bridges (or the other values). To avoid this you need to use the custom_model.

curbside
Array of strings

Optional parameter. It specifies on which side a point should be relative to the driver when she leaves/arrives at a start/target/via point. You need to specify this parameter for either none or all points. Only supported for motor vehicles and OpenStreetMap.

Items Enum: "any" "right" "left"
locale
string
Default: "en"

The locale of the resulting turn instructions. E.g. pt_PT for Portuguese or de for German.

elevation
boolean
Default: false

If true, a third coordinate, the altitude, is included with all positions in the response. This changes the format of the points and snapped_waypoints fields of the response, in both their encodings. Unless you switch off the points_encoded parameter, you need special code on the client side that can handle three-dimensional coordinates.

details
Array of strings

Optional parameter. The following path details are available: street_name, street_ref, street_destination, leg_time, leg_distance, roundabout, country, time, distance, max_speed, max_weight, max_width, toll, road_class, road_class_link, road_access, road_environment, hazmat, hazmat_tunnel, hazmat_water, lanes, surface, smoothness, hike_rating, mtb_rating, foot_network, bike_network. Read more about the usage of path details here.

optimize
string
Default: "false"

Normally, the calculated route will visit the points in the order you specified them. If you have more than two points, you can set this parameter to "true" and the points may be re-ordered to minimize the total travel time. Keep in mind that the limits on the number of locations of the Route Optimization API applies, and the request costs more credits.

instructions
boolean
Default: true

If instructions should be calculated and returned

calc_points
boolean
Default: true

If the points for the route should be calculated at all.

debug
boolean
Default: false

If true, the output will be formatted.

points_encoded
boolean
Default: true

Allows changing the encoding of location data in the response. The default is polyline encoding, which is compact but requires special client code to unpack. (We provide it in our JavaScript client library!) Set this parameter to false to switch the encoding to simple coordinate pairs like [lon,lat], or [lon,lat,elevation]. See the description of the response format for more information.

ch.disable
boolean
Default: false

Combine this parameter with any of the following options below.

heading
Array of integers <int32>

Favour a heading direction for a certain point. Specify either one heading for the start point or as many as there are points. In this case headings are associated by their order to the specific points. Headings are given as north based clockwise angle between 0 and 360 degree. This parameter also influences the tour generated with algorithm=round_trip and forces the initial direction. Requires ch.disable=true.

heading_penalty
integer <int32>
Default: 300

Time penalty in seconds for not obeying a specified heading. Requires ch.disable=true.

pass_through
boolean
Default: false

If true, u-turns are avoided at via-points with regard to the heading_penalty. Requires ch.disable=true.

algorithm
string

Rather than looking for the shortest or fastest path, this parameter lets you solve two different problems related to routing: With alternative_route, we give you not one but several routes that are close to optimal, but not too similar to each other. With round_trip, the route will get you back to where you started. This is meant for fun (think of a bike trip), so we will add some randomness. The round_trip option requires ch.disable=true. You can control both of these features with additional parameters, see below.

Enum: "round_trip" "alternative_route"
round_trip.distance
integer <int32>
Default: 10000

If algorithm=round_trip, this parameter configures approximative length of the resulting round trip. Requires ch.disable=true.

round_trip.seed
integer <int64>

If algorithm=round_trip, this sets the random seed. Change this to get a different tour for each value.

alternative_route.max_paths
integer <int32>
Default: 2

If algorithm=alternative_route, this parameter sets the number of maximum paths which should be calculated. Increasing can lead to worse alternatives.

alternative_route.max_weight_factor
number
Default: 1.4

If algorithm=alternative_route, this parameter sets the factor by which the alternatives routes can be longer than the optimal route. Increasing can lead to worse alternatives.

alternative_route.max_share_factor
number
Default: 0.6

If algorithm=alternative_route, this parameter specifies how similar an alternative route can be to the optimal route. Increasing can lead to worse alternatives.

Responses
200

Routing Result

400

Your request is not valid. For example, you specified too few or too many points.

401

Authentication necessary

429

API limit reached.

500

Internal server error. We get notified automatically and fix this asap.

get/route
Request samples
curl "https://graphhopper.com/api/1/route?point=51.131,12.414&point=48.224,3.867&profile=car&locale=de&calc_points=false&key=api_key"
Response samples
application/json
{
  • "hints": {
    },
  • "info": {
    },
  • "paths": [
    ]
}

POST Route Endpoint

To do a request you send JSON data.

See the GET endpoint for an alternative query method which is slightly simpler to get started but has some disadvantages.

Please note that in contrast to the GET endpoint, points are specified in the order of [longitude, latitude] and some parameter names use the plural. For example the string point=10,11&point=20,22 will be converted to the points array (plural):

{ "points": [[11,10], [22,20]] }

So this points array uses a format similar to GeoJson.

Example:

curl -X POST -H "Content-Type: application/json" "https://graphhopper.com/api/1/route?key=[YOUR_KEY]" -d '{"elevation":false,"points":[[-0.087891,51.534377],[-0.090637,51.467697]],"profile":"car"}'
Securityapi_key
Request
Request Body schema: application/json
profile
string (VehicleProfileId)

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

points
Array of numbers

The points for the route in an array of [longitude,latitude]. For instance, if you want to calculate a route from point A to B to C then you specify `points: [ [A_longitude, A_latitude], [B_longitude, B_latitude], [C_longitude, C_latitude]]

point_hints
Array of strings

Optional parameter. Specifies a hint for each point in the points array to prefer a certain street for the closest location lookup. E.g. if there is an address or house with two or more neighboring streets you can control for which street the closest location is looked up. Make sure you do not include the house number of city name and only the street name to improve the quality of the matching.

snap_preventions
Array of strings

Optional parameter. 'Snapping' is the process of finding the closest road location for GPS coordinates provided in the points array. The snap_preventions array allows you to prevent snapping to specific types of roads. For example, if the array includes bridge, then the routing engine will avoid snapping to a bridge, even if it is the closest road for the given point. Note that once snapped the routing algorithm can still route over bridges (or the other values). To avoid this you need to use the custom_model.

Items Enum: "motorway" "trunk" "bridge" "ford" "tunnel" "ferry"
curbsides
Array of strings

Optional parameter. It specifies on which side a point should be relative to the driver when she leaves/arrives at a start/target/via point. You need to specify this parameter for either none or all points. Only supported for motor vehicle profiles and OpenStreetMap.

Items Enum: "any" "right" "left"
locale
string
Default: "en"

The locale of the resulting turn instructions. E.g. pt_PT for Portuguese or de for German.

elevation
boolean
Default: false

If true, a third coordinate, the altitude, is included with all positions in the response. This changes the format of the points and snapped_waypoints fields of the response, in both their encodings. Unless you switch off the points_encoded parameter, you need special code on the client side that can handle three-dimensional coordinates.

details
Array of strings

Optional parameter. The following path details are available: street_name, street_ref, street_destination, leg_time, leg_distance, roundabout, country, time, distance, max_speed, max_weight, max_width, toll, road_class, road_class_link, road_access, road_environment, hazmat, hazmat_tunnel, hazmat_water, lanes, surface, smoothness, hike_rating, mtb_rating, foot_network, bike_network. Read more about the usage of path details here.

optimize
string
Default: "false"

Normally, the calculated route will visit the points in the order you specified them. If you have more than two points, you can set this parameter to "true" and the points may be re-ordered to minimize the total travel time. Keep in mind that the limits on the number of locations of the Route Optimization API applies, and the request costs more credits.

instructions
boolean
Default: true

If instructions should be calculated and returned

calc_points
boolean
Default: true

If the points for the route should be calculated at all.

debug
boolean
Default: false

If true, the output will be formatted.

points_encoded
boolean
Default: true

Allows changing the encoding of location data in the response. The default is polyline encoding, which is compact but requires special client code to unpack. (We provide it in our JavaScript client library!) Set this parameter to false to switch the encoding to simple coordinate pairs like [lon,lat], or [lon,lat,elevation]. See the description of the response format for more information.

ch.disable
boolean
Default: false

Use this parameter in combination with one or more parameters from below.

object (CustomModel)

The custom_model modifies the routing behaviour of the specified profile. See the detailed documentation. Below is a complete request example in Berlin that limits all speeds to 100km/h, excludes motorways and makes shorter routes a bit more likely than the default due to a higher distance_influence. Note that it also includes the "ch.disabled": true parameter which is required to make use of custom_model.

{
  "points": [
    [
      13.31543,
      52.509535
    ],
    [
      13.29779,
      52.512434
    ]
  ],
  "profile": "car",
  "ch.disable": true,
  "custom_model": {
    "speed": [
      {
        "if": "true",
        "limit_to": "100"
      }
    ],
    "priority": [
      {
        "if": "road_class == MOTORWAY",
        "multiply_by": "0"
      }
    ],
    "distance_influence": 100
  }
} 
headings
Array of integers <int32>

Favour a heading direction for a certain point. Specify either one heading for the start point or as many as there are points. In this case headings are associated by their order to the specific points. Headings are given as north based clockwise angle between 0 and 360 degree. This parameter also influences the tour generated with algorithm=round_trip and forces the initial direction. Requires ch.disable=true.

heading_penalty
integer <int32>
Default: 300

Time penalty in seconds for not obeying a specified heading. Requires ch.disable=true.

pass_through
boolean
Default: false

If true, u-turns are avoided at via-points with regard to the heading_penalty. Requires ch.disable=true.

algorithm
string

Rather than looking for the shortest or fastest path, this parameter lets you solve two different problems related to routing: With alternative_route, we give you not one but several routes that are close to optimal, but not too similar to each other. With round_trip, the route will get you back to where you started. This is meant for fun (think of a bike trip), so we will add some randomness. The round_trip option requires ch.disable=true. You can control both of these features with additional parameters, see below.

Enum: "round_trip" "alternative_route"
round_trip.distance
integer <int32>
Default: 10000

If algorithm=round_trip, this parameter configures approximative length of the resulting round trip. Requires ch.disable=true.

round_trip.seed
integer <int64>

If algorithm=round_trip, this sets the random seed. Change this to get a different tour for each value.

alternative_route.max_paths
integer <int32>
Default: 2

If algorithm=alternative_route, this parameter sets the number of maximum paths which should be calculated. Increasing can lead to worse alternatives.

alternative_route.max_weight_factor
number
Default: 1.4

If algorithm=alternative_route, this parameter sets the factor by which the alternatives routes can be longer than the optimal route. Increasing can lead to worse alternatives.

alternative_route.max_share_factor
number
Default: 0.6

If algorithm=alternative_route, this parameter specifies how similar an alternative route can be to the optimal route. Increasing can lead to worse alternatives.

Responses
200

Routing Result

400

Your request is not valid. For example, you specified too few or too many points.

401

Authentication necessary

429

API limit reached.

500

Internal server error. We get notified automatically and fix this asap.

post/route
Request samples
application/json
{
  • "profile": "bike",
  • "points": [
    ],
  • "point_hints": [
    ],
  • "snap_preventions": [
    ],
  • "details": [
    ]
}
Response samples
application/json
{
  • "hints": {
    },
  • "info": {
    },
  • "paths": [
    ]
}

Matrix API

Compute a matrix

Calculate a matrix of travel times and/or distances between N origins and M destinations.

This includes the common cases of routes from one origin to many destinations, or from many origins to one destination.

Securityapi_key
Request
Request Body schema: application/json
One of:
profile
string (VehicleProfileId)

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

from_points
Array of numbers

The origin points for the routes in an array of [longitude,latitude].

to_points
Array of numbers

The destination points for the routes in an array of [longitude,latitude].

from_point_hints
Array of strings

See point_hintsof symmetrical matrix

to_point_hints
Array of strings

See point_hintsof symmetrical matrix

snap_preventions
Array of strings

See snap_preventions of symmetrical matrix

from_curbsides
Array of strings

See curbsidesof symmetrical matrix

to_curbsides
Array of strings

See curbsidesof symmetrical matrix

out_arrays
Array of strings

Specifies which matrices should be included in the response. Specify one or more of the following options weights, times, distances. The units of the entries of distances are meters, of times are seconds and of weights is arbitrary and it can differ for different vehicles or versions of this API.

fail_fast
boolean
Default: true

Specifies whether or not the matrix calculation should return with an error as soon as possible in case some points cannot be found or some points are not connected. If set to false the time/weight/distance matrix will be calculated for all valid points and contain the null value for all entries that could not be calculated. The hint field of the response will also contain additional information about what went wrong (see its documentation).

Responses
200

Matrix API response

post/matrix
Request samples
application/json
{
  • "from_points": [
    ],
  • "to_points": [
    ],
  • "from_point_hints": [
    ],
  • "to_point_hints": [
    ],
  • "out_arrays": [
    ],
  • "vehicle": "car"
}
Response samples
application/json
{
  • "distances": [
    ],
  • "times": [
    ],
  • "weights": [
    ],
  • "info": {
    }
}

Compute a matrix

For N origins and M destinations, compute routes from all origins to all destinations and output the result as a matrix of travel times and/or distances.

This includes the common cases of routes from one origin to many destinations, or from many origins to one destination.

Securityapi_key
Request
query Parameters
profile
string (VehicleProfileId)
Default: "car"

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

point
Array of strings

Specify multiple points in latitude,longitude for which the weight-, route-, time- or distance-matrix should be calculated. In this case the starts are identical to the destinations. If there are N points, then NxN entries will be calculated. The order of the point parameter is important. Specify at least three points. Cannot be used together with from_point or to_point.

from_point
Array of strings

The origin points for the routes in latitude,longitude. E.g. if you want to calculate the three routes A->1, A->2, A->3 then you have one from_point parameter and three to_point parameters.

to_point
Array of strings

The destination points for the routes in latitude,longitude.

point_hint
Array of strings

Optional parameter. Specifies a hint for each point parameter to prefer a certain street for the closest location lookup. E.g. if there is an address or house with two or more neighboring streets you can control for which street the closest location is looked up.

from_point_hint
Array of strings

For the from_point parameter. See point_hint

to_point_hint
Array of strings

For the to_point parameter. See point_hint

snap_prevention
Array of strings

Optional parameter. 'Snapping' is the process of finding the closest road location for GPS coordinates provided in the point parameter. The snap_prevention parameter allows you to prevent snapping to specific types of roads. For example, if snap_prevention is set to bridge, the routing engine will avoid snapping to a bridge, even if it is the closest road for the given point. Current supported values: motorway, trunk, ferry, tunnel, bridge and ford. Multiple values are specified like snap_prevention=ferry&snap_prevention=motorway. Note that once snapped the routing algorithm can still route over bridges (or the other values). To avoid this you need to use the custom_model.

curbside
Array of strings

Optional parameter. It specifies on which side a point should be relative to the driver when she leaves/arrives at a start/target/via point. You need to specify this parameter for either none or all points. Only supported for motor vehicles and OpenStreetMap.

Items Enum: "any" "right" "left"
from_curbside
Array of strings

Curbside setting for the from_point parameter. See curbside.

Items Enum: "any" "right" "left"
to_curbside
Array of strings

Curbside setting for the to_point parameter. See curbside.

Items Enum: "any" "right" "left"
out_array
Array of strings

Specifies which arrays should be included in the response. Specify one or more of the following options 'weights', 'times', 'distances'. To specify more than one array use e.g. out_array=times&out_array=distances. The units of the entries of distances are meters, of times are seconds and of weights is arbitrary and it can differ for different vehicles or versions of this API.

fail_fast
boolean
Default: true

Specifies whether or not the matrix calculation should return with an error as soon as possible in case some points cannot be found or some points are not connected. If set to false the time/weight/distance matrix will be calculated for all valid points and contain the null value for all entries that could not be calculated. The hint field of the response will also contain additional information about what went wrong (see its documentation).

Responses
200

Matrix API response

get/matrix
Request samples
curl "https://graphhopper.com/api/1/matrix?point=49.932707,11.588051&point=50.241935,10.747375&point=50.118817,11.983337&type=json&profile=car&out_array=weights&out_array=times&out_array=distances&key=api_key"
Response samples
application/json
{
  • "distances": [
    ],
  • "times": [
    ],
  • "weights": [
    ],
  • "info": {
    }
}

Submit a matrix computation job

An alternate endpoint for computing a large matrix asynchronously, where a request against the regular endpoint would result in a timeout.

The request format is the same, but instead of the result, you are given a job identification number that you can use to retrieve the result once it is available.

In most cases, prefer the regular endpoints.

Here are some full examples via curl:

$ curl -X POST -H "Content-Type: application/json" "https://graphhopper.com/api/1/matrix/calculate?key=[YOUR_KEY]" -d '{"points":[[13.29895,52.48696],[13.370876,52.489575],[13.439026,52.511206]]}'
{"job_id":"7ac65787-fb99-4e02-a832-2c3010c70097"}

Pick the returned job_id and use it in the next GET requests:

$ curl -X GET "https://graphhopper.com/api/1/matrix/solution/7ac65787-fb99-4e02-a832-2c3010c70097?key=[YOUR_KEY]"
{"status":"waiting"}

When the calculation is finished (status:finished) the JSON response will contain the full matrix JSON under solution:

$ curl -X GET "https://graphhopper.com/api/1/matrix/solution/7ac65787-fb99-4e02-a832-2c3010c70097?key=[YOUR_KEY]"
{"solution":{"weights":[[0.0,470.453,945.414],[503.793,0.0,580.871],[970.49,569.511,0.0]],"info":{"copyrights":["GraphHopper","OpenStreetMap contributors"]}},"status":"finished"}

Please note that if an error occured while calculation the JSON will not have a status but contain directly the error message e.g.:

{"message":"Cannot find from_points: 1"}

And the optional hints array.

Securityapi_key
Request
Request Body schema: application/json
One of:
profile
string (VehicleProfileId)

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

from_points
Array of numbers

The origin points for the routes in an array of [longitude,latitude].

to_points
Array of numbers

The destination points for the routes in an array of [longitude,latitude].

from_point_hints
Array of strings

See point_hintsof symmetrical matrix

to_point_hints
Array of strings

See point_hintsof symmetrical matrix

snap_preventions
Array of strings

See snap_preventions of symmetrical matrix

from_curbsides
Array of strings

See curbsidesof symmetrical matrix

to_curbsides
Array of strings

See curbsidesof symmetrical matrix

out_arrays
Array of strings

Specifies which matrices should be included in the response. Specify one or more of the following options weights, times, distances. The units of the entries of distances are meters, of times are seconds and of weights is arbitrary and it can differ for different vehicles or versions of this API.

fail_fast
boolean
Default: true

Specifies whether or not the matrix calculation should return with an error as soon as possible in case some points cannot be found or some points are not connected. If set to false the time/weight/distance matrix will be calculated for all valid points and contain the null value for all entries that could not be calculated. The hint field of the response will also contain additional information about what went wrong (see its documentation).

Responses
200

A jobId you can use to retrieve your solution from the server.

post/matrix/calculate
Request samples
application/json
{
  • "from_points": [
    ],
  • "to_points": [
    ],
  • "from_point_hints": [
    ],
  • "to_point_hints": [
    ],
  • "out_arrays": [
    ],
  • "vehicle": "car"
}
Response samples
application/json
{
  • "job_id": "44886560-b584-4da5-b245-768151dacd8f"
}

Retrieve result of a matrix computation job

Securityapi_key
Request
path Parameters
jobId
required
string

The jobId you received when you submitted the job.

Responses
200

A response containing the matrix

get/matrix/solution/{jobId}
Request samples
Response samples
application/json
{
  • "solution": {
    }
}

Geocoding API

Everything about geocoding

Geocoding Endpoint

Introduction

Geocoding Example

Geocoding describes the process of transforming an textual address representation to a coordinate (latitude,longitude). For example the conversion from Berlin to 52.5170365,13.3888599.

Reverse geocoding converts a coordinate to a textual address representation or place name. Find out more about Geocoding itself on Wikipedia.

Securityapi_key
Request
query Parameters
q
string

A textual description of the address you are looking for. Required for forward geocoding. Note that the default geocoding provider does prefix searches preferable for "autocomplete" use cases, but may lead to sub-optimal results if used without user interaction. See e.g. provider=nominatim as an appropriate alternative for less interactive use cases.

locale
string
Default: "en"

Display the search results for the specified locale. Currently French (fr), English (en) and German (de) are explicitly supported. Otherwise leave the locale empty.

limit
integer <int32>
Default: 5

Specify the maximum number of results to return

reverse
boolean
Default: false

It is required to be true if you want to do a reverse geocoding request. If it is true, point must be defined as well, and q must not be used.

debug
boolean
Default: false

If true, the output will be formatted.

point
string

Forward geocoding: The location bias in the format 'latitude,longitude' e.g. point=45.93272,11.58803. Reverse geocoding: The location to find amenities, cities.

provider
string
Default: "default"

The provider parameter is currently under development and can fall back to default at any time. The intend is to provide alternatives to our default geocoder. Each provider has its own strenghts and might fit better for certain scenarios, so it's worth to compare the different providers. To try it append the providerparameter to the URL like &provider=nominatim, the result structure should be identical in all cases - if not, please report this back to us. Keep in mind that some providers do not support certain parameters or don't return some fields, for example osm_id and osm_type are not supported by every geocoding provider. If you would like to use additional parameters of one of the providers, but it's not available for the GraphHopper Geocoding API, yet? Please contact us.

The credit costs can be different for all providers - see here for more information about it.

Currently, only the default provider and gisgraphy support autocompletion of partial search strings.

All providers support normal "forward" geocoding and reverse geocoding via reverse=true.

Default (provider=default)

This provider returns results of our internal geocoding engine. It is best suited for use cases with user interaction as it does prefix searches required for an "autocomplete" use case (a user types an address into a search field).

In addition to the above documented parameters the following parameters are possible:

  • osm_tag - you can filter key:value or exclude places with certain OpenStreetMap tags !key:value. E.g. osm_tag=tourism:museum or just the key osm_tag=tourism. To exclude multiple tags you add multiple osm_tag parameters.
  • location_bias_scale - describes how much the prominence of a result should still be taken into account. Sensible values go from 0.0 (ignore prominence almost completely) to 1.0 (prominence has approximately the same influence as the location). The default is 0.2.
  • zoom - describes the radius around the center to focus on. This is a number that should correspond roughly to the map zoom parameter of a corresponding map. The default is zoom=16.
  • bbox - the expected format is minLon,minLat,maxLon,maxLat. This requires reverse=false.
  • radius - the search radius in km for the reverse search. This requires reverse=true.

Nominatim (provider=nominatim)

The GraphHopper Directions API uses a commercially hosted Nominatim geocoder (hosted by OpenCageData). It is best suited for use cases without or less user interaction like batch processing or detailed location data retrieval. It is not suited for "autocomplete".

In addition to the above documented parameters we currently support the following parameters:

  • countrycode - The country code is a two letter code as defined by the ISO 3166-1 Alpha 2 standard. E.g. gb for the United Kingdom, fr for France, us for United States.
  • bounds - the expected format is minLon,minLat,maxLon,maxLat

Gisgraphy (provider=gisgraphy)

This provider returns results from the Gisgraphy geocoder which you can try here.

Limitations: The locale parameter is not supported. Gisgraphy does not return OSM tags or an extent.

Gisgraphy has a special autocomplete API, which you can use by adding autocomplete=true (does not work with reverse=true). The autocomplete API is optimized on predicting text input, but returns less information.

In addition to the above documented parameters Gisgraphy allows to use the following parameters, which can be used as documented here:

  • radius - radius in meters
  • country - restrict search for the specified country. The value must be the ISO 3166 Alpha 2 code of the country.

NetToolKit (provider=nettoolkit)

This provider returns results from the NetToolKit provider which is specialized for US addresses and provides a wrapper around Nominatim for other addresses. You can try it here.

The following additional NetToolKit parameters are supported (read here for more details):

  • source: User can choose which source provider to geocode the address, this value is "NetToolKit" by default
  • country_code: an iso-3166-2 country code (e.g : US) filter the results to the specify country code

Limitations: NetToolKit does not support the locale parameter. NetToolKit does not return OSM tags (e.g. osm_id, osm_type, osm_value).

OpenCage Data (provider=opencagedata)

This provider returns results from the OpenCageData geocoder which you can try here. The difference to the nominatim provider is that other geocoders might be used under the hood.

In addition to the above documented parameters OpenCage Data allows to use the following parameters, which can be used as documented here:

  • countrycode - The country code is a two letter code as defined by the ISO 3166-1 Alpha 2 standard. E.g. gb for the United Kingdom, fr for France, us for United States.
  • bounds - the expected format is minLon,minLat,maxLon,maxLat
Responses
200

An array found locations

get/geocode
Request samples
curl "https://graphhopper.com/api/1/geocode?q=berlin&locale=de&key=api_key"
Response samples
application/json
{
  • "hits": [
    ],
  • "took": 37
}

Isochrone API

Everything about isochrones

Isochrone Endpoint

Example

You can get an example response via:

curl "https://graphhopper.com/api/1/isochrone?point=51.131108,12.414551&key=[YOUR_KEY]"

Don't forget to replace the placeholder with your own key.

Introduction

Isochrone screenshot

An isochrone of a location is ''a line connecting points at which a vehicle arrives at the same time'', see Wikipedia. With the same API you can also calculate isodistances, just use the parameter distance_limit instead of time_limit`.

Use Cases

Some possible areas in which this API may be useful to you:

  • real estate analysis
  • realtors
  • vehicle scheduling
  • geomarketing
  • reach of electric vehicles
  • transport planning
  • logistics (distribution and retail network planning)

API Clients and Examples

See the clients section in the main documentation, and our API explorer.

Securityapi_key
Request
query Parameters
point
required
string

Specify the start coordinate

time_limit
integer <int32>
Default: 600

Specify which time the vehicle should travel. In seconds.

distance_limit
integer <int32>

Specify which distance the vehicle should travel. In meters.

profile
string (VehicleProfileId)
Default: "car"

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

buckets
integer <int32>
Default: 1

Number by which to divide the given time_limit to create buckets nested isochrones of time intervals time_limit-n*time_limit/buckets. Applies analogously to distance_limit.

reverse_flow
boolean
Default: false

If false the flow goes from point to the polygon, if true the flow goes from the polygon "inside" to the point. Example use case for false: How many potential customer can be reached within 30min travel time from your store vs. true: How many customers can reach your store within 30min travel time.

Responses
200

Isochrone Result

get/isochrone
Request samples
Response samples
application/json
{
  • "polygons": [
    ]
}

Map Matching API

Everything about map matching aka "snap to road"

Map-match a GPX file

Example

You get an example response for a GPX via:

curl -XPOST -H "Content-Type: application/gpx+xml" "https://graphhopper.com/api/1/match?profile=car&key=[YOUR_KEY]" --data @/path/to/some.gpx

A minimal working GPX file looks like

<gpx>
 <trk>
  <trkseg>
   <trkpt lat="51.343657" lon="12.360708"></trkpt>
   <trkpt lat="51.343796" lon="12.361337"></trkpt>
   <trkpt lat="51.342784" lon="12.361882"></trkpt>
  </trkseg>
 </trk>
</gpx>

Introduction

Map Matching screenshot

The Map Matching API is part of the GraphHopper Directions API and with this API you can snap measured GPS points typically as GPX files to a digital road network to e.g. clean data or attach certain data like elevation or turn instructions to it. Read more at Wikipedia.

In the example screenshot above and demo you see the Map Matching API in action where the black line is the GPS track and the green one is matched result.

To get a match response you send a GPX file in the body of an HTTP POST request and specify request parameters like the key and profile in the URL. See below for more supported parameters.

API Clients and Examples

See the clients section in the main documentation, and our API explorer.

Limits and Counts

The cost for one request depends on the number of GPS location and is documented here.

One request should not exceed the Map Matching API location limit depending on the package, see the pricing in our dashboard.

Securityapi_key
Request
query Parameters
gps_accuracy
integer

Specify the precision of a point, in meter

profile
string (VehicleProfileId)
Default: "car"

The routing profile. It determines the network, speed and other physical attributes used when computing the route. See the section about routing profiles for more details and valid profile values.

locale
string
Default: "en"

The locale of the resulting turn instructions. E.g. pt_PT for Portuguese or de for German.

elevation
boolean
Default: false

If true, a third coordinate, the altitude, is included with all positions in the response. This changes the format of the points and snapped_waypoints fields of the response, in both their encodings. Unless you switch off the points_encoded parameter, you need special code on the client side that can handle three-dimensional coordinates.

details
Array of strings

Optional parameter. The following path details are available: street_name, street_ref, street_destination, leg_time, leg_distance, roundabout, country, time, distance, max_speed, max_weight, max_width, toll, road_class, road_class_link, road_access, road_environment, hazmat, hazmat_tunnel, hazmat_water, lanes, surface, smoothness, hike_rating, mtb_rating, foot_network, bike_network. Read more about the usage of path details here.

instructions
boolean
Default: true

If instructions should be calculated and returned

calc_points
boolean
Default: true

If the points for the route should be calculated at all.

points_encoded
boolean
Default: true

Allows changing the encoding of location data in the response. The default is polyline encoding, which is compact but requires special client code to unpack. (We provide it in our JavaScript client library!) Set this parameter to false to switch the encoding to simple coordinate pairs like [lon,lat], or [lon,lat,elevation]. See the description of the response format for more information.

Responses
200

Map matching result

post/match
Request samples
curl -XPOST -H "Content-Type: application/gpx+xml" "https://graphhopper.com/api/1/match?profile=car&key=[YOUR_KEY]" -d '
  <gpx>
    <trk>
      <trkseg>
        <trkpt lat="51.343657" lon="12.360708"></trkpt>
        <trkpt lat="51.343796" lon="12.361337"></trkpt>
        <trkpt lat="51.342784" lon="12.361882"></trkpt>
      </trkseg>
    </trk>
  </gpx>'
Response samples
application/json
{
  • "hints": {
    },
  • "info": {
    },
  • "paths": [
    ]
}

Cluster API

Introduction

Cluster Example

It solves the “capacity clustering problem” by assigning a set of customers to a given number of distinct groups (called clusters). The API “clusters” by minimizing the total distance from each individual customer to its designated group median. It can also consider minimum and maximum capacity restrictions for each group.

Clustering can be used in many practical applications. For example, it can help to plan territories, i.e. territory optimization for field teams with large territories for field workers, or to solve large vehicle routing problems (VRP).

Try the Cluster API in our API Explorer!

The idea is to divide a certain number of customers, a pre-specified number of clusters. As already written above, a distribution is sought that minimizes the total cost (e.g. distance or time or a function of distance and time). We currently support two approaches.

  1. You can simply define a certain number of clusters via configuration ("clustering" with empty set of "clusters") and additionally how many customers should be in such a cluster. This is defined by an upper and lower limit ("min_quantity" and "max_quantity). The algorithm then searches for suitable clusters and divides the customers into these clusters.

  2. You can explicitly define clusters via "clusters". In this way, each individual cluster can be defined. This approach not only allows each cluster to have its own capacity upper and lower bound, but each cluster can also be assigned a fixed cluster center. In contrast to 1. the algorithm then does not search for a suitable center, but assigns the customers given the fixed centers to each cluster. Note that if you define clusters explicitly, any configuration of "clustering" will be overwritten by these explicit clusters.

POST Cluster Endpoint

The Cluster endpoint is used with a POST request towards https://graphhopper.com/api/1/cluster?key=<your_key>. The solution will be provided in the JSON response. Please note that for problems that take longer than 10 seconds a bad request error is returned. In this case please use the asynchronous Batch Cluster Endpoint instead.

Securityapi_key
Request
Request Body schema: application/json
required

Request object that contains the problem to be solved

object (ClusterConfiguration)
Array of objects (Clusters)
Array of objects (ClusterCustomer)
Responses
200

A response containing the solution

400

Error occurred when reading the request. Request is invalid.

500

Error occurred on server side.

post/cluster
Request samples
application/json
{
  • "configuration": {
    },
  • "clusters": [
    ],
  • "customers": [
    ]
}
Response samples
application/json
{
  • "copyrights": [
    ],
  • "status": "finished",
  • "waiting_time_in_queue": 0,
  • "processing_time": 4900,
  • "clusters": [
    ]
}

Batch Cluster Endpoint

Prefer the synchronous endpoint and use this Batch Cluster endpoint for long running problems only. The work flow is asynchronous:

  • send a POST request towards https://graphhopper.com/api/1/cluster/calculate?key=<your_key> and fetch the job_id.
  • poll the solution every 500ms until it gives status=finished. Do this with a GET request towards https://graphhopper.com/api/1/cluster/solution/<job_id>?key=<your_key>.
Securityapi_key
Request
Request Body schema: application/json
required

Request object that contains the problem to be solved

object (ClusterConfiguration)
Array of objects (Clusters)
Array of objects (ClusterCustomer)
Responses
200

A jobId you can use to retrieve your solution from the server - see solution endpoint.

400

Error occurred when reading client request. Request is invalid.

500

Error occurred on server side.

post/cluster/calculate
Request samples