OSRM
OSRM
Servidor de rutas
1 Building OSRM
General build instructions from source
OSRM source is available via git or source archives, and is built with CMake.
1.1.1.1 Git
If you would like to build a specific release (optional), you can list the release tags with git tag
-l and then checkout a specific tag using git checkout tags/<tag_name>.
OSRM can be built from the source archives available on the releases page. Example:
wget https://github.com/Project-OSRM/osrm-backend/archive/vX.Y.Z.tar.gz
tar -xzf vX.Y.Z.tar.gz
cd osrm-backend-X.Y.Z
1.1.1.3 Building
mkdir -p build
cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build .
sudo cmake --build . --target install
1.1.2 Ubuntu
For Ubuntu we support two ways of getting dependencies installed:
• Building on Ubuntu - using apt (the default, try this first)
• Building with Mason - using Mason (fetching pre-built packages externally)
Building on Squeeze and Wheezy requires getting a recent gcc, boost, and other packages.
Probably building them from source. It can be done but is unsupported and not recommended.
Open a ticket if you need help there.
CentOS 7.x only ships with gcc 4.8.5 which is too old to build OSRM, so install a more recent
gcc from the CentOS Software Collections:
For all other dependencies make use of mason so that Boost and so on don't have to be built
manually as well:
2.1 Quickstart
For the MLD pipeline we need to extract (osrm-extract) a graph out of the OpenStreetMap
base map, then partition (osrm-partition) this graph recursively into cells, customize the cells
(osrm-customize) by calculating routing weights for all cells, and then spawning up the
development HTTP server (osrm-routed) responding to queries:
wget http://download.geofabrik.de/europe/germany/berlin-latest.osm.pbf
osrm-extract berlin.osm.pbf
osrm-partition berlin.osrm
osrm-customize berlin.osrm
For CH the partition and customize pipeline stage gets replaced by adding shortcuts from the
Contraction Hierarchies algorithm (osrm-contract):
wget http://download.geofabrik.de/europe/germany/berlin-latest.osm.pbf
osrm-routed berlin-latest.osrm
2.2 Extracting the Road Network (osrm-extract)
Exported OSM data files can be obtained from providers such as Geofabrik. OSM data comes in a
variety of formats including XML and PBF, and contain a plethora of data. The data includes
information which is irrelevant to routing, such as positions of public waste baskets. Also, the
data does not conform to a hard standard and important information can be described in various
ways. Thus it is necessary to extract the routing data into a normalized format. This is done by
the OSRM tool named extractor. It parses the contents of the exported OSM file and writes out
routing metadata.
Profiles are used during this process to determine what can be routed along, and what cannot
(private roads, barriers etc.).
It's best to provide a swapfile so that the out-of-memory situations do not kill OSRM (the size
depends on your map data):
Note: this does not write 100 GB of zeros. Instead what it does is allocating a certain amount of
blocks and just setting the 'uninitialized' flag on them, returning more or less immediately.
External memory accesses are handled by the stxxl library. Although you can run the code
without any special configuration you might see a warning similar to [STXXL-ERRMSG]
Warning: no config file found. Given you have enough free disk space, you can happily
ignore the warning or create a config file called .stxxl in the same directory where the extractor
tool sits. The following is taken from the stxxl manual:
You must define the disk configuration for an STXXL program in a file named '.stxxl' that must
reside in the same directory where you execute the program. You can change the default file
name for the configuration file by setting the enviroment variable STXXLCFG .
Each line of the configuration file describes a disk. A disk description uses the following format:
disk=full_disk_filename,capacity,access_method
Example: at the time of writing this (v4.9.1) the demo server uses 250GB stxxl file with the
following configuration:
disk=/path/to/stxxl,250000,syscall
osrm-contract map.osrm
where map.osrm is the extracted road network. Both are generated by the previous step. A
nearest-neighbor data structure and a node map are created alongside the hierarchy.
osrm-routed map.osrm
You can access the API on localhost:5000. See the Server API for details on how to use it.
Here is how to run an example query:
curl "http://127.0.0.1:5000/route/v1/driving/13.388860,52.517037;13.385983,52.496891?steps=true"
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
This setup assumes you have 3 different osrm-routed servers running, each using a different
.osrm file set, and each running on a different HTTP port (5000, 5001, and 5002).
The driving, walking, cycling part of the URL is used by nginx to select the correct proxy
backend, but after that, osrm-routed ignores it and just returns a route on whatever data that
instance of osrm-routed is running with. It's up to you to ensure that the correct osrm-routed
instance is using the correct datafiles so that /driving/ actually routes on a dataset generated
from the car.lua profile.
3 Disk and Memory Requirements
Note: the following rough numbers are as of v5.8 and on OpenStreetMap planets from July
2017.
3.1 Pre-Processing
For the car profile you will need
• around 175 GB of RAM for pre-processing
• around 280 GB of STXXL disk space
you'll also need 35 GB for the planet .osm.pbf file, and 40-50 GB for the generated datafiles.
For the foot profile the latest number we have are about 248 GB of RAM. Everything else is
proportionally larger.
The profile has a big impact on size - the foot profile includes a lot more ways/roads/paths than
the car profile, so it needs more resources. The cycling profile sits somewhere in between.
3.2 Runtime
For the car profile you will need
• around 64GB of RAM
We basically just load all the files into memory, so whatever the output file size from pre-
processing - that's roughly how much RAM you'll need (minus the size of the .fileIndex file,
which is mmap()-ed and read on-demand).
4 Configuring and using Shared Memory
Usually, when you start an application and it allocates some block of memory, this is freed after
your application terminates. And also, this memory is only accessible to a single process only.
And then, there is shared memory. It allows you to share data among a number of processes and
the shared memory we use is persistent. It stays in the system until it is explicitly removed.
By default, there is some restriction on the size of and shared memory segment. Depending on
your distribution and its version it may be as little as 64 kilobytes. This is of course not enough
for serious applications.
The following gives a brief description on how to set the limits in a way that you (most probably)
won't ever run into them in the future. Please read up on actual settings for your production
environment in the manpage of shmctl, or consult further information, eg. here.
First, we are going to raise the system limits. Second, we are going to raise the user limits.
kernel.shmall = 1152921504606846720
kernel.shmmax = 18446744073709551615
and then run sysctl -p with super-user privileges. Then check if settings were accepted:
$ ipcs -lm
4.1.1.2 OS X
kern.sysv.shmmax=1073741824
kern.sysv.shmall=262144
kern.sysv.shmseg=256
Then reboot.
So, as a user we are allowed to only lock at most 64 KiB into RAM. This is obviously not
enough. The settings can be changed by editing /etc/security/limits.conf. Add the
following lines to the file, to raise the user limits to 64 GiB. At the time of writing, this is enough
to do planet-wide car routing.
Note that is the user name under which the routing process is running, and you need to re-login
to activate these changes. If the user does not have a login, you can use sudo -i -u <user> to
simulate an initial login.
Note that on Ubuntu 12.04 LTS it is also necessary to edit /etc/pam.d/su (and
/etc/pam.d/common-session) and remove the comment from the following line in order to
activate /etc/security/limits.conf:
$ ./osrm-datastore /path/to/data.osrm
If there is insufficient available RAM (or not enough space configured), you will receive the
following warning when loading data with osrm-datastore:
In this case, data will be swapped to a cache on disk, and you will still be able to run queries. But
note that caching comes at the prices of disk latency.
You will also see an error message, if you are lacking the CAP_IPC_LOCK capability for system-
wide memory locking. In this case granting the capability manually helps:
Starting the routing process and pointing it to shared memory is also very, very easy:
$ ./osrm-routed --shared-memory
Since OSRM 5.17 we allow multiple datasets in memory at the same time:
50267,27780,32,30.3 <- duration will be updated, weight will be updated with 30.3*length
25296,25295,24 <- duration will be updated, weight will be updated to match duration
34491,34494,3, <- duration will be updated, weight will be unchanged
2837,23844,3,,junk <- duration will be updated, weight will be unchanged, junk is ignored
1283974,2387,3,junk <- will cause an error
Every line should be a restriction, an empty line will result in an Segment speed file updates.csv malformed
error
The from/to ids are OSM node IDs that are directly connected. To update the speed for an entire
way, you must list each node pair along the way in the CSV file. Note that order is important, to
update both directions for connected nodes A and B, you must list
A,B,new_speed_forward(,new_rate_forward)? and
B,A,new_speed_backward(,new_rate_backward)?.
As of OSRM 5.7 the --generate-edge-lookup flag does nothing and this will work without it.
Since this is too slow for big datasets to get meaningful updates cycles, you can do a partial
contraction using the --core parameter. A core factor drastically increases query times. As a
result, the alternative-route search is slowed down immensely. Note that the viaroute service
does not calculate alternative routes by default, so you should take care if you enable it to the
query. If you do response times will be very slow.
./osrm-extract data.osm.pbf -p profile.lua --generate-edge-lookup
# about x8 speedup wrt to --core 1.0
./osrm-contract data.osrm --segment-speed-file updates.csv --core 0.8
# modify updates.csv
./osrm-contract data.osrm --segment-speed-file updates.csv --core 0.8
# Repeat in loop for desired update time
A level cache should always be generated with a full hierarchy (core=1.0). After this initial
generation, any core factor can be specified.
Alternatively, you can use the MLD routing algorithm - this calculates routes more slowly than
CH, but traffic imports are significantly faster:
# Run the following in a loop as you replace updates.csv with new data
./osrm-customize data.osrm --segment-speed-file updates.csv
138334372,15739272,138334381,0.13,11.1
15337331,13035445,138214289,1.27,22.2
137304004,15903737,15903725,0.73
138708033,13294070,134814059,-0.07
Every line should be a penalty, an empty line will result in an turn penalty file malformed error
The value of turn durations and weights must be in range [-3276.8, 3276.7] and [-
32768/10^{weight_precision}, 32767/10^{weight_precision}] respectively.
3 4 56 66 6 7
3 4 4 56 20 3
5 6 5 3 14 1
Data available immediately in this format includes, for example, ArcInfo ASCII grids of SRTM
data. These files also include six lines of metadata, which are necessary for loading a source file;
for example:
ncols 6001
nrows 6001
xllcorner -125.00041606132
yllcorner 34.999583357538
cellsize 0.00083333333333333
NODATA_value -9999
function source_function ()
mysource = sources:load(
"../path/to/raster_source.asc",
0, -- longitude min
0.1, -- longitude max
0, -- latitude min
0.1, -- latitude max
5, -- number of rows
4 -- number of cols
)
end
• sources is a single instance of a SourceContainer class that is bound to this lua state.
load is a binding to SourceContainer::loadRasterSource.
• mysource is an int ID that is saved to the global scope of this lua state, meaning it will be
available for use in other functions later. If you are loading multiple sources, you can
assign them to multiple variables.
mysource is now available for use in a segment_function, a separate function to write into the
profile. Its function signature is segment_function(segment) where segment has fields:
• source and target both have lat,lon properties (premultiplied by
COORDINATE_PRECISION)
• It is advisable, then, to either hardcode or read from environment the lat and lon
min/max in the source_function — the latter can be done like
LON_MIN=tonumber(os.getenv("LON_MIN"))
— and then multiplying all of them by the precision constant, bound to the lua
state as constants.precision, before exiting the scope of source_function
• distance is a const double in meters
• weight is a segment weight in properties.weight_name units
• duration is a segment duration in seconds
In a segment_function you can query loaded raster sources using a nearest-neighbor query or a
bilinear interpolation query, which have signatures like
-- nearest neighbor:
local sourceData = sources:query(mysource, segment.source.lon, segment.source.lat)
-- bilinear interpolation:
local sourceData = sources:interpolate(mysource, segment.target.lon, segment.target.lat)
where the signatures both look like (unsigned int source_id, int lon, int lat). They both
return an instance of RasterDatum with a member std::int32_t datum. Out-of-bounds
queries return a specific int std::numeric_limits<std::int32_t>::max(), which is bound
as a member function to the lua state as invalid_data(). So you could use this to find whether
a query was out of bounds:
…though it is faster to compare source and target to the raster bounds before querying the
source.
The complete additions of both functions then might look like so (since [OSRM version 5.6.0]
the parameters of segment_function () changed):
api_version = 1
properties.force_split_edges = true
local LON_MIN=tonumber(os.getenv("LON_MIN"))
local LON_MAX=tonumber(os.getenv("LON_MAX"))
local LAT_MIN=tonumber(os.getenv("LAT_MIN"))
local LAT_MAX=tonumber(os.getenv("LAT_MAX"))
function source_function()
raster_source = sources:load(
os.getenv("RASTER_SOURCE_PATH"),
LON_MIN,
LON_MAX,
LAT_MIN,
LAT_MAX,
tonumber(os.getenv("NROWS")),
tonumber(os.getenv("NCOLS")))
LON_MIN = LON_MIN * constants.precision
LON_MAX = LON_MAX * constants.precision
LAT_MIN = LAT_MIN * constants.precision
LAT_MAX = LAT_MAX * constants.precision
end
local slope = 0
local penalize = 0
-- these types of heuristics are fairly arbitrary and take some trial and error
if slope > 0.08 then
penalize = 0.6
end
if slope ~= 0 then
segment.weight = segment.weight * (1 - penalize)
-- a very rought estimate of duration of the edge so that the time estimate is more
accurate
segment.duration = segment.duration * (1+slope)
end
end
end
Default behavior during the extraction stage is to merge forward and backward edges into one
edge if travel modes, speeds and rates are equal. If the profile modifies in segment_function
forward and backward weights or durations independently then the global properties flag
force_split_edges must be set to true. Otherwise segment_function will be called only
once for a segment that corresponds to the forward edge.
7 OSRM profiles
OSRM supports "profiles". Profiles representing routing behavior for different transport modes
like car, bike and foot. You can also create profiles for variations like a fastest/shortest car profile
or fastest/safest/greenest bicycles profile.
A profile describes whether or not it's possible to route along a particular type of way, whether
we can pass a particular node, and how quickly we'll be traveling when we do. This feeds into the
way the routing graph is created and thus influences the output routes.
7.6 Elements
7.6.1 api_version
A profile should set api_version at the top of your profile. This is done to ensure that older
profiles are still supported when the api changes. If api_version is not defined, 0 will be
assumed. The current api version is 4.
7.6.3 setup()
The setup function is called once when the profile is loaded and must return a table of
configurations. It's also where you can do other global setup, like loading data sources that are
used during processing.
Note that processing of data is parallelized and several unconnected LUA interpreters will be
running at the same time. The setup function will be called once for each. Each LUA
iinterpreter will have its own set of globals.
The following global properties can be set under properties in the hash you return in the
setup function:
Attribute Type Notes
weight_name String Name used in output for the routing weight property (default 'duration')
weight_precision Unsigned Decimal precision of edge weights (default 1)
left_hand_driving Boolean Are vehicles assumed to drive on the left? (used in guidance, default false)
use_turn_restrictions Boolean Are turn instructions followed? (default false)
continue_straight_at Must the route continue straight on at a via point, or are U-turns allowed?
Boolean
_waypoint (default true)
max_speed_for_map
Float Maximum vehicle speed to be assumed in matching (in m/s)
_matching
max_turn_weight Float Maximum turn penalty weight
True value forces a split of forward and backward edges of extracted ways and
force_split_edges Boolean
guarantees that process_segment will be called for all segments (default false)
The following additional global properties can be set in the hash you return in the setup
function:
Attribute Type Notes
Determines which class-combinations are supported by the exclude option at query
Sequence of
excludable time. E.g. Sequence{Set{"ferry", "motorway"}, Set{"motorway"}} will allow
Sets
you to exclude ferries and motorways, or only motorways.
Determines the allowed classes that can be referenced using
classes Sequence
{forward,backward}_classes on the way in the process_way function.
restrictions Sequence Determines which turn restrictions will be used for this profile.
List of name suffixes needed for determining if "Highway 101 NW" the same road as
suffix_list Set
"Highway 101 ES".
relation_typ Determines wich relations should be cached for processing in this profile. It contains
Sequence
es relations types
c e
| /
| /
a ---- x ---- b
/|
/ |
f d
When setting appropriate turn weights and duration, information about the highway and access
tags of roads that are involved in the turn are necessary. The lua turn function process_turn
does not have access to the original osrm tags anymore. However,
highway_turn_classification and access_turn_classification can be set during setup.
The classification set during setup can be later used in process_turn.
Example
In the following example we use highway_turn_classification to set the turn weight to 10 if
the turn is on a highway and to 5 if the turn is on a primary.
function setup()
return {
highway_turn_classification = {
['motorway'] = 2,
['primary'] = 1
}
}
end
7.7 Guidance
The guidance parameters in profiles are currently a work in progress. They can and will change.
Please be aware of this when using guidance configuration possibilities.
Guidance uses road classes to decide on when/if to emit specific instructions and to discover
which road is obvious when following a route. Classification uses three flags and a priority-
category. The flags indicate whether a road is a motorway (required for on/off ramps), a link type
(the ramps itself, if also a motorway) and whether a road may be omitted in considerations (is
considered purely for connectivity). The priority-category influences the decision which road is
considered the obvious choice and which roads can be seen as fork. Forks can be emitted
between roads of similar priority category only. Obvious choices follow a major priority road, if
the priority difference is large.
function setup()
return {
raster_source = raster:load(
"rastersource.asc", -- file to load
0, -- longitude min
0.1, -- longitude max
0, -- latitude min
0.1, -- latitude max
5, -- number of rows
4 -- number of columns
)
}
end
The input data must an ASCII file with rows of integers. e.g.:
0 0 0 0
0 0 0 250
0 0 250 500
0 0 0 250
0 0 0 0
In your segment_function you can then access the raster source and use raster:query() to
query to find the nearest data point, or raster:interpolate() to interpolate a value based on
nearby data points.
You must check whether the result is valid before use it.
Example:
8.1.1 Requests
GET /{service}/{version}/{profile}/{coordinates}[.{format}]?option=value&option=value
Parameter Description
service One of the following values: route, nearest, table, match, trip, tile
version Version of the protocol implemented by the service. v1 for all OSRM 5.x installations
Mode of transportation, is determined statically by the Lua profile that is used to prepare the
profile
data using osrm-extract. Typically car, bike or foot if using one of the supplied profiles.
String of format {longitude},{latitude};{longitude},{latitude}[;{longitude},
coordinates
{latitude} ...] or polyline({polyline}) or polyline6({polyline6}).
format Only json is supported at the moment. This parameter is optional and defaults to json.
Passing any option=value is optional. polyline follows Google's polyline format with
precision 5 by default and can be generated using this package.
To pass parameters to each location some options support an array like encoding:
Request options
Option Values Description
{bearing};{bearing}[; Limits the search to segments with given bearing in degrees
bearings
{bearing} ...] towards true north in clockwise direction.
{radius};{radius}[;
radiuses Limits the search to given radius in meters.
{radius} ...]
Adds a Hint to the response which can be used in subsequent
generate_hints true (default), false
requests, see hints parameter.
{hint};{hint}[; Hint from previous request to derive position in street
hints
{hint} ...] network.
{approach};{approach}[;
approaches Keep waypoints on curb side.
{approach} ...]
exclude {class}[,{class}] Additive list of classes to avoid, order does not matter.
Default snapping avoids is_startpoint (see profile) edges, any
snapping default (default), any
will snap to any edge in the graph
Where the elements follow the following format:
Element Values
bearing {value},{range} integer 0 .. 360,integer 0 .. 180
radius double >= 0 or unlimited (default)
hint Base64 string
approach curb or unrestricted (default)
class A class name determined by the profile or none.
{option}={element};{element}[;{element} ... ]
The number of elements must match exactly the number of locations (except for
generate_hints and exclude). If you don't want to pass a value but instead use the default you
can pass an empty element.
Example: 2nd location use the default value for option:
{option}={element};;{element}
# Using polyline:
curl 'http://router.project-osrm.org/route/v1/driving/polyline(ofp_Ik_vpAilAyu@te@g`E)?
overview=false'
8.1.2 Responses
8.1.2.1 Code
Every response object has a code property containing one of the strings below or a service
dependent code:
Type Description
Ok Request could be processed as expected.
InvalidUrl URL string is invalid.
InvalidService Service name is invalid.
Type Description
InvalidVersion Version is not found.
InvalidOptions Options are invalid.
InvalidQuery The query string is synctactically malformed.
InvalidValue The successfully parsed query parameters are invalid.
NoSegment One of the supplied input coordinates could not snap to street segment.
TooBig The request size violates one of the service specific request size restrictions.
• message is a optional human-readable error message. All other status types are service
dependent.
• In case of an error the HTTP status code will be 400. Otherwise the HTTP status code
will be 200 and code will be Ok.
Every response object has a data_version propetry containing timestamp from the original
OpenStreetMap file. This field is optional. It can be ommited if data_version parametr was not
set on osrm-extract stage or OSM file has not osmosis_replication_timestamp section.
{
"code": "Ok",
"message": "Everything worked",
"data_version": "2017-11-17T21:43:02Z"
}
8.2 Services
8.2.1 Nearest service
Snaps a coordinate to the street network and returns the nearest n matches.
GET http://{server}/nearest/v1/{profile}/{coordinates}.json?number={number}
# Querying nearest three snapped locations of `13.388860,52.517037` with a bearing between `20° -
340°`.
curl 'http://router.project-osrm.org/nearest/v1/driving/13.388860,52.517037?
number=3&bearings=0,20'
{
"waypoints" : [
{
"nodes": [
2264199819,
0
],
"hint" :
"KSoKADRYroqUBAEAEAAAABkAAAAGAAAAAAAAABhnCQCLtwAA_0vMAKlYIQM8TMwArVghAwEAAQH1a66g",
"distance" : 4.152629,
"name" : "Friedrichstraße",
"location" : [
13.388799,
52.517033
]
},
{
"nodes": [
2045820592,
0
],
"hint" :
"KSoKADRYroqUBAEABgAAAAAAAAAAAAAAKQAAABhnCQCLtwAA7kvMAAxZIQM8TMwArVghAwAAAQH1a66g",
"distance" : 11.811961,
"name" : "Friedrichstraße",
"location" : [
13.388782,
52.517132
]
},
{
"nodes": [
0,
21487242
],
"hint" :
"KioKgDbbDgCUBAEAAAAAABoAAAAAAAAAPAAAABlnCQCLtwAA50vMADJZIQM8TMwArVghAwAAAQH1a66g",
"distance" : 15.872438,
"name" : "Friedrichstraße",
"location" : [
13.388775,
52.51717
],
}
],
"code" : "Ok"
}
GET /route/v1/{profile}/{coordinates}?alternatives={true|false|number}&steps={true|
false}&geometries={polyline|polyline6|geojson}&overview={full|simplified|
false}&annotations={true|false}
In addition to the general options the following options are supported for this service:
Option Values Description
Search for alternative routes. Passing a number
alternatives true, false (default), or Number
alternatives=n searches for up to n alternative routes.*
steps true, false (default) Returned route steps for each route leg
true, false (default), nodes,
Returns additional metadata for each coordinate along the
annotations distance, duration, datasources,
route geometry.
weight, speed
polyline (default), polyline6, Returned route geometry format (influences overview
geometries
geojson and per step)
Add overview geometry either full, simplified according
overview simplified (default), full, false
to highest zoom level it could be display on, or not at all.
Forces the route to keep going straight at waypoints
continue_straig
default (default), true, false constraining uturns there even if it would be faster.
ht
Default value depends on the profile.
Treats input coordinates indicated by given indices as
waypoints {index};{index};{index}... waypoints in returned Match object. Default is to treat all
input coordinates as waypoints.
* Please note that even if alternative routes are requested, a result cannot be guaranteed.
Response
• code if the request was successful Ok otherwise see the service dependent and general
status codes.
• waypoints: Array of Waypoint objects representing all waypoints in order:
• routes: An array of Route objects, ordered by descending recommendation rank.
In case of error the following codes are supported in addition to the general ones:
Type Description
NoRoute No route found.
All other properties might be undefined.
GET /table/v1/{profile}/{coordinates}?
{sources}=[{elem}...];&{destinations}=[{elem}...]&annotations={duration|distance|
duration,distance}
Options
In addition to the general options the following options are supported for this service:
Option Values Description
{index};{index}[;{index}
sources Use location with given index as source.
...] or all (default)
{index};{index}[;{index}
destinations Use location with given index as destination.
...] or all (default)
duration (default),
annotations distance, or Return the requested table or tables in response.
duration,distance
If no route found between a source/destination pair, calculate
fallback_speed double > 0 the as-the-crow-flies distance, then use this speed to estimate
duration.
When using a fallback_speed, use the user-supplied
fallback_coordin
input (default), or snapped coordinate (input), or the snapped location (snapped) for
ate
calculating distances.
Option Values Description
Use in conjunction with annotations=durations. Scales the
scale_factor double > 0
table duration values by this number.
Unlike other array encoded options, the length of sources and destinations can be smaller
or equal to number of input locations;
Example:
sources=0;5;7&destinations=5;1;4;2;3;6
Element Values
index 0 <= integer < #locations
8.2.3.1 Example Request
# Returns a asymmetric 3x2 duration matrix with from the polyline encoded locations
`qikdcB}~dpXkkHz`:
curl
'http://router.project-osrm.org/table/v1/driving/polyline(egs_Iq_aqAppHzbHulFzeMe`EuvKpnCglA)?
sources=0;1;3&destinations=2;4'
# Returns a 3x3 duration matrix and a 3x3 distance matrix for CH:
curl
'http://router.project-osrm.org/table/v1/driving/13.388860,52.517037;13.397634,52.529407;13.42855
5,52.523219?annotations=distance,duration'
Response
• code if the request was successful Ok otherwise see the service dependent and general
status codes.
• durations array of arrays that stores the matrix in row-major order. durations[i][j]
gives the travel time from the i-th waypoint to the j-th waypoint. Values are given in
seconds. Can be null if no route between i and j can be found.
• distances array of arrays that stores the matrix in row-major order. distances[i][j]
gives the travel distance from the i-th waypoint to the j-th waypoint. Values are given in
meters. Can be null if no route between i and j can be found.
• sources array of Waypoint objects describing all sources in order
• destinations array of Waypoint objects describing all destinations in order
• fallback_speed_cells (optional) array of arrays containing i,j pairs indicating which
cells contain estimated values based on fallback_speed. Will be absent if
fallback_speed is not used.
In case of error the following codes are supported in addition to the general ones:
Type Description
NoTable No route found.
NotImplemented This request is not supported
All other properties might be undefined.
{
"sources": [
{
"location": [
13.3888,
52.517033
],
"hint":
"PAMAgEVJAoAUAAAAIAAAAAcAAAAAAAAArss0Qa7LNEHiVIRA4lSEQAoAAAAQAAAABAAAAAAAAADMAAAAAEzMAKlYIQM8TMwA
rVghAwEA3wps52D3",
"name": "Friedrichstraße"
},
{
"location": [
13.397631,
52.529432
],
"hint":
"WIQBgL6mAoAEAAAABgAAAAAAAAA7AAAAhU6PQHvHj0IAAAAAQbyYQgQAAAAGAAAAAAAAADsAAADMAAAAf27MABiJIQOCbswA
_4ghAwAAXwVs52D3",
"name": "Torstraße"
},
{
"location": [
13.428554,
52.523239
],
"hint":
"7UcAgP___38fAAAAUQAAACYAAABTAAAAhSQKQrXq5kKRbiZCWJo_Qx8AAABRAAAAJgAAAFMAAADMAAAASufMAOdwIQNL58wA
03AhAwMAvxBs52D3",
"name": "Platz der Vereinten Nationen"
}
],
"durations": [
[
0,
192.6,
382.8
],
[
199,
0,
283.9
],
[
344.7,
222.3,
0
]
],
"destinations": [
{
"location": [
13.3888,
52.517033
],
"hint":
"PAMAgEVJAoAUAAAAIAAAAAcAAAAAAAAArss0Qa7LNEHiVIRA4lSEQAoAAAAQAAAABAAAAAAAAADMAAAAAEzMAKlYIQM8TMwA
rVghAwEA3wps52D3",
"name": "Friedrichstraße"
},
{
"location": [
13.397631,
52.529432
],
"hint":
"WIQBgL6mAoAEAAAABgAAAAAAAAA7AAAAhU6PQHvHj0IAAAAAQbyYQgQAAAAGAAAAAAAAADsAAADMAAAAf27MABiJIQOCbswA
_4ghAwAAXwVs52D3",
"name": "Torstraße"
},
{
"location": [
13.428554,
52.523239
],
"hint":
"7UcAgP___38fAAAAUQAAACYAAABTAAAAhSQKQrXq5kKRbiZCWJo_Qx8AAABRAAAAJgAAAFMAAADMAAAASufMAOdwIQNL58wA
03AhAwMAvxBs52D3",
"name": "Platz der Vereinten Nationen"
}
],
"code": "Ok",
"distances": [
[
0,
1886.89,
3791.3
],
[
1824,
0,
2838.09
],
[
3275.36,
2361.73,
0
]
],
"fallback_speed_cells": [
[ 0, 1 ],
[ 1, 0 ]
]
}
GET /match/v1/{profile}/{coordinates}?steps={true|false}&geometries={polyline|polyline6|
geojson}&overview={simplified|full|false}&annotations={true|false}
In addition to the general options the following options are supported for this service:
Option Values Description
steps true, false (default) Returned route steps for each route
polyline (default), polyline6, Returned route geometry format (influences overview
geometries
geojson and per step)
true, false (default), nodes,
Returns additional metadata for each coordinate along
annotations distance, duration, datasources,
the route geometry.
weight, speed
Add overview geometry either full, simplified according
overview simplified (default), full, false
to highest zoom level it could be display on, or not at all.
Timestamps for the input locations in seconds since
{timestamp};{timestamp}[;
timestamps UNIX epoch. Timestamps need to be monotonically
{timestamp} ...]
increasing.
Option Values Description
Standard deviation of GPS precision used for map
radiuses {radius};{radius}[;{radius} ...]
matching. If applicable use GPS accuracy.
Allows the input track splitting based on huge timestamp
gaps split (default), ignore
gaps between points.
Allows the input track modification to obtain better
tidy true, false (default)
matching quality for noisy tracks.
Treats input coordinates indicated by given indices as
waypoints {index};{index};{index}... waypoints in returned Match object. Default is to treat all
input coordinates as waypoints.
Parameter Values
timestamp integer seconds since UNIX epoch
radius double >= 0 (default 5m)
The radius for each point should be the standard error of the location measured in meters from
the true location. Use Location.getAccuracy() on Android or
CLLocation.horizontalAccuracy on iOS. This value is used to determine which points
should be considered as candidates (larger radius means more candidates) and how likely each
candidate is (larger radius means far-away candidates are penalized less). The area to search is
chosen such that the correct candidate should be considered 99.9% of the time (for more details
see this ticket).
Response
• code if the request was successful Ok otherwise see the service dependent and general
status codes.
• tracepoints: Array of Waypoint objects representing all points of the trace in order. If
the trace point was ommited by map matching because it is an outlier, the entry will be
null. Each Waypoint object has the following additional properties:
• matchings_index: Index to the Route object in matchings the sub-trace was
matched to.
• waypoint_index: Index of the waypoint inside the matched route.
• alternatives_count: Number of probable alternative matchings for this trace
point. A value of zero indicate that this point was matched unambiguously. Split
the trace at these points for incremental map matching.
• matchings: An array of Route objects that assemble the trace. Each Route object has the
following additional properties:
• confidence: Confidence of the matching. float value between 0 and 1. 1 is very
confident that the matching is correct.
In case of error the following codes are supported in addition to the general ones:
Type Description
NoMatch No matchings found.
All other properties might be undefined.
GET /trip/v1/{profile}/{coordinates}?roundtrip={true|false}&source{any|first}&destination{any|
last}&steps={true|false}&geometries={polyline|polyline6|geojson}&overview={simplified|full|
false}&annotations={true|false}'
In addition to the general options the following options are supported for this service:
Option Values Description
Returned route is a roundtrip (route returns to first
roundtrip true (default), false
location)
source any (default), first Returned route starts at any or first coordinate
destination any (default), last Returned route ends at any or last coordinate
steps true, false (default) Returned route instructions for each trip
true, false (default), nodes, distance, Returns additional metadata for each coordinate
annotations
duration, datasources, weight, speed along the route geometry.
Returned route geometry format (influences
geometries polyline (default), polyline6, geojson
overview and per step)
Add overview geometry either full, simplified
overview simplified (default), full, false according to highest zoom level it could be display
on, or not at all.
Fixing Start and End Points
It is possible to explicitely set the start or end coordinate of the trip. When source is set to first,
the first coordinate is used as start coordinate of the trip in the output. When destination is set to
last, the last coordinate will be used as destination of the trip in the returned output. If you
specify any, any of the coordinates can be used as the first or last coordinate in the output.
However, if source=any&destination=any the returned round-trip will still start at the first
input coordinate by default.
Currently, not all combinations of roundtrip, source and destination are supported. Right
now, the following combinations are possible:
roundtrip source destination supported
true first last yes
true first any yes
true any last yes
true any any yes
false first last yes
false first any no
false any last no
false any any no
8.2.5.1 Example Requests
# Round trip in Berlin with four stops, starting at the first stop, ending at the last:
curl
'http://router.project-osrm.org/trip/v1/driving/13.388860,52.517037;13.397634,52.529407;13.428555
,52.523219;13.418555,52.523215?source=first&destination=last'
8.2.5.2 Response
• code: if the request was successful Ok otherwise see the service dependent and general
status codes.
• waypoints: Array of Waypoint objects representing all waypoints in input order. Each
Waypoint object has the following additional properties:
• trips_index: Index to trips of the sub-trip the point was matched to.
• waypoint_index: Index of the point in the trip.
• trips: An array of Route objects that assemble the trace.
In case of error the following codes are supported in addition to the general ones:
Type Description
NoTrips No trips found because input coordinates are not connected.
NotImplemented This request is not supported
All other properties might be undefined.
8.2.6 Tile service
This service generates Mapbox Vector Tiles that can be viewed with a vector-tile capable slippy-
map viewer. The tiles contain road geometries and metadata that can be used to examine the
routing graph. The tiles are generated directly from the data in-memory, so are in sync with
actual routing results, and let you examine which roads are actually routable, and what weights
they have applied.
GET /tile/v1/{profile}/tile({x},{y},{zoom}).mvt
http://map.project-osrm.org/debug/#14.33/52.5212/13.3919
The response object is either a binary encoded blob with a Content-Type of application/x-
protobuf, or a 404 error. Note that OSRM is hard-coded to only return tiles from zoom level 12
and higher (to avoid accidentally returning extremely large vector tiles).
Vector tiles contain two layers:
speeds layer:
Property Type Description
speed integer the speed on that road segment, in km/h
whether this segment belongs to a small (< 1000 node) strongly connected
is_small boolean
component
the source for the speed value (normally lua profile unless you're using the
datasource string traffic update feature, in which case it contains the stem of the filename that
supplied the speed value for this segment
how long this segment takes to traverse, in seconds. This value is to calculate the
duration float
total route ETA.
how long this segment takes to traverse, in units (may differ from duration when
weight integer artificial biasing is applied in the Lua profiles). ACTUAL ROUTING USES THIS
VALUE.
name string the name of the road this segment belongs to
the value of length/weight - analagous to speed, but using the weight value
rate float
rather than duration, rounded to the nearest integer
is_startpoint boolean whether this segment can be used as a start/endpoint for routes
turns layer:
Property Type Description
the absolute bearing that approaches the intersection. -180 to +180, 0 = North, 90 =
bearing_in integer
East
the angle of the turn, relative to the bearing_in. -180 to +180, 0 = straight ahead, 90
turn_angle integer
= 90-degrees to the right
the time we think it takes to make that turn, in seconds. May be negative, depending on
cost float
how the data model is constructed (some turns get a "bonus").
the weight we think it takes to make that turn. May be negative, depending on how the
weight float data model is constructed (some turns get a "bonus"). ACTUAL ROUTING USES
THIS VALUE
the type of this turn - values like turn, continue, etc. See the StepManeuver for a
type string partial list, this field also exposes internal turn types that are never returned with an API
response
modifier string the direction modifier of the turn (left, sharp left, etc)
8.3 Result objects
8.3.1 Route object
Represents a route through (potentially multiple) waypoints.
Properties
• distance: The distance traveled by the route, in float meters.
• duration: The estimated travel time, in float number of seconds.
• geometry: The whole geometry of the route value depending on overview parameter,
format depending on the geometries parameter. See RouteStep's geometry property for
a parameter documentation.
• weight: The calculated weight of the route.
• weight_name: The name of the weight profile used during extraction phase.
overview Description
simplified Geometry is simplified according to the highest zoom level it can still be displayed on full.
full Geometry is not simplified.
false Geometry is not added.
• legs: The legs between the given waypoints, an array of RouteLeg objects.
8.3.1.1 Example
{
"distance": 90.0,
"duration": 300.0,
"weight": 300.0,
"weight_name": "duration",
"geometry": {"type": "LineString", "coordinates": [[120.0, 10.0], [120.1, 10.0], [120.2, 10.0],
[120.3, 10.0]]},
"legs": [
{
"distance": 30.0,
"duration": 100.0,
"steps": []
},
{
"distance": 60.0,
"duration": 200.0,
"steps": []
}
]
}
8.3.2 RouteLeg object
Represents a route between two waypoints.
Properties
• distance: The distance traveled by this route leg, in float meters.
• duration: The estimated travel time, in float number of seconds.
• weight: The calculated weight of the route leg.
• summary: Summary of the route taken as string. Depends on the summary parameter:
summary
true Names of the two major roads used. Can be empty if route is too short.
false empty string
• steps: Depends on the steps parameter.
steps
true array of RouteStep objects describing the turn-by-turn instructions
false empty array
• annotation: Additional details about each coordinate along the route geometry:
annotations
true An Annotation object containing node ids, durations, distances and weights.
false undefined
8.3.2.1 Example
{
"distance": 30.0,
"duration": 100.0,
"weight": 100.0,
"steps": [],
"annotation": {
"distance": [5,5,10,5,5],
"duration": [15,15,40,15,15],
"datasources": [1,0,0,0,1],
"metadata": { "datasource_names": ["traffic","lua profile","lua profile","lua
profile","traffic"] },
"nodes": [49772551,49772552,49786799,49786800,49786801,49786802],
"speed": [0.3, 0.3, 0.3, 0.3, 0.3]
}
}
8.3.3.1 Example
{
"distance": [5,5,10,5,5],
"duration": [15,15,40,15,15],
"datasources": [1,0,0,0,1],
"metadata": { "datasource_names": ["traffic","lua profile","lua profile","lua
profile","traffic"] },
"nodes": [49772551,49772552,49786799,49786800,49786801,49786802],
"weight": [15,15,40,15,15]
}
8.3.4.1 Example
{
"geometry" : "{lu_IypwpAVrAvAdI",
"mode" : "driving",
"duration" : 15.6,
"weight" : 15.6,
"intersections" : [
{ "bearings" : [ 10, 92, 184, 270 ],
"lanes" : [
{ "indications" : [ "left", "straight" ],
"valid" : "false" },
{ "valid" : "true",
"indications" : [ "right" ] }
],
"out" : 2,
"in" : 3,
"entry" : [ "true", "true", "true", "false" ],
"location" : [ 13.39677, 52.54366 ]
},
{ "out" : 1,
"lanes" : [
{ "indications" : [ "straight" ],
"valid" : "true" },
{ "indications" : [ "right" ],
"valid" : "false" }
],
"bearings" : [ 60, 240, 330 ],
"in" : 0,
"entry" : [ "false", "true", "true" ],
"location" : [ 13.394718, 52.543096 ]
}
],
"name" : "Lortzingstraße",
"distance" : 152.3,
"maneuver" : {
"modifier" : "right",
"type" : "turn"
}
}
8.3.6.1 Example
{
"indications": ["left", "straight"],
"valid": "false"
}
8.3.7.1 Example
{
"location":[13.394718,52.543096],
"in":0,
"out":2,
"bearings":[60,150,240,330],
"entry":["false","true","true","true"],
"classes": ["toll", "restricted"],
"lanes":{
"indications": ["left", "straight"],
"valid": "false"
}
}
8.3.8.1 Example
{
"hint" : "KSoKADRYroqUBAEAEAAAABkAAAAGAAAAAAAAABhnCQCLtwAA_0vMAKlYIQM8TMwArVghAwEAAQH1a66g",
"distance" : 4.152629,
"name" : "Friedrichstraße",
"location" : [
13.388799,
52.517033
]
}
9 Node OSRM Library
The OSRM method is the main constructor for creating an OSRM instance. An OSRM instance
requires a .osrm network, which is prepared by the OSRM Backend C++ library.
You can create such a .osrm file by running the OSRM binaries we ship in
node_modules/osrm/lib/binding/ and default profiles (e.g. for setting speeds and
determining road types to route on) in node_modules/osrm/profiles/:
9.1 Methods
Service Description
osrm.route shortest path between given coordinates
osrm.nearest returns the nearest street segment for a given coordinate
osrm.table computes distance tables for given coordinates
osrm.match matches given coordinates to the road network
osrm.trip Compute the shortest trip between given coordinates
osrm.tile Return vector tiles containing debugging info
9.3 route
Returns the fastest route between two or more coordinates while visiting the waypoints in order.
9.3.1 Parameters
• options Object Object literal containing parameters for the route query.
• options.alternatives [Boolean] Search for alternative routes and return as well.
Please note that even if an alternative route is requested, a result cannot be guaranteed.
(optional, default false)
• options.steps [Boolean] Return route steps for each route leg. (optional, default
false)
• options.annotations [Boolean] or [Array<String>] Return annotations for each
route leg for duration, nodes, distance, weight, datasources and/or speed.
Annotations can be false or true (no/full annotations) or an array of strings with
duration, nodes, distance, weight, datasources, speed. (optional, default
false)
• options.geometries [String] Returned route geometry format (influences
overview and per step). Can also be geojson. (optional, default polyline)
• options.overview [String] Add overview geometry either full, simplified
according to highest zoom level it could be display on, or not at all (false).
(optional, default simplified)
• options.continue_straight [Boolean] Forces the route to keep going straight at
waypoints and don't do a uturn even if it would be faster. Default value depends
on the profile. null/true/false
• callback Function
9.3.2 Examples
var osrm = new OSRM("berlin-latest.osrm");
osrm.route({coordinates: [[13.438640,52.519930], [13.415852, 52.513191]]}, function(err, result)
{
if(err) throw err;
console.log(result.waypoints); // array of Waypoint objects representing all waypoints in order
console.log(result.routes); // array of Route objects ordered by descending recommendation rank
});
Returns Object An array of Waypoint objects representing all waypoints in order AND an array of
Route objects ordered by descending recommendation rank.
9.4 nearest
Snaps a coordinate to the street network and returns the nearest n matches.
Note: coordinates in the general options only supports a single {longitude},{latitude}
entry.
9.4.1 Parameters
• options Object Object literal containing parameters for the nearest query.
• options.number [Number] Number of nearest segments that should be returned.
Must be an integer greater than or equal to 1. (optional, default 1)
• callback Function
9.4.2 Examples
var osrm = new OSRM('network.osrm');
var options = {
coordinates: [[13.388860,52.517037]],
number: 3,
bearings: [[0,20]]
};
osrm.nearest(options, function(err, response) {
console.log(response.waypoints); // array of Waypoint objects
});
Returns Object containing waypoints. waypoints: array of Ẁaypoint objects sorted by distance
to the input coordinate. Each object has an additional distance property, which is the distance
in meters to the supplied input coordinate.
9.5 table
Computes duration tables for the given locations. Allows for both symmetric and asymmetric
tables.
9.5.1 Parameters
• options Object Object literal containing parameters for the table query.
• options.sources [Array] An array of index elements (0 <= integer <
#coordinates) to use location with given index as source. Default is to use all.
• options.destinations [Array] An array of index elements (0 <= integer <
#coordinates) to use location with given index as destination. Default is to use
all.
• callback Function
9.5.2 Examples
var osrm = new OSRM('network.osrm');
var options = {
coordinates: [
[13.388860,52.517037],
[13.397634,52.529407],
[13.428555,52.523219]
]
};
osrm.table(options, function(err, response) {
console.log(response.durations); // array of arrays, matrix in row-major order
console.log(response.sources); // array of Waypoint objects
console.log(response.destinations); // array of Waypoint objects
});
Returns Object containing durations, sources, and destinations. durations: array of arrays
that stores the matrix in row-major order. durations[i][j] gives the travel time from the i-th
waypoint to the j-th waypoint. Values are given in seconds. sources: array of Ẁaypoint objects
describing all sources in order. destinations: array of Ẁaypoint objects describing all
destinations in order.
9.6 tile
This generates Mapbox Vector Tiles that can be viewed with a vector-tile capable slippy-map
viewer. The tiles contain road geometries and metadata that can be used to examine the routing
graph. The tiles are generated directly from the data in-memory, so are in sync with actual
routing results, and let you examine which roads are actually routable, and what weights they
have applied.
9.6.1 Parameters
• ZXY Array an array consisting of x, y, and z values representing tile coordinates like
wiki.openstreetmap.org/wiki/Slippy_map_tilenames and are supported by vector tile viewers
like [Mapbox GL JS](https://www.mapbox.com/mapbox-gl-js/api/.
• callback Function
9.6.2 Examples
var osrm = new OSRM('network.osrm');
osrm.tile([0, 0, 0], function(err, response) {
if (err) throw err;
fs.writeFileSync('./tile.vector.pbf', response); // write the buffer to a file
});
9.7 match
Map matching matches given GPS points to the road network in the most plausible way. Please
note the request might result multiple sub-traces. Large jumps in the timestamps (>60s) or
improbable transitions lead to trace splits if a complete matching could not be found. The
algorithm might not be able to match all points. Outliers are removed if they can not be matched
successfully.
9.7.1 Parameters
• options Object Object literal containing parameters for the match query.
• options.steps [Boolean] Return route steps for each route. (optional, default
false)
• options.annotations [Boolean] or [Array<String>] Return annotations for each
route leg for duration, nodes, distance, weight, datasources and/or speed.
Annotations can be false or true (no/full annotations) or an array of strings with
duration, nodes, distance, weight, datasources, speed. (optional, default
false)
• options.geometries [String] Returned route geometry format (influences
overview and per step). Can also be geojson. (optional, default polyline)
• options.overview [String] Add overview geometry either full, simplified
according to highest zoom level it could be display on, or not at all (false).
(optional, default simplified)
• options.timestamps [Array<Number>] Timestamp of the input location
(integers, UNIX-like timestamp).
• options.radiuses [Array] Standard deviation of GPS precision used for map
matching. If applicable use GPS accuracy (double >= 0, default 5m).
• callback Function
9.7.2 Examples
var osrm = new OSRM('network.osrm');
var options = {
coordinates: [[13.393252,52.542648],[13.39478,52.543079],[13.397389,52.542107]],
timestamps: [1424684612, 1424684616, 1424684620]
};
osrm.match(options, function(err, response) {
if (err) throw err;
console.log(response.tracepoints); // array of Waypoint objects
console.log(response.matchings); // array of Route objects
});
9.8 trip
The trip plugin solves the Traveling Salesman Problem using a greedy heuristic (farthest-
insertion algorithm). The returned path does not have to be the fastest path, as TSP is NP-hard it
is only an approximation. Note that all input coordinates have to be connected for the trip
service to work.
9.8.1 Parameters
• options Object Object literal containing parameters for the trip query.
• options.roundtrip [Boolean] Return route is a roundtrip. (optional, default
true)
• options.source [String] Return route starts at any coordinate. Can also be first.
(optional, default any)
• options.destination [String] Return route ends at any coordinate. Can also be
last. (optional, default any)
• options.steps [Boolean] Return route steps for each route. (optional, default
false)
• options.annotations [Boolean] or [Array<String>] Return annotations for each
route leg for duration, nodes, distance, weight, datasources and/or speed.
Annotations can be false or true (no/full annotations) or an array of strings with
duration, nodes, distance, weight, datasources, speed. (optional, default
false)
• options.geometries [String] Returned route geometry format (influences
overview and per step). Can also be geojson. (optional, default polyline)
• options.overview [String] Add overview geometry either full, simplified
(optional, default simplified)
• callback Function
It is possible to explicitly set the start or end coordinate of the trip. When source is set to first,
the first coordinate is used as start coordinate of the trip in the output. When destination is set to
last, the last coordinate will be used as destination of the trip in the returned output. If you
specify any, any of the coordinates can be used as the first or last coordinate in the output.
However, if source=any&destination=any the returned round-trip will still start at the first
input coordinate by default.
Currently, not all combinations of roundtrip, source and destination are supported. Right
now, the following combinations are possible:
roundtrip source destination supported
true first last yes
true first any yes
true any last yes
true any any yes
false first last yes
roundtrip source destination supported
false first any no
false any last no
false any any no
9.8.2 Examples
9.8.2.1 Roundtrip Request
Returns Object containing waypoints and trips. waypoints: an array of Ẁaypoint objects
representing all waypoints in input order. Each Waypoint object has the following additional
properties, 1) trips_index: index to trips of the sub-trip the point was matched to, and 2)
waypoint_index: index of the point in the trip. trips: an array of Route objects that assemble
the trace.
9.9 Responses
Responses
9.10 Route
Represents a route through (potentially multiple) waypoints.
Parameters
• exteral documentation in osrm-backend
9.11 RouteLeg
Represents a route between two waypoints.
Parameters
• exteral documentation in osrm-backend
9.12 RouteStep
A step consists of a maneuver such as a turn or merge, followed by a distance of travel along a
single way to the subsequent step.
Parameters
• exteral documentation in osrm-backend
9.13 StepManeuver
Parameters
• exteral documentation in osrm-backend
9.14 Waypoint
Object used to describe waypoint on a route.
Parameters
• exteral documentation in osrm-backend
10 Graph representation
This page explains how OSRM converts OSM data to an edge-expanded graph, given that the
input data is correct.
In order to use Dijkstra's algorithm, we convert OSM into a graph. We use OSM tags to get
speeds, then calculate the duration (in seconds) of each edge, and add some penalties (in
seconds) for turns, based on their angle. Once the graph is set up with all the data, finding the
route between two points is mostly just a matter of selecting the nodes on the graph, then
running Dijkstra's algorithm to find the shortest duration path. Once we have the path, we
convert it back to a list of coordinates and turn instructions for spots where a turn was made.
We have lots of optimizations under the hood to make it really fast, but conceptually, it works
like any description of Dijkstra you will find.
10.1.1 Node
The geometric representation within OSRM is based on nodes. An OSM node is a 2D point
with latitude and longitude, i.e. a geo-coordinate.
10.1.2 Way
An OSM way connects a number of nodes. A way is thus a 2D poly-line, consisting of a number
of segments. Several ways can share the same node where they cross.
10.1.3 Relation
An OSM relation relates several nodes or ways, or both. It can be used for turn restrictions,
routes, and other things. A relation is often not a physical structure, but an abstraction like a bus
route for example.
The data consists of two way: abc and dce, meeting at node c.
First, all ways are split into individual segments: ab,bc,cd,ce. For each segment, two graph nodes
are created, one for each direction of the segment:
ab, ba
bc, cb
cd, dc
ce, ec
A graph edge is then created for every possible movement taking you from one graph node
(direction of a OSM segment) to another. If we allow all turns (including u-turns), in the map
above, we get these edges:
dc-cd
dc-cb
dc-ce
ab-ba
ab-bc
ba-ab
bc-cd
bc-cb
bc-ce
cd-dc
cb-ba
cb-bc
ce-ec
ec-cd
ec-cb
ec-ce
Edge have been written in the form "fromGraphNode-toGraphNode". Since we can only move
along connected paths, the second graph node always start where the first ends.
The list above includes all possible u-turns, including u-turns in the middle of a way. For
example ab-ba represents a u-turn at OSM node b of OSM way abc. OSRM removes such u-
turns, and we get:
OSRM will also remove turns that are prohibited by turn restrictions.