Sunteți pe pagina 1din 68

O.S.R.M.

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

To download from Git, run the following commands:

git clone https://github.com/Project-OSRM/osrm-backend.git


cd osrm-backend

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>.

1.1.1.2 Source Release

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

See below for required dependencies.

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)

1.1.3 Debian Jessie


Use the following command to install the dependencies (git is used to fetch the source):
sudo apt-get install git g++ cmake libboost-dev libboost-filesystem-dev libboost-thread-dev \
libboost-system-dev libboost-regex-dev libstxxl-dev libxml2-dev libsparsehash-dev libbz2-dev \
zlib1g-dev libzip-dev libgomp1 liblua5.1-0-dev \
pkg-config libgdal-dev libboost-program-options-dev libboost-iostreams-dev \
libboost-test-dev libtbb-dev libexpat1-dev

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.

1.1.4 Red Hat Enterprise Linux, Fedora, or CentOS


1.1.4.1 CentOS 7.x

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:

yum install yum-utils centos-release-scl


yum-config-manager --enable rhel-server-rhscl-7-rpms
yum install devtoolset-6

Start a new shell with the gcc-6 environment:

scl enable devtoolset-6 bash

A few other dependencies are needed:

yum install git cmake3 zlib-devel

For all other dependencies make use of mason so that Boost and so on don't have to be built
manually as well:

git clone https://github.com/Project-OSRM/osrm-backend.git


cd osrm-backend
mkdir build
cd build
cmake3 .. -DENABLE_MASON=ON -DCMAKE_CXX_COMPILER=/opt/rh/devtoolset-6/root/usr/bin/g++
make
make install
2 Running OSRM - How to run the tool chain
There are two pre-processing pipelines available:
• Contraction Hierarchies (CH) which best fits use-cases where query performance is key,
especially for large distance matrices
• Multi-Level Dijkstra (MLD) which best fits use-cases where query performance still needs
to be very good; and live-updates to the data need to be made e.g. for regular Traffic
updates
Our efforts are shifting towards the MLD pipeline with some features seeing MLD-specific
implementations (such as multiple alternative routes). We recommend using the MLD pipeline
except for special use-cases such as very large distance matrices where the CH pipeline is still
faster.

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

osrm-routed --algorithm=MLD 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-extract berlin-latest.osm.pbf -p profiles/car.lua


osrm-contract berlin-latest.osrm

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):

fallocate -l 100G /path/to/swapfile


chmod 600 /path/to/swapfile
mkswap /path/to/swapfile
swapon /path/to/swapfile

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

Check STXXL's config documentation.

2.3 Creating the Hierarchy (osrm-contract)


The so-called Hierarchy is precomputed data that enables the routing engine to find shortest
path within short time.

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.

2.4 Running the Engine via a HTTP Server (osrm-routed)


We provide a demo HTTP server on top of the libosrm library doing the heavy lifting. You can
start it via:

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"

2.5 Running multiple profiles on one machine


Below is an example nginx.conf configuration that shows how to configure an nginx as a
reverse proxy to send different requests to different osrm-routed instances:

server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;

# catch all v5 routes and send them to OSRM


location /route/v1/driving { proxy_pass http://localhost:5000; }
location /route/v1/walking { proxy_pass http://localhost:5001; }
location /route/v1/cycling { proxy_pass http://localhost:5002; }

# Everything else is a mistake and returns an error


location / {
add_header Content-Type text/plain;
return 404 'Your request is bad and you should feel bad.';
}
}

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.

4.1 System Limits


4.1.1.1 Linux

Append the following lines to /etc/sysctl.conf:

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

On Mac OS X, add the following to /etc/sysctl.conf:

kern.sysv.shmmax=1073741824
kern.sysv.shmall=262144
kern.sysv.shmseg=256

Then reboot.

------ Shared Memory Limits --------


max number of segments = 4096
max seg size (kbytes) = 18014398509481983
max total shared memory (kbytes) = 4611686018427386880
min seg size (bytes) = 1

4.2 User Limits


This is only half of the story. On Linux, only the super user is allowed to lock arbitrary amounts
of shared memory into RAM. To fix this, we need to set the user limits properly. Let's have a
look at what Ubuntu 12.10 sets by default:

$ ulimit -a|grep max


max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited

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.

<user> hard memlock unlimited


<user> soft memlock 68719476736

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:

session required pam_limits.so

4.3 Using Shared Memory


With all these changes done, you should now load all shared memory directly into RAM.
Loading data into shared memory is as easy as

$ ./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:

[warning] could not lock shared memory to RAM

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:

$ sudo setcap "cap_ipc_lock=ep" `which osrm-datastore`

$ sudo getcap `which osrm-datastore`


osrm-datastore = cap_ipc_lock+ep

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:

$ ./osrm-datastore --dataset-name=mydata /path/to/data.osrm


$ ./osrm-routed --dataset-name=mydata --shared-memory

4.4 Locking mechanism and cleaning locks


osrm-datastore and osrm-routed use IPC mechanism based on the Boost.Interprocess
library:
• boost::interprocess::named_mutex at /dev/shm/sem.osrm-region (Linux specific)
protects the current region data that contains the current region ID and the incremental
time stamp. Process osrm-routed acquires shared mutual access (read-only) and osrm-
datastore acquires exclusive mutual access (read-write) to the data.
• boost::interprocess::named_condition at /dev/shm/osrm-region-cv (Linux
specific) is a conditional variable sent by osrm-datastore to notify osrm-routed
processes about changed data.
• boost::interprocess::file_lock at /tmp/osrm-datastore.lock guarantees
mutual exclusive execution of osrm-datastore processes.
Use the following options with care
Because of asynchronous nature of signals there exists a small risk that osrm-routed can be
killed by the system while holding sem.osrm-region mutex. This will lead to osrm-datastore
process lock in during exclusive mutual access acquire. To unlock the shared mutex without full
system reboot, osrm-datastore has the following options:
• osrm-datastore --remove-locks — removes sem.osrm-region mutex and and
osrm-region-cv conditional variable
• osrm-datastore --spring-clean — marks shared memory blocks as removed and
removes locks
5 Traffic
OSRM has experimental support of traffic data, as of 4.9.0. This is achieved by providing osrm-
contract with an additional file that specifies edge weight updates. For convenience, updates
can be specified in a csv file; each line has to follow the format
from_osm_id,to_osm_id,edge_speed_in_km_h(,edge_rate?,(anything else)?)?. If the
edge_rate column is completely missing (i.e. the file only has 3 columns), then the edge speed
will be used to update edge weight (corresponds to the "duration" weight). If the edge_rate
column is supplied but the value is blank, then the existing weight on that edge will be kept, but
the duration will be updated. An example of a CSV file for traffic updates is:

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)?.

./osrm-extract data.osm.pbf -p profile.lua --generate-edge-lookup


./osrm-contract data.osrm --segment-speed-file updates.csv
# modify updates.csv
./osrm-contract data.osrm --segment-speed-file updates.csv
# Repeat in loop for desired update time

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

For even more speedups use the --level-cache option:

./osrm-extract data.osm.pbf -p profile.lua --generate-edge-lookup


# For the first run a core of 1.0 is required
./osrm-contract data.osrm --segment-speed-file updates.csv --core 1.0
# modify updates.csv
./osrm-contract data.osrm --segment-speed-file updates.csv --core 0.8 --level-cache true
# 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:

./osrm-extract data.osm.pbf -p profile.lua


./osrm-partition data.osrm

# Run the following in a loop as you replace updates.csv with new data
./osrm-customize data.osrm --segment-speed-file updates.csv

Remember to re-load the data by either restarting osrm-routed, or using osrm-routed -s


along with osrm-datastore.

5.1 Turn penalty data


OSRM also supports updating penalties applied to turn maneuvers for more realistic modelling
of turn maneuvers. This is achieved by providing osrm-contract with an additional file that
specifies turn penalty updates. For convenience, updates can be specified in a csv file. Each line
has to follow the format
from_osm_id,via_osm_id,to_osm_id,penalty_in_secs(,weight_penalty)?. If
weight_penalty is not specified in a CSV file then penalty_in_secs will be used to update
turn penalty weights.

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

./osrm-extract data.osm.pbf -p profile.lua --generate-edge-lookup


./osrm-contract data.osrm --turn-penalty-file penalties.csv

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.

5.2 Multiple data files


It is possible to specify multiple CSV files:

./osrm-contract data.osrm --segment-speed-file updates1.csv --segment-speed-file updates2.csv

To merge conflicting values a last-one-wins behavior is used. So values in updates2.csv will


have higher priority than in updates1.csv. The priority for values with equal keys in one file is
not specified.
6 Integrating third party raster data
As of OSRM version 4.8.0, OSRM supports incorporating third-party data into a Lua profile
with a native (non-PostGIS) API.

6.1 Data Format


As of the initial release, this feature only supports plaintext ASCII grid sources — looking
something like

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

These lines should be stripped before loading this source file.

6.2 Profile API


To use a raster source in a profile, include a source_function in your profile. When present,
this function is called once by a specific lua state that can later be used for per-segment updates.
A source_function takes no arguments in its signature and should be used to call
sources:load as such:

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:

if sourceData.datum ~= sourceData.invalid_data() then


-- this is in bounds
end

…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

function segment_function (segment)


local out_of_bounds = false
if segment.source.lon < LON_MIN or segment.source.lon > LON_MAX or
segment.source.lat < LAT_MIN or segment.source.lat > LAT_MAX or
segment.target.lon < LON_MIN or segment.target.lon > LON_MAX or
segment.target.lat < LAT_MIN or segment.target.lat > LAT_MAX then
out_of_bounds = true
end

if out_of_bounds == false then


local sourceData = sources:interpolate(raster_source, segment.source.lon, segment.source.lat)
local targetData = sources:interpolate(raster_source, segment.target.lon, segment.target.lat)
local elev_delta = targetData.datum - sourceData.datum

local slope = 0
local penalize = 0

if distance ~= 0 and targetData.datum > 0 and sourceData.datum > 0 then


slope = elev_delta / segment.distance
end

-- 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.1 Available profiles


Out-of-the-box OSRM comes with profiles for car, bicycle and foot. You can easily modify these
or create new ones if you like.
Profiles have a 'lua' extension, and are placed in 'profiles' directory.
When running OSRM preprocessing commands you specify the profile with the --profile (or the
shorthand -p) option, for example:

osrm-extract --profile ../profiles/car.lua planet-latest.osm.pbf

7.2 Processing flow


It's important to understand that profiles are used when preprocessing the OSM data, NOT at
query time when routes are computed.
This means that after modifying a profile you will need to extract, contract and reload the data
again and to see changes in the routing results. See Processing Flow for more.

7.3 Profiles are written in Lua


Profiles are not just configuration files. They are scripts written in the Lua scripting language. The
reason for this is that OpenStreetMap data is complex, and it's not possible to simply define tag
mappings. Lua scripting offers a powerful way to handle all the possible tag combinations found
in OpenStreetMap nodes and ways.
7.4 Basic structure of profiles
A profile will process every node and way in the OSM input data to determine what ways are
routable in which direction, at what speed, etc.
A profile will typically:
• Define api version (required)
• Require library files (optional)
• Define setup function (required)
• Define process functions (some are required)
• Return functions table (required)
A profile can also define various local functions it needs.
Looking at car.lua as an example, at the top of the file the api version is defined and then required
library files are included.
Then follows the setup function, which is called once when the profile is loaded. It returns a big
hash table of configurations, specifying things like what speed to use for different way types. The
configurations are used later in the various processing functions. Many adjustments can be done
just by modifying this configuration table.
The setup function is also where you can do other setup, like loading an elevation data source if
you want to consider that when processing ways.
Then come the process_node and process_way functions, which are called for each OSM
node and way when extracting OpenStreetMap data with osrm-extract.
The process_turn function processes every possible turn in the network, and sets a penalty
depending on the angle and turn of the movement.
Profiles can also define a process_segment function to handle differences in speed along an
OSM way, for example to handle elevation. As you can see, this is not currently used in the car
profile.
At the end of the file, a table is returned with references to the setup and processing functions
the profile has defined.
7.5 Understanding speed, weight and rate
When computing a route from A to B there can be different measures of what is the best route.
That's why there's a need for different profiles.
Because speeds vary on different types of roads, the shortest and the fastest route are typically
different. But there are many other possible preferences. For example a user might prefer a
bicycle route that follow parks or other green areas, even though both duration and distance are a
bit longer.
To handle this, OSRM doesn't simply choose the ways with the highest speed. Instead it uses the
concepts of weight and rate. The rate is an abstract measure that you can assign to ways as you
like to make some ways preferable to others. Routing will prefer ways with high rate.
The weight of a way is normally computed as length / rate. The weight can be thought of as the
resistance or cost when passing the way. Routing will prefer ways with low weight.
You can also set the weight of a way to a fixed value. In this case it's not calculated based on the
length or rate, and the rate is ignored.
You should set the speed to your best estimate of the actual speed that will be used on a
particular way. This will result in the best estimated travel times.
If you want to prefer certain ways due to other factors than the speed, adjust the rate accordingly.
If you adjust the speed, the time estimation will be skewed.
If you set the same rate on all ways, the result will be shortest path routing. If you set rate = speed
on all ways, the result will be fastest path routing. If you want to prioritize certain streets,
increase the rate on these.

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.2 Library files


The folder profiles/lib/ contains LUA library files for handling many common processing tasks.
File Notes
way_handlers.lua Functions for processing way tags
tags.lua Functions for general parsing of OSM tags
set.lua Defines the Set helper for handling sets of values
sequence.lua Defines the Sequence helper for handling sequences of values
access.lua Function for finding relevant access tags
destination.lua Function for finding relevant destination tags
maxspeed.lua Function for determining maximum speed
guidance.lua Function for processing guidance attributes
They all return a table of functions when you use require to load them. You can either store
this table and reference its functions later, or if you need only a single function you can store that
directly.

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

7.6.4 process_node(profile, node, result, relations)


Process an OSM node to determine whether this node is a barrier or can be passed and whether
passing it incurs a delay.
Argument Description
profile The configuration table you returned in setup.
node The input node to process (read-only).
result The output that you will modify.
relations Storage of relations to access relations, where node is a member.
The following attributes can be set on result:
Attribute Type Notes
barrier Boolean Is it an impassable barrier?
traffic_lights Boolean Is it a traffic light (incurs delay in process_turn)?

7.6.5 process_way(profile, way, result, relations)


Given an OpenStreetMap way, the process_way function will either return nothing (meaning
we are not going to route over this way at all), or it will set up a result hash.
Argument Description
profile The configuration table you returned in setup.
way The input way to process (read-only).
result The output that you will modify.
relations Storage of relations to access relations, where way is a member.
Importantly it will set result.forward_mode and result.backward_mode to indicate the
travel mode in each direction, as well as set result.forward_speed and
result.backward_speed to integer values representing the speed for traversing the way.
It will also set a number of other attributes on result.
Using the power of the scripting language you wouldn't typically see something as simple as a
result.forward_speed = 20 line within the process_way function. Instead process_way
will examine the tag set on the way, process this information in various ways, calling other local
functions and referencing the configuration in profile, etc., before arriving at the result.
The following attributes can be set on the result in process_way:
Attribute Type Notes
forward_speed Float Speed on this way in km/h. Mandatory.
backward_speed Float ""
Routing weight, expressed as meters/weight (e.g. for a fastest-route
forward_rate Float weighting, you would want this to be meters/second, so set it to
forward_speed/3.6)
backward_rate Float ""
Mode of travel (e.g. car, ferry). Mandatory. Defined in
forward_mode Enum
include/extractor/travel_mode.hpp.
backward_mode Enum ""
Mark this way as being of a specific class, e.g.
forward_classes Table result.classes["toll"] = true. This will be exposed in the API as
classes on each RouteStep.
backward_classes Table ""
duration Float Alternative setter for duration of the whole way in both directions
weight Float Alternative setter for weight of the whole way in both directions
turn_lanes_forward String Directions for individual lanes (normalized OSM turn:lanes value)
turn_lanes_backward String ""
Is this a restricted access road? (e.g. private, or deliveries only; used to
forward_restricted Boolean enable high turn penalty, so that way is only chosen for start/end of
route)
backward_restricted Boolean ""
Can a journey start on this way? (e.g. ferry; if false, prevents snapping
is_startpoint Boolean
the start point to this way)
roundabout Boolean Is this part of a roundabout?
circular Boolean Is this part of a non-roundabout circular junction?
name String Name of the way
Road number (equal to set forward_ref and backward_ref with one
ref String
value)
forward_ref String Road number in forward way direction
backward_ref String Road number in backward way direction
destinations String The road's destinations
exits String The ramp's exit numbers or names
pronunciation String Name pronunciation
Attribute Type Notes
road_classification.motorway_
Boolean Guidance: way is a motorway
class
road_classification.link_class Boolean Guidance: way is a slip/link road
road_classification.road_priori Guidance: order in priority list. Defined in
Enum
ty_class include/extractor/guidance/road_classification.hpp
road_classification.may_be_ig
Boolean Guidance: way is non-highway
nored
road_classification.num_lanes Unsigned Guidance: total number of lanes in way

7.6.6 process_segment(profile, segment)


The process_segment function is called for every segment of OSM ways. A segment is a
straight line between two OSM nodes.
On OpenStreetMap way cannot have different tags on different parts of a way. Instead you
would split the way into several smaller ways. However many ways are long. For example, many
ways pass hills without any change in tags.
Processing each segment of an OSM way makes it possible to have different speeds on different
parts of a way based on external data like data about elevation, pollution, noise or scenic value
and adjust weight and duration of the segment accordingly.
In the process_segment function you don't have access to OSM tags. Instead you use the
geographical location of the start and end point of the way to look up information from another
data source, like elevation data. See rasterbot.lua for an example.
The following attributes can be read and set on the result in process_segment:
Attribute Read/write? Type Notes
source.lon Read Float Co-ordinates of segment start
source.lat Read Float ""
target.lon Read Float Co-ordinates of segment end
target.lat Read Float ""
distance Read Float Length of segment
weight Read/write Float Routing weight for this segment
duration Read/write Float Duration for this segment

7.6.7 process_turn(profile, turn)


The process_turn function is called for every possible turn in the network. Based on the angle
and type of turn you assign the weight and duration of the movement.
The following attributes can be read and set on the result in process_turn:
Read/
Attribute Type Notes
write?
Angle of turn in degrees ([-179, 180]: 0=straight, 180=u turn, +x=x
angle Read Float
degrees to the right, -x= x degrees to the left)
number_of_roads Read Integer Number of ways at the intersection of the turn
is_u_turn Read Boolean Is the turn a u-turn?
has_traffic_light Read Boolean Is a traffic light present at this turn?
is_left_hand_driving Read Boolean Is left-hand traffic?
source_restricted Read Boolean Is it from a restricted access road? (See definition in process_way)
Travel mode before the turn. Defined in
source_mode Read Enum
include/extractor/travel_mode.hpp
source_is_motorway Read Boolean Is the source road a motorway?
source_is_link Read Boolean Is the source road a link?
source_number_of_la How many lanes does the source road have? (default when not tagged:
Read Integer
nes 0)
source_highway_turn Classification based on highway tag defined by user during setup.
Read Integer
_classification (default when not set: 0, allowed classification values are: 0-15))
source_access_turn_cl Classification based on access tag defined by user during setup. (default
Read Integer
assification when not set: 0, allowed classification values are: 0-15))
source_speed Read Integer Speed on this source road in km/h
The type of road priority class of the source. Defined in
source_priority_class Read Enum
include/extractor/guidance/road_classification.hpp
target_restricted Read Boolean Is the target a restricted access road? (See definition in process_way)
Travel mode after the turn. Defined in
target_mode Read Enum
include/extractor/travel_mode.hpp
target_is_motorway Read Boolean Is the target road a motorway?
target_is_link Read Boolean Is the target road a link?
target_number_of_lan How many lanes does the target road have? (default when not tagged:
Read Integer
es 0)
target_highway_turn_ Classification based on highway tag defined by user during setup.
Read Integer
classification (default when not set: 0, allowed classification values are: 0-15))
target_access_turn_cla Classification based on access tag defined by user during setup. (default
Read Integer
ssification when not set: 0, allowed classification values are: 0-15))
target_speed Read Integer Speed on this target road in km/h
The type of road priority class of the target. Defined in
target_priority_class Read Enum
include/extractor/guidance/road_classification.hpp
Vector with information about other roads on the right of the turn that
roads_on_the_right Read Vector
are also connected at the intersection
Vector with information about other roads on the left of the turn that
roads_on_the_left Read Vector
are also connected at the intersection. If turn is a u turn, this is empty.
Read/
Attribute Type Notes
write?
Read/
weight Float Penalty to be applied for this turn (routing weight)
write
Read/
duration Float Penalty to be applied for this turn (duration in deciseconds)
write
7.6.7.1 roads_on_the_right and roads_on_the_left

The information of roads_on_the_right and roads_on_the_left that can be read are as


follows:
Read/
Attribute Type Notes
write?
is_restricted Read Boolean Is it a restricted access road? (See definition in process_way)
Travel mode before the turn. Defined in
mode Read Enum
include/extractor/travel_mode.hpp
is_motorway Read Boolean Is the road a motorway?
is_link Read Boolean Is the road a link?
number_of_lanes Read Integer How many lanes does the road have? (default when not tagged: 0)
highway_turn_classi Classification based on highway tag defined by user during setup.
Read Integer
fication (default when not set: 0, allowed classification values are: 0-15)
access_turn_classific Classification based on access tag defined by user during setup. (default
Read Integer
ation when not set: 0, allowed classification values are: 0-15)
speed Read Integer Speed on this road in km/h
The type of road priority class of the leg. Defined in
priority_class Read Enum
include/extractor/guidance/road_classification.hpp
is_incoming Read Boolean Is the road an incoming road of the intersection
is_outgoing Read Boolean Is the road an outgoing road of the intersection
The order of the roads in roads_on_the_right and roads_on_the_left are counter clockwise. If
the turn is a u turn, all other connected roads will be in roads_on_the_right.
Example

c e
| /
| /
a ---- x ---- b
/|
/ |
f d

When turning from a to b via x,


• roads_on_the_right[1] is the road xf
• roads_on_the_right[2] is the road xd
• roads_on_the_left[1] is the road xe
• roads_on_the_left[2] is the road xc
Note that indices of arrays in lua are 1-based.

7.6.7.2 highway_turn_classification and access_turn_classification

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

function process_turn(profile, turn) {


if turn.source_highway_turn_classification == 2 and turn.target_highway_turn_classification ==
2 then
turn.weight = 10
end
if turn.source_highway_turn_classification == 1 and turn.target_highway_turn_classification ==
1 then
turn.weight = 5
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.

7.7.1 Using raster data


OSRM has built-in support for loading an interpolating raster data in ASCII format. This can be
used e.g. for factoring in elevation when computing routes.
Use raster:load() in your setup function to load data and store the source in your
configuration hash:

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:

function process_segment (profile, segment)


local sourceData = raster:query(profile.raster_source, segment.source.lon, segment.source.lat)
local targetData = raster:query(profile.raster_source, segment.target.lon, segment.target.lat)

local invalid = sourceData.invalid_data()


if sourceData.datum ~= invalid and targetData.datum ~= invalid then
-- use values to adjust weight and duration
[...]
end

See rasterbot.lua and rasterbotinterp.lua for examples.

7.7.2 Helper functions


There are a few helper functions defined in the global scope that profiles can use:
• durationIsValid
• parseDuration
• trimLaneString
• applyAccessTokens
• canonicalizeStringList
8 HTTP - API
8.1 General options
All OSRM HTTP requests use a common structure.
The following syntax applies to all services, except as noted.

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}

8.1.1.1 Example Requests

# Query on Berlin with three coordinates:


curl
'http://router.project-osrm.org/route/v1/driving/13.388860,52.517037;13.397634,52.529407;13.42855
5,52.523219?overview=false'

# Query on Berlin excluding the usage of motorways:


curl 'http://router.project-osrm.org/route/v1/driving/13.388860,52.517037;13.397634,52.529407?
exclude=motorway'

# 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.

8.1.2.2 Data version

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.

8.1.2.3 Example response

{
"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}

Where coordinates only supports a single {longitude},{latitude} entry.


In addition to the general options the following options are supported for this service:
Option Values Description
number integer >= 1 (default 1) Number of nearest segments that should be returned.
Response
• code if the request was successful Ok otherwise see the service dependent and general
status codes.
• waypoints array of Waypoint objects sorted by distance to the input coordinate. Each
object has at least the following additional properties:
• nodes: Array of OpenStreetMap node ids.

8.2.1.1 Example Requests

# 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'

8.2.1.2 Example Response

{
"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"
}

8.2.2 Route service


Finds the fastest route between coordinates in the supplied order.

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.

8.2.2.1 Example Request

# Query on Berlin with three coordinates and no overview geometry returned:


curl
'http://router.project-osrm.org/route/v1/driving/13.388860,52.517037;13.397634,52.529407;13.42855
5,52.523219?overview=false'

8.2.3 Table service


Computes the duration of the fastest route between all pairs of supplied coordinates. Returns the
durations or distances or both between the coordinate pairs. Note that the distances are not the
shortest distance between two coordinates, but rather the distances of the fastest routes. Duration
is in seconds and distances is in meters.

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 3x3 duration matrix:


curl
'http://router.project-osrm.org/table/v1/driving/13.388860,52.517037;13.397634,52.529407;13.42855
5,52.523219'

# Returns a 1x3 duration matrix


curl
'http://router.project-osrm.org/table/v1/driving/13.388860,52.517037;13.397634,52.529407;13.42855
5,52.523219?sources=0'

# 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:


curl
'http://router.project-osrm.org/table/v1/driving/13.388860,52.517037;13.397634,52.529407;13.42855
5,52.523219?annotations=duration'

# Returns 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'

# 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.

8.2.3.2 Example Response

{
"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 ]
]
}

8.2.4 Match service


Map matching matches/snaps 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.

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.

8.2.5 Trip service


The trip plugin solves the Traveling Salesman Problem using a greedy heuristic (farthest-
insertion algorithm) for 10 or more waypoints and uses brute force for less than 10 waypoints.
The returned path does not have to be the fastest path. As TSP is NP-hard it only returns an
approximation. Note that all input coordinates have to be connected for the trip service to work.

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 three stops:


curl
'http://router.project-osrm.org/trip/v1/driving/13.388860,52.517037;13.397634,52.529407;13.428555
,52.523219'

# 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

The x, y, and zoom values are the same as described at


https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames, and are supported by vector tile viewers
like Mapbox GL JS.

8.2.6.1 Example request

# This fetches a Z=13 tile for downtown San Francisco:


curl 'http://router.project-osrm.org/tile/v1/car/tile(1310,3166,13).mvt'

8.2.6.2 Example response

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

Three input coordinates, geometry=geojson, steps=false:

{
"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

With steps=false and annotations=true:

{
"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 Annotation object


Annotation of the whole route leg with fine-grained information about each segment or node id.
Properties
• distance: The distance, in metres, between each pair of coordinates
• duration: The duration between each pair of coordinates, in seconds. Does not include
the duration of any turns.
• datasources: The index of the datasource for the speed between each pair of
coordinates. 0 is the default profile, other values are supplied via --segment-speed-file
to osrm-contract or osrm-customize. String-like names are in the
metadata.datasource_names array.
• nodes: The OSM node ID for each coordinate along the route, excluding the first/last
user-supplied coordinates
• weight: The weights between each pair of coordinates. Does not include any turn costs.
• speed: Convenience field, calculation of distance / duration rounded to one decimal
place
• metadata: Metadata related to other annotations
• datasource_names: The names of the datasources used for the speed between
each pair of coordinates. lua profile is the default profile, other values arethe
filenames supplied via --segment-speed-file to osrm-contract or osrm-
customize

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 RouteStep object


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.
Properties
• distance: The distance of travel from the maneuver to the subsequent step, in float
meters.
• duration: The estimated travel time, in float number of seconds.
• geometry: The unsimplified geometry of the route segment, depending on the
geometries parameter.
• weight: The calculated weight of the step.
geometry
polyline polyline with precision 5 in [latitude,longitude] encoding
polyline6 polyline with precision 6 in [latitude,longitude] encoding
geojson GeoJSON LineString
• name: The name of the way along which travel proceeds.
• ref: A reference number or code for the way. Optionally included, if ref data is available
for the given way.
• pronunciation: A string containing an IPA phonetic transcription indicating how to
pronounce the name in the name property. This property is omitted if pronunciation data
is unavailable for the step.
• destinations: The destinations of the way. Will be undefined if there are no
destinations.
• exits: The exit numbers or names of the way. Will be undefined if there are no exit
numbers or names.
• mode: A string signifying the mode of transportation.
• maneuver: A StepManeuver object representing the maneuver.
• intersections: A list of Intersection objects that are passed along the segment, the
very first belonging to the StepManeuver
• rotary_name: The name for the rotary. Optionally included, if the step is a rotary and a
rotary name is available.
• rotary_pronunciation: The pronunciation hint of the rotary name. Optionally
included, if the step is a rotary and a rotary pronunciation is available.
• driving_side: The legal driving side at the location for this step. Either left or right.

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.5 StepManeuver object


Properties
• location: A [longitude, latitude] pair describing the location of the turn.
• bearing_before: The clockwise angle from true north to the direction of travel
immediately before the maneuver. Range 0-359.
• bearing_after: The clockwise angle from true north to the direction of travel
immediately after the maneuver. Range 0-359.
• type A string indicating the type of maneuver. new identifiers might be introduced
without API change Types unknown to the client should be handled like the turn type,
the existence of correct modifier values is guranteed.
type Description
turn a basic turn into direction of the modifier
no turn is taken/possible, but the road name changes. The road can take a turn itself,
new name
following modifier.
depart indicates the departure of the leg
type Description
arrive indicates the destination of the leg
merge onto a street (e.g. getting on the highway from a ramp, the modifier specifies the
merge
direction of the merge)
ramp Deprecated. Replaced by on_ramp and off_ramp.
on ramp take a ramp to enter a highway (direction given my modifier)
off ramp take a ramp to exit a highway (direction given my modifier)
fork take the left/right side at a fork depending on modifier
end of road road ends in a T intersection turn in direction of modifier
use lane Deprecated replaced by lanes on all intersection entries
continue Turn in direction of modifier to stay on the same road
traverse roundabout, if the route leaves the roundabout there will be an additional property
roundabout
exit for exit counting. The modifier specifies the direction of entering the roundabout.
a traffic circle. While very similar to a larger version of a roundabout, it does not necessarily
follow roundabout rules for right of way. It can offer rotary_name and/or
rotary
rotary_pronunciation parameters (located in the RouteStep object) in addition to the
exit parameter (located on the StepManeuver object).
Describes a turn at a small roundabout that should be treated as normal turn. The modifier
roundabout turn
indicates the turn direciton. Example instruction: At the roundabout turn left.
not an actual turn but a change in the driving conditions. For example the travel mode or
notification
classes. If the road takes a turn itself, the modifier describes the direction
exit roundabout Describes a maneuver exiting a roundabout (usually preceeded by a roundabout instruction)
exit rotary Describes the maneuver exiting a rotary (large named roundabout)
Please note that even though there are new name and notification instructions, the mode and
name can change between all instructions. They only offer a fallback in case nothing else is to
report.
• modifier An optional string indicating the direction change of the maneuver.
modifier Description
uturn indicates reversal of direction
sharp right a sharp right turn
right a normal turn to the right
slight right a slight turn to the right
straight no relevant change in direction
slight left a slight turn to the left
left a normal turn to the left
sharp left a sharp turn to the left
The list of turns without a modifier is limited to: depart/arrive. If the source/target location is
close enough to the depart/arrive location, no modifier will be given.
The meaning depends on the type property.
type Description
turn modifier indicates the change in direction accomplished through the turn
modifier indicates the position of departure point and arrival point in relation to the current
depart/arrive
direction of travel
• exit An optional integer indicating number of the exit to take. The property exists for
the roundabout / rotary property: Number of the roundabout exit to take. If exit is
undefined the destination is on the roundabout.
New properties (potentially depending on type) may be introduced in the future without an
API version change.

8.3.6 Lane object


A Lane represents a turn lane at the corresponding turn location.
Properties
• indications: a indication (e.g. marking on the road) specifying the turn lane. A road can
have multiple indications (e.g. an arrow pointing straight and left). The indications are
given in an array, each containing one of the following types. Further indications might be
added on without an API version change.
value Description
none No dedicated indication is shown.
uturn An indication signaling the possibility to reverse (i.e. fully bend arrow).
sharp right An indication indicating a sharp right turn (i.e. strongly bend arrow).
right An indication indicating a right turn (i.e. bend arrow).
slight right An indication indicating a slight right turn (i.e. slightly bend arrow).
straight No dedicated indication is shown (i.e. straight arrow).
slight left An indication indicating a slight left turn (i.e. slightly bend arrow).
left An indication indicating a left turn (i.e. bend arrow).
sharp left An indication indicating a sharp left turn (i.e. strongly bend arrow).
• valid: a boolean flag indicating whether the lane is a valid choice in the current
maneuver

8.3.6.1 Example

{
"indications": ["left", "straight"],
"valid": "false"
}

8.3.7 Intersection object


An intersection gives a full representation of any cross-way the path passes bay. For every step,
the very first intersection (intersections[0]) corresponds to the location of the
StepManeuver. Further intersections are listed for every cross-way until the next turn instruction.
Properties
• location: A [longitude, latitude] pair describing the location of the turn.
• bearings: A list of bearing values (e.g. [0,90,180,270]) that are available at the
intersection. The bearings describe all available roads at the intersection. Values are
between 0-359 (0=true north)
• classes: An array of strings signifying the classes (as specified in the profile) of the road
exiting the intersection.
• entry: A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value of
true indicates that the respective road could be entered on a valid route. false indicates
that the turn onto the respective road would violate a restriction.
• in: index into bearings/entry array. Used to calculate the bearing just before the turn.
Namely, the clockwise angle from true north to the direction of travel immediately before
the maneuver/passing the intersection. Bearings are given relative to the intersection. To
get the bearing in the direction of driving, the bearing has to be rotated by a value of 180.
The value is not supplied for depart maneuvers.
• out: index into the bearings/entry array. Used to extract the bearing just after the turn.
Namely, The clockwise angle from true north to the direction of travel immediately after
the maneuver/passing the intersection. The value is not supplied for arrive maneuvers.
• lanes: Array of Lane objects that denote the available turn lanes at the intersection. If no
lane information is available for an intersection, the lanes property will not be present.

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 Waypoint object


Object used to describe waypoint on a route.
Properties
• name Name of the street the coordinate snapped to
• location Array that contains the [longitude, latitude] pair of the snapped
coordinate
• distance The distance, in metres, from the input coordinate to the snapped coordinate
• hint Unique internal identifier of the segment (ephemeral, not constant over data
updates) This can be used on subsequent request to significantly speed up the query and
to connect multiple services. E.g. you can use the hint value obtained by the nearest
query as hint values for route inputs.

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/:

node_modules/osrm/lib/binding/osrm-extract data.osm.pbf -p node_modules/osrm/profiles/car.lua


node_modules/osrm/lib/binding/osrm-contract data.osrm

Consult the osrm-backend documentation or further details.


Once you have a complete network.osrm file, you can calculate networks in javascript with this
library using the methods below. To create an OSRM instance with your network you need to
construct an instance like this:

var osrm = new OSRM('network.osrm');

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.2 General Options


Each OSRM method (except for OSRM.tile()) has set of general options as well as unique
options, outlined below.
Option Values Description Format
array of coordinate
array with [{lon},{lat}]
coordinates elements: [{coordinate}, The coordinates this request will use.
values, in decimal degrees
...]
bearings array of bearing Limits the search to segments with null or array with [{value},
Option Values Description Format
elements: given bearing in degrees towards true {range}] integer 0 ..
[{bearing}, ...] north in clockwise direction. 360,integer 0 .. 180
array of radius elements: Limits the search to given radius in null or double >= 0 or
radiuses
[{radius}, ...] meters. unlimited (default)
array of hint elements: Hint to derive position in street
hints Base64 string
[{hint}, ...] network.
Adds a Hint to the response which
generate_hin
true (default) or false can be used in subsequent requests, Boolean
ts
see hints parameter.

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
});

Returns Buffer contains a Protocol Buffer encoded vector tile.

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
});

Returns Object containing tracepoints and matchings. tracepoints Array of Ẁaypoint


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 includes two
additional properties, 1) matchings_index: Index to the Route object in matchings the sub-trace
was matched to, 2) waypoint_index: Index of the waypoint inside the matched route.
matchings is an array of Route objects that assemble the trace. Each Route object has an
additional confidence property, which is the confidence of the matching. float value between 0
and 1. 1 is very confident that the matching is correct.

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

9.8.1.1 Fixing Start and End Points

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

var osrm = new OSRM('network.osrm');


var options = {
coordinates: [
[13.36761474609375, 52.51663871100423],
[13.374481201171875, 52.506191342034576]
]
}
osrm.trip(options, function(err, response) {
if (err) throw err;
console.log(response.waypoints); // array of Waypoint objects
console.log(response.trips); // array of Route objects
});

9.8.2.2 Non Roundtrip Request

var osrm = new OSRM('network.osrm');


var options = {
coordinates: [
[13.36761474609375, 52.51663871100423],
[13.374481201171875, 52.506191342034576]
],
source: "first",
destination: "last",
roundtrip: false
}
osrm.trip(options, function(err, response) {
if (err) throw err;
console.log(response.waypoints); // array of Waypoint objects
console.log(response.trips); // array of Route objects
});

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 OSM input data


Data comes from OSM, which has nodes, ways and relations

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.

10.2 OSRM edge-expanded graph


OSRM loads the OSM data, and transforms it into an edge-expanded graph that's better suited
for modelling turn costs and turn restrictions. Suppose the following OSM data is loaded:
| | | d |
| a | b | c |
| | | e |

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:

ab-bc (from ab, continue on bc)


ba-ab (from ba, do a u-turn at a and return on ab)
bc-cd (from bc, turn left onto dc)
bc-ce (from bc, turn right onto ce)
cb-ba (from cb, continue along on ba)
cd-dc (from cd, do a u-turn at d and return on dc)
ce-ec (from ce, do a u turn at e and return on ec)
dc-cb (from dc, turn right onto cd)
dc-ce (from dc, continue on ce)
ec-cd (from ec, continue on cd)
ec-cb (from ec, turn left onto cb)

OSRM will also remove turns that are prohibited by turn restrictions.

10.2.1 Graph node


Graph nodes represents a specific direction (forward or backward) of an OSM segment. There are
two graph nodes for a bidirectional segment, but only one if it's a oneway segment.

10.2.2 Graph Edge


Graph edges connect graph nodes, and thus represent transitioning from moving in a specific
direction of one OSM segment, to moving in a specific direction of another (or the same) OSM
segment. The transition can be either via a turn from one way onto another way, doing a u-turn,
or moving from segment to segment along the same way.
Here's an image that shows the basic changes in the graph leading up to the edge-based graph.
Some details (bidirectional edges) are ignored for the sake of simplicity:

S-ar putea să vă placă și