OSRM
The OSRM method is the main constructor for creating an OSRM instance.
An OSRM instance requires a .osrm.* dataset(.osrm.* because it contains several files), which is prepared by the OSRM toolchain.
You can create such a .osrm.* dataset 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.osrmConsult the osrm-backend documentation for further details.
Once you have a complete network.osrm.* dataset, you can calculate routes in javascript with this object.
var osrm = new OSRM('network.osrm');Parameters
options(Object | String ) Options for creating an OSRM object or string to the.osrmfile. (optional, default{shared_memory:true})options.algorithmString ? The algorithm to use for routing. Can be ‘CH’, ‘CoreCH’ or ‘MLD’. Default is ‘CH’. Make sure you prepared the dataset with the correct toolchain.options.shared_memoryBoolean ? Connects to the persistent shared memory datastore. This requires you to runosrm-datastoreprior to creating anOSRMobject.options.dataset_nameString ? Connects to the persistent shared memory datastore defined by--dataset_nameoption when runningosrm-datastore. This requires you to runosrm-datastore --dataset_nameprior to creating anOSRMobject.options.memory_fileString ? DEPRECATED Old behaviour: Path to a file on disk to store the memory using mmap. Current behaviour: setting this value is the same as settingmmap_memory: true.options.mmap_memoryBoolean ? Map on-disk files to virtual memory addresses (mmap), rather than loading into RAM.options.pathString ? The path to the.osrmfiles. This is mutually exclusive with setting {options.shared_memory} to true.options.max_locations_tripNumber ? Max. locations supported in trip query (default: unlimited).options.max_locations_viarouteNumber ? Max. locations supported in viaroute query (default: unlimited).options.max_locations_distance_tableNumber ? Max. locations supported in distance table query (default: unlimited).options.max_locations_map_matchingNumber ? Max. locations supported in map-matching query (default: unlimited).options.max_radius_map_matchingNumber ? Max. radius size supported in map matching query (default: 5).options.max_results_nearestNumber ? Max. results supported in nearest query (default: unlimited).options.max_alternativesNumber ? Max. number of alternatives supported in alternative routes query (default: 3).
route
Returns the fastest route between two or more coordinates while visiting the waypoints in order.
Parameters
optionsObject Object literal containing parameters for the route query.options.coordinatesArray ? The coordinates this request will use, coordinates as[{lon},{lat}]values, in decimal degrees.options.bearingsArray ? Limits the search to segments with given bearing in degrees towards true north in clockwise direction. Can benullor an array of[{value},{range}]withinteger 0 .. 360,integer 0 .. 180.options.radiusesArray ? Limits the coordinate snapping to streets in the given radius in meters. Can benull(unlimited, default) ordouble >= 0.options.hintsArray ? Hints for the coordinate snapping. Array of base64 encoded strings.options.excludeArray ? List of classes to avoid, order does not matter.options.generate_hintsBoolean Whether or not adds a Hint to the response which can be used in subsequent requests. (optional, defaulttrue)options.alternativesBoolean Search for alternative routes. (optional, defaultfalse)options.alternativesNumber Search for up to this many alternative routes. Please note that even if alternative routes are requested, a result cannot be guaranteed. (optional, default0)options.stepsBoolean Return route steps for each route leg. (optional, defaultfalse)options.annotations(Array | Boolean ) An array with strings ofduration,nodes,distance,weight,datasources,speedor boolean for enabling/disabling all. (optional, defaultfalse)options.geometriesString Returned route geometry format (influences overview and per step). Can also begeojson. (optional, defaultpolyline)options.overviewString Add overview geometry eitherfull,simplifiedaccording to highest zoom level it could be display on, or not at all (false). (optional, defaultsimplified)options.continue_straightBoolean ? 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.options.approachesArray ? Keep waypoints on curb side. Can benull(unrestricted, default) orcurb.null/true/falseoptions.waypointsArray ? Indices to coordinates to treat as waypoints. If not supplied, all coordinates are waypoints. Must include first and last coordinate index.options.formatString ? Which output format to use, eitherjson, orflatbuffers.options.snappingString ? Which edges can be snapped to, eitherdefault, orany.defaultonly snaps to edges marked by the profile asis_startpoint,anywill allow snapping to any edge in the routing graph.options.skip_waypointsBoolean Removes waypoints from the response. Waypoints are still calculated, but not serialized. Could be useful in case you are interested in some other part of response and do not want to transfer waste data. (optional, defaultfalse)
callbackFunction
Examples
var osrm = new OSRM("berlin-latest.osrm");
osrm.route({coordinates: [[52.519930,13.438640], [52.513191,13.415852]]}, 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.
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.
Parameters
optionsObject Object literal containing parameters for the nearest query.options.coordinatesArray ? The coordinates this request will use, coordinates as[{lon},{lat}]values, in decimal degrees.options.bearingsArray ? Limits the search to segments with given bearing in degrees towards true north in clockwise direction. Can benullor an array of[{value},{range}]withinteger 0 .. 360,integer 0 .. 180.options.radiusesArray ? Limits the coordinate snapping to streets in the given radius in meters. Can benull(unlimited, default) ordouble >= 0.options.hintsArray ? Hints for the coordinate snapping. Array of base64 encoded strings.options.generate_hintsBoolean Whether or not adds a Hint to the response which can be used in subsequent requests. (optional, defaulttrue)options.numberNumber Number of nearest segments that should be returned. Must be an integer greater than or equal to1. (optional, default1)options.approachesArray ? Keep waypoints on curb side. Can benull(unrestricted, default) orcurb.options.formatString ? Which output format to use, eitherjson, orflatbuffers.options.snappingString ? Which edges can be snapped to, eitherdefault, orany.defaultonly snaps to edges marked by the profile asis_startpoint,anywill allow snapping to any edge in the routing graph.
callbackFunction
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.
table
Computes duration table for the given locations. Allows for both symmetric and asymmetric tables. Optionally returns distance table.
Parameters
optionsObject Object literal containing parameters for the table query.options.coordinatesArray ? The coordinates this request will use, coordinates as[{lon},{lat}]values, in decimal degrees.options.bearingsArray ? Limits the search to segments with given bearing in degrees towards true north in clockwise direction. Can benullor an array of[{value},{range}]withinteger 0 .. 360,integer 0 .. 180.options.radiusesArray ? Limits the coordinate snapping to streets in the given radius in meters. Can benull(unlimited, default) ordouble >= 0.options.hintsArray ? Hints for the coordinate snapping. Array of base64 encoded strings.options.generate_hintsBoolean Whether or not adds a Hint to the response which can be used in subsequent requests. (optional, defaulttrue)options.sourcesArray ? An array ofindexelements (0 <= integer < #coordinates) to use location with given index as source. Default is to use all.options.destinationsArray ? An array ofindexelements (0 <= integer < #coordinates) to use location with given index as destination. Default is to use all.options.approachesArray ? Keep waypoints on curb side. Can benull(unrestricted, default) orcurb.options.fallback_speedNumber ? Replacenullresponses in result with as-the-crow-flies estimates based onfallback_speed. Value is in metres/second.options.fallback_coordinateString ? Eitherinput(default) orsnapped. If using afallback_speed, use either the user-supplied coordinate (input), or the snapped coordinate (snapped) for calculating the as-the-crow-flies distance between two points.options.scale_factorNumber ? Multiply the table duration values in the table by this number for more controlled input into a route optimization solver.options.snappingString ? Which edges can be snapped to, eitherdefault, orany.defaultonly snaps to edges marked by the profile asis_startpoint,anywill allow snapping to any edge in the routing graph.options.annotationsArray ? Return the requested table or tables in response. Can be['duration'](return the duration matrix, default),[distance'](return the distance matrix), or['duration', distance'](return both the duration matrix and the distance matrix).
callbackFunction
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.distances); // 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, distances, 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.
distances: array of arrays that stores the matrix in row-major order. distances[i][j] gives the travel time from the i-th waypoint to the j-th waypoint.
Values are given in meters.
sources: array of Ẁaypoint objects describing all sources in order.
destinations: array of Ẁaypoint objects describing all destinations in order.
fallback_speed_cells: (optional) if fallback_speed is used, will be an array of arrays of row,column values, indicating which cells contain estimated values.
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.
Parameters
ZXYArray an array consisting ofx,y, andzvalues representing tile coordinates like wiki.openstreetmap.org/wiki/Slippy_map_tilenames and are supported by vector tile viewers like Mapbox GL JS .callbackFunction
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.
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.
Parameters
optionsObject Object literal containing parameters for the match query.options.coordinatesArray ? The coordinates this request will use, coordinates as[{lon},{lat}]values, in decimal degrees.options.bearingsArray ? Limits the search to segments with given bearing in degrees towards true north in clockwise direction. Can benullor an array of[{value},{range}]withinteger 0 .. 360,integer 0 .. 180.options.hintsArray ? Hints for the coordinate snapping. Array of base64 encoded strings.options.generate_hintsBoolean Whether or not adds a Hint to the response which can be used in subsequent requests. (optional, defaulttrue)options.stepsBoolean Return route steps for each route. (optional, defaultfalse)options.annotations(Array | Boolean ) An array with strings ofduration,nodes,distance,weight,datasources,speedor boolean for enabling/disabling all. (optional, defaultfalse)options.geometriesString Returned route geometry format (influences overview and per step). Can also begeojson. (optional, defaultpolyline)options.overviewString Add overview geometry eitherfull,simplifiedaccording to highest zoom level it could be display on, or not at all (false). (optional, defaultsimplified)options.timestampsArray <Number >? Timestamp of the input location (integers, UNIX-like timestamp).options.radiusesArray ? Standard deviation of GPS precision used for map matching. If applicable use GPS accuracy. Can benullfor default value5meters ordouble >= 0.options.gapsString Allows the input track splitting based on huge timestamp gaps between points. Eithersplitorignore. (optional, defaultsplit)options.tidyBoolean Allows the input track modification to obtain better matching quality for noisy tracks. (optional, defaultfalse)options.waypointsArray ? Indices to coordinates to treat as waypoints. If not supplied, all coordinates are waypoints. Must include first and last coordinate index.options.snappingString ? Which edges can be snapped to, eitherdefault, orany.defaultonly snaps to edges marked by the profile asis_startpoint,anywill allow snapping to any edge in the routing graph.
callbackFunction
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 has the following 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.
3) 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 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.
trip
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 shortest 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.
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 |
Parameters
optionsObject Object literal containing parameters for the trip query.options.coordinatesArray ? The coordinates this request will use, coordinates as[{lon},{lat}]values, in decimal degrees.options.bearingsArray ? Limits the search to segments with given bearing in degrees towards true north in clockwise direction. Can benullor an array of[{value},{range}]withinteger 0 .. 360,integer 0 .. 180.options.radiusesArray ? Limits the coordinate snapping to streets in the given radius in meters. Can bedouble >= 0ornull(unlimited, default).options.hintsArray ? Hints for the coordinate snapping. Array of base64 encoded strings.options.generate_hintsBoolean Whether or not adds a Hint to the response which can be used in subsequent requests. (optional, defaulttrue)options.stepsBoolean Return route steps for each route. (optional, defaultfalse)options.annotations(Array | Boolean ) An array with strings ofduration,nodes,distance,weight,datasources,speedor boolean for enabling/disabling all. (optional, defaultfalse)options.geometriesString Returned route geometry format (influences overview and per step). Can also begeojson. (optional, defaultpolyline)options.overviewString Add overview geometry eitherfull,simplified(optional, defaultsimplified)options.roundtripBoolean Return route is a roundtrip. (optional, defaulttrue)options.sourceString Return route starts atanyorfirstcoordinate. (optional, defaultany)options.destinationString Return route ends atanyorlastcoordinate. (optional, defaultany)options.approachesArray ? Keep waypoints on curb side. Can benull(unrestricted, default) orcurb.options.snappingString ? Which edges can be snapped to, eitherdefault, orany.defaultonly snaps to edges marked by the profile asis_startpoint,anywill allow snapping to any edge in the routing graph.
callbackFunction
Examples
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 Waypoint 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.
Configuration
All plugins support a second additional object that is available to configure some NodeJS specific behaviours.
Parameters
plugin_configObject ? Object literal containing parameters for the trip query.plugin_config.formatString ? The format of the result object to various API calls. Valid options areobject(default ifoptions.formatisjson), which returns a standard Javascript object, as described above, andbuffer(default ifoptions.formatisflatbuffers), which will return a NodeJS Buffer object, containing a JSON string or Flatbuffers object. The latter has the advantage that it can be immediately serialized to disk/sent over the network, and the generation of the string is performed outside the main NodeJS event loop. This option is ignored by thetileplugin. Also note thatoptions.formatset toflatbufferscannot be used withplugin_config.formatset toobject.json_bufferis deprecated alias forbuffer.
Examples
var osrm = new OSRM('network.osrm');
var options = {
coordinates: [
[13.36761474609375, 52.51663871100423],
[13.374481201171875, 52.506191342034576]
]
};
osrm.route(options, { format: "buffer" }, function(err, response) {
if (err) throw err;
console.log(response.toString("utf-8"));
});Responses
Route
Represents a route through (potentially multiple) waypoints.
Parameters
externaldocumentation inosrm-backend
RouteLeg
Represents a route between two waypoints.
Parameters
externaldocumentation inosrm-backend
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
externaldocumentation inosrm-backend
StepManeuver
Parameters
externaldocumentation inosrm-backend
Waypoint
Object used to describe waypoint on a route.
Parameters
externaldocumentation inosrm-backend