Maps SDK for Web

tt.services.calculateRoute

Calculates a route between two locations using the TomTom Routing API;

Parameters need to be passed to the constructor.

The types used in the Routing service:

  • point - longitude, latitude pair (in EPSG4326 projection), with the following constraints:

    • Longitude values must be in the range -180..+180 inclusive.
    • Latitude values must be in the range -90..+90 inclusive.
    • Example: 4.89406, 52.37245
  • circle - A circle with a center point and a radius (in meters).

    • The radius must be a positive integer with the maximum value of 20050000.
    • Note that larger integer values will not be rejected but lowered to the maximum value.
    • Example: circle(4.89406,52.37245,10000)
  • location - A point or a circle.

    • Example: 4.89406,52.37245 circle(4.89406,52.37245,10000)
  • dateTime - A date and time specified in RFC-3339 format with an optional time zone offset.

    • Example: 1996-12-19T16:39:57 1996-12-19T16:39:57-08:00

Response

This service extends the API response by providing the following methods:

  • toGeoJson(), converts route data into a FeatureCollection of LineString or MultiLineString geometries.
  • toRouteSectionsCollection(), provides an array of FeatureCollections. Each FeatureCollection consists of LineStrings representing segments of the route. Take a look at Route sections example to see it in action.
  • getTrackingId(), returns the Tracking-ID associated with the request.

To read more about services responses take a look at Difference between API responses and this library's responses section. or dive into Static route example code.

Constructor

tt.services.calculateRoute([options], [additionalOptions])

Example
tt.services.calculateRoute({
  key: <Your API key>,
  locations: '4.8,52.3:4.87,52.37'
}).then(function(routeData) {
    console.log(routeData.toGeoJson());
  });
Parameters
Name Description
options
Object | Array
default:None
Options to be passed to the routing call, or an array of such options objects to perform a batch request.
additionalOptions
Object
default:None
Additional options to be passed to the service.
additionalOptions.abortSignal
Object
default:None

Signal created with abortController.


Use AbortController to cancel requests in progress.
Example
var abortController = new AbortController();
var options = {};
tt.services.calculateRoute(options, { abortSignal: abortController.signal })
    .then(function(response) { console.log(response) });
    .catch(function(error) {
        if (abortController.signal.aborted === true) {
            console.log('Request aborted.');
        }
    });
abortController.abort();
options.accelerationEfficiency
Number
default:None
Specifies the efficiency of converting chemical energy stored in fuel to kinetic energy when the vehicle accelerates (i.e., KineticEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed is obtained by converting consumed fuel to chemical energy using fuelEnergyDensityInMJoulesPerLiter.
options.allowVignette
String | String[]
default:None
An array of country codes.
List of 3-character ISO 3166-1 alpha-3 country codes of countries in which toll roads with vignettes are allowed. Specifying allowVignette with some countries X is equivalent to specifying avoidVignette with all countries but X. Specifying allowVignette with an empty list is the same as avoiding all toll roads with vignettes. It is an error to specify both avoidVignette and allowVignette.
options.alternativeType
String
default:None
The type of the alternative route.
Specifies whether to compute alternatives with the objective to find routes that are significantly different, or whether to look for routes better than the reference route. Possible values are:
  1. anyRoute: compute alternative routes that are significantly different from the reference route.
  2. betterRoute: return an alternative route only if it is better than the reference route according to the given planning criteria. If there is a road block on the reference route, then any alternative that does not contain blockages is considered as a better route.
Can only be used when reconstructing a route.
options.arriveAt
String
default:None
The properly formatted date with a time value. Date cannot be in the past and has to follow ISO 8601 standard.
The date and time of arrival at the destination point. It must be specified as a dateTime. When a time zone offset is not specified it will be assumed to be that of the destination point. The arriveAt value must be in the future. The arriveAt parameter cannot be used in conjunction with departAt.
options.auxiliaryPowerInkW
Number
default:None
Specifies the amount of power consumed for sustaining auxiliary systems in kilowatts (kW). It can be used to specify consumption due to devices and systems such as AC systems, radio, heating, etc.
options.auxiliaryPowerInLitersPerHour
Number
default:None
Specifies the amount of fuel consumed for sustaining auxiliary systems of the vehicle, in liters per hour. It can be used to specify consumption due to devices and systems such as AC systems, radio, heating, etc.
options.avoid
Array | String
default:None
Specifies something that the route calculation should try to avoid when determining the route.
Specifies something that the route calculation should try to avoid when determining the route. Can be specified multiple times. Possible values:
  • tollRoads: avoids toll roads.
  • motorways: avoids motorways.
  • ferries: avoids ferries.
  • unpavedRoads: avoids unpaved roads.
  • carpools: avoids routes that require use of a carpool (HOV/ High Occupancy Vehicle) lanes.
  • alreadyUsedRoads: avoids using the same road multiple times.
Most useful in conjunction with routeType=thrilling.
options.avoidAreas
Object[]
default:None
A list of shapes to avoid for planning routes.
A list of shapes to avoid for planning routes. Supported shapes include rectangles. Can contain one of each supported shapes element.
Example
tt.services.calculateRoute({
     locations: '52.37173,4.91015:52.36357,4.898046255',
     avoidAreas: [{
     southWestCorner: {latitude: 52.36391, longitude:4.90106},
     northEastCorner: {latitude: 52.36554, longitude:4.90767}
}]);

Supported point formats:

  • 'lat,lon'
  • {lat:111, lon:111}
  • {lat:111, lng:111}
  • {latitude:111, longitude:111}
  • {x:111, y:111}
  • {lat: function(), lng:function()}
options.avoidVignette
String | String[]
default:None
An array of country codes.
List of 3-character ISO 3166-1 alpha-3 country codes of countries in which all toll roads with vignettes are to be avoided. Toll roads with vignettes in countries not in the list are unaffected. It is an error to specify both avoidVignette and allowVignette.
options.computeBestOrder
Boolean
default:None
A flag to reorder the route waypoints to reduce the route length.
Reorders the route waypoints to reduce the route length. Yields best results when used in conjunction with routeType shortest. Possible values:
  • true (compute a better order, if possible; not allowed to be used in conjunction with a maxAlternatives value greater than 0; not allowed to be used in conjunction with circle waypoints). The response will include the optimized waypoint indices.
  • false (use the locations in the given order). Not allowed to be used in conjunction with routeRepresentation none.
options.computeTravelTimeFor
String
default:None
Setting 'all' provides additional information regarding travel times.
Specifies whether to return additional travel times using different types of traffic information (none, historic, live) as well as the default best-estimate travel time. Possible values:
  • none - do not compute additional travel times.
  • all - compute travel times for all types of traffic information. Specifying all results in the fields noTrafficTravelTimeInSeconds, historicTrafficTravelTimeInSeconds and liveTrafficIncidentsTravelTimeInSeconds being included in the summaries in the route response.
options.constantSpeedConsumptionInkWhPerHundredkm
Array
default:None
Colon-delimited list of ElectricConstantSpeedConsumptionPairs, e.g., an array of such pairs "60,7".
Specifies the speed-dependent component of consumption. Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a consumption curve. Consumption rates for speeds not in the list are found as follows:
  • By linear interpolation, if the given speed lies in between two speeds in the list.
  • By linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by the nearest two points in the list.
The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of that point is used without further processing. Consumption specified for the largest speed must be greater than or equal to that of the penultimate highest speed. This ensures that extrapolation does not lead to negative consumption rates. Similarly, consumption values specified for the two lowest speeds in the list cannot lead to a negative consumption rate for any lower speed. The minimum and maximum values described here refer to the valid range for the consumption values (expressed in kWh/100km).
options.constantSpeedConsumptionInLitersPerHundredkm
Array
default:None
Colon-delimited list of CombustionConstantSpeedConsumptionPairs, e.g., an array of such pairs "60,7".
Specifies the speed-dependent component of consumption. Provided as an unordered list of speed/consumption-rate pairs. The list defines points on a consumption curve. Consumption rates for speeds not in the list are found as follows:
  • By linear interpolation, if the given speed lies in between two speeds in the list.
  • By linear extrapolation otherwise, assuming a constant (ΔConsumption/ΔSpeed) determined by the nearest two points in the list.
The list must contain between 1 and 25 points (inclusive), and may not contain duplicate points for the same speed. If it only contains a single point, then the consumption rate of that point is used without further processing. Consumption specified for the largest speed must be greater than or equal to that of the penultimate highest speed. This ensures that extrapolation does not lead to negative consumption rates. Similarly, consumption values specified for the two lowest speeds in the list cannot lead to a negative consumption rate for any smaller speed. The minimum and maximum values described here refer to the valid range for the consumption values (expressed in l/100km).
options.consumptionInkWhPerkmAltitudeGain
Number
default:None
Electric energy in kWh
Specifies the electric energy in kWh consumed by the vehicle through gaining 1000 meters of elevation.
  • Note: It must be paired with recuperationInkWhPerkmAltitudeLoss.
  • Note: It cannot be used with accelerationEfficiency, decelerationEfficiency, uphillEfficiency or downhillEfficiency.
Minimum value: recuperationInkWhPerkmAltitudeLoss Maximum value: 500.0
options.currentChargeInkWh
Number
default:None
Specifies the current electric energy supply in kilowatt hours (kWh).
options.currentFuelInLiters
Number
default:None
Specifies the current supply of fuel in liters.
options.decelerationEfficiency
Number
default:None
Specifies the efficiency of converting kinetic energy to saved (not consumed) fuel when the vehicle decelerates (i.e., ChemicalEnergySaved/KineticEnergyLost). ChemicalEnergySaved is obtained by converting saved (not consumed) fuel to energy using fuelEnergyDensityInMJoulesPerLiter.
options.departAt
String
default:None
The properly formatted date with the time or 'now' value. Date cannot be in the past and has to follow ISO 8601 standard.
The date and time of departure from the origin point. Departure times, apart from now, must be specified as a dateTime. When a time zone offset is not specified, it will be assumed to be that of the origin point. The departAt value must be in the future. The departAt parameter cannot be used in conjunction with arriveAt.
options.downhillEfficiency
Number
default:None
Specifies the efficiency of converting potential energy to saved (not consumed) fuel when the vehicle loses elevation (i.e., ChemicalEnergySaved/PotentialEnergyLost). ChemicalEnergySaved is obtained by converting saved (not consumed) fuel to energy using fuelEnergyDensityInMJoulesPerLiter.
options.fuelEnergyDensityInMJoulesPerLiter
Number
default:None
Specifies the amount of chemical energy stored in one liter of fuel in megajoules (MJ). It is used in conjunction with the *Efficiency parameters for conversions between saved or consumed energy and fuel. For example, energy density is 34.2 MJ/l for gasoline, and 35.8 MJ/l for Diesel fuel.
options.hilliness
String
default:None
The level of hilliness on a thrilling route.
Degree of hilliness for thrilling route. Possible values: low, normal, high. This parameter can only be used in conjunction with routeType thrilling.
options.instructionsType
String
default:None
If a street number is sent in along with the request, the response may include the side of the street (Left/Right) and also an offset position for that street number.
If specified, guidance instructions will be returned (if available). Possible values:
  • coded : returns raw instruction data without human-readable messages.
  • text : returns raw instructions data with human-readable messages in plain text.
  • tagged : returns raw instruction data with tagged human-readable messages to permit formatting.
Note that the instructionsType parameter cannot be used in conjunction with routeRepresentation=none. If alternative routes are requested, instructions will be generated for each route returned.
options.key
String
default:None

A valid API Key for the requested service.


Key is required to make use of the given service. It can be issued in the Developer Portal.
options.language
String
default:None
The language value.
The language parameter determines the language of the guidance messages. It does not affect proper nouns (the names of streets, plazas, etc.) It has no effect when instructionsType=coded. Allowed values are (a subset of) the IETF language tags described here. The currently supported languages are listed in the supported languages section: Routing supported languages
options.locations
String | Array
default:None
These are the specified locations for route calculation.
Locations through which the route is calculated. The following constraints apply:
  • At least two locations must be provided.
  • The first location in the sequence defines the origin and must be of type 'point'.
  • The last location in the sequence defines the destination and must be of type 'point'.
  • One or more optional intermediate locations (known as waypoints) may be provided:
    • The maximum allowed number of waypoints is 150.
    • A point waypoint results in an extra leg in the response, a circle waypoint does not.
    • Circle waypoints cannot be used when computeBestOrder is true.
The points or circles that will be used to calculate the route. The following input types are allowed:
  1. A string with colon-delimited locations. For example '13.42936,52.50931:13.43872,52.50274' where comma divides longitude and latitude.
  2. An array containing locations. Location can be defined as a string, object, or array.
Note: Please keep in mind, that supportingPoints and 'Waypoints' (meaning more than two locations) are mutually exclusive. If you are using supportingPoints you can use only two locations.
options.maxAlternatives
Number
default:None
To restrict the maximum alternative routes to be calculated.
The number of desired alternative routes to be calculated. The value provided: Must be an integer in the range 0-5. Using a value greater than 0 in conjunction with computeBestOrder set to true is not allowed. Fewer alternative routes may be returned if either fewer alternatives exist or the requested number of alternatives is larger than the service can calculate. The default value is 0, the maximum value is 5.
options.maxChargeInkWh
Number
default:None
Specifies the maximum electric energy supply in kilowatt hours (kWh) that may be stored in the vehicle's battery.
options.minDeviationDistance
Number
default:None
Meters represented as a positive integer number.
Defines at least how far in meters the alternative routes have to follow the reference route. This option cannot be used in conjunction with arriveAt.
options.minDeviationTime
Number
default:None
Seconds represented as a positive integer number.
Defines at least how far in time (seconds) the alternative routes have to follow the reference route. This option cannot be used in conjunction with arriveAt.
options.protocol
String
default:None

Protocol type, one of http or https.


Represents the type of protocol used to perform the service call.
options.recuperationInkWhPerkmAltitudeLoss
Number
default:None
Electric energy in kWh
Specifies the electric energy in kWh gained by the vehicle through losing 1000 meters of elevation.
  • Note: It must be paired with consumptionInkWhPerkmAltitudeGain.
  • Note: It cannot be used with accelerationEfficiency, decelerationEfficiency, uphillEfficiency or downhillEfficiency.
Minimum value: 0.0 Maximum value: consumptionInkWhPerkmAltitudeGain
options.report
String
default:None
The level of a verbose answer from the service, useful for debugging purposes.
Specifies which data should be reported for diagnosis purposes. Possible values: effectiveSettings Reports the effective parameters or data used when calling the API. In the case of defaulted parameters, the default will be reflected where the parameter was not specified by the caller.
options.routeRepresentation
String
default:None
Allows the routing response to omit the actual route and give only the best ordered waypoints.
Specifies the representation of the set of routes provided as a response. Possible values:
  • polyline includes routes in the response.
  • none includes only the optimized waypoint indices but does not include the routes in the response.
This parameter value can only be used in conjunction with computeBestOrder 'true'.
options.routeType
String
default:'fastest'
The route type to be used during route calculation.
The type of route requested. Notes on specific values:
  • fastest returns the fastest route.
  • shortest returns the shortest route by distance.
  • eco routes balance economy and speed.
  • thrilling routes include interesting or challenging roads and use as few motorways as possible. You can choose the level of turns included and also the degree of hilliness. See the hilliness and windingness parameters to see how to set this. There is a limit of 900km on routes planned with routeType=thrilling.
The default value is fastest.
options.sectionType
String | String[]
default:None
An array of section types.
Specifies which of the section types is reported in the route response. Possible values:
  • carTrain, ferry, tunnel or motorway: get sections if the route includes car trains, ferries, tunnels, or motorways.
  • pedestrian: sections which are only suited for pedestrians.
  • tollRoad: sections which require a toll to be payed.
  • tollVignette: sections which require a toll vignette to be present.
  • country: countries the route has parts in.
  • travelMode: sections in relation to the request parameter 'travelMode'.
The default value is travelMode.
options.supportingPoints
String | String[] | Object | Object[]
default:None
Supporting points for route calculation.
Can be used to set supporting points for constructing (or reconstructing) a route and for calculating alternative routes to a base route. The provided sequence of supporting points is used as input for route reconstruction. Pseudo examples:
  • If the base route is A > B and we include a supporting point C, the result will be A > C > B;
  • Supporting points can be used to entirely reconstruct a route you previously had: Let us illustrate the problem. To go from A > B you received A > C > D > E > B. If later, you try to generate the same route (A > B), you might get different middle points. So, if you need to generate the exact same route you previously had you can do something like routing().locations(A, B).supportingPoints(C, D, E)
You can use one of the following input formats to define the supporting points:
  • String: '4.8,52.3' or '4.8,52.3:4.87,52.37'
  • String[]: ['4.8,52.3:4.87,52.37', '4.8,52.3:4.87,52.37']
  • Object: {lat: 52.3, lon: 4.8} or {lat: 53.3, lng: 5.8} or {x: 53.3, y: 5.8} or {latitude: 53.3, longitude: 5.8}
  • Object[]: [{lat: 52.3, lon: 4.8}] or [{lat: 53.3, lng: 5.8}]
How 'Supporting Points' differ from 'Waypoints?' - Waypoints are points where the calculated route will go through, but the resulting route might be different from search to search. The waypoints order might not necessarilly be respected when calculating the best route. Finally, there is a limit to the number of waypoints you can use in a route calculation. Supporting points can be used to entirely contruct a previous route, or parts of it, using the previously generated points. This means that there is no limit to the number of points, and the order of these points will be respected.

Note: Please keep in mind, that supportingPoints and 'Waypoints' (meaning more than two locations) are mutually exclusive. If you are using supportingPoints you can use only two locations. For more information please refer to the Routing API Docs
Example
tt.services.routing({
     locations: '4.8,52.3:4.87,52.37',
     supportingPoints: ['-7.164026,39.319843', '-6.16632,39.342266']
})
  .then(function(routeGeoJson) {
    console.log(routeGeoJson);
  });
options.trackingId
String
default:uuid

Sets value of "Tracking-ID" header.


Specifies an identifier for the request. If not set by the user, UUID is generated for each call.
  • It can be used to trace a call.
  • The value must match the regular expression '^[a-zA-Z0-9-]{1,100}$'.
  • An example of the format that matches this regular expression is UUID: (e.g. 9ac68072-c7a4-11e8-a8d5-f2801f1b9fd1). For details check RFC 4122.
  • If specified, it is replicated in the Tracking-ID Response header.
  • It is only meant to be used for support and does not involve tracking of you or your users in any form.
options.traffic
Boolean
default:true
A boolean flag determines if traffic data should be used to calculate the route.
Possible values:
  • true (do consider all available traffic information during routing)
  • false (ignores current traffic data during routing) Note that although the current traffic data is ignored during routing, the effect of historic traffic on effective road speeds is still incorporated.
The default is true.
options.travelMode
String
default:None
The primary means of transportation to be used while routing.
The travel mode for the requested route. Possible values: car, truck, taxi, bus, van, motorcycle, bicycle, pedestrian Note that the requested travelMode may not be available for the entire route. Where the requested travelMode is not available for a particular section, the element of the response for that section will be 'other'.
options.uphillEfficiency
Number
default:None
Specifies the efficiency of converting chemical energy stored in fuel to potential energy when the vehicle gains elevation (i.e., PotentialEnergyGained/ChemicalEnergyConsumed). ChemicalEnergyConsumed is obtained by converting consumed fuel to chemical energy using fuelEnergyDensityInMJoulesPerLiter.
options.vehicleAdrTunnelRestrictionCode
String
default:None
An ADR restriction code
If specified, the vehicle is subject to ADR tunnel restrictions.
  • Vehicles with code B are restricted from roads with ADR tunnel categories B, C, D, and E.
  • Vehicles with code C are restricted from roads with ADR tunnel categories C, D, and E.
  • Vehicles with code D are restricted from roads with ADR tunnel categories D and E.
  • Vehicles with code E are restricted from roads with ADR tunnel category E.
  • If vehicleAdrTunnelRestrictionCode is not specified, no ADR tunnel restrictions apply.
Notes:
  • If travelMode is pedestrian or bicycle, vehicleAdrTunnelRestrictionCode is not considered.
  • The vehicleAdrTunnelRestrictionCode and vehicleLoadType parameters are independent; please provide both if applicable.
options.vehicleAxleWeight
Number
default:None
The vehicle axle wight in kg (kilograms).
Weight per axle of the vehicle in kg (kilograms). A value of 0 means that weight restrictions per axle are not considered during route planning. This parameter is currently only considered for travelMode truck.
options.vehicleCommercial
Boolean
default:None
True if the vehicle is used for commercial purposes.
The vehicle is used for commercial purposes and thus may not be allowed to drive on some roads. This parameter is currently only considered for travelMode truck.
options.vehicleEngineType
String
default:None
The vehicle engine type.
Engine type of the vehicle. This parameter is currently only considered for travelMode truck. Valid options are: combustion, electric
options.vehicleHeading
Number
default:None
The angle in which the vehicle is heading.
The directional heading of the vehicle in degrees starting at true North and continuing in a clockwise direction. North is 0 degrees, East is 90 degrees, South is 180 degrees, West is 270 degrees. Possible values are 0-359.
options.vehicleHeight
Number
default:None
The vehicle height in meters.
Height of the vehicle in meters. A value of 0 means that height restrictions are not considered during route planning. This parameter is currently only considered for travelMode truck.
options.vehicleLength
Number
default:None
The vehicle length in meters.
Length of the vehicle in meters. A value of 0 means that length restrictions are not considered during route planning. This parameter is currently only considered for travelMode truck.
options.vehicleLoadType
Array | String
default:None
The array of truck cargo classification.
Types of cargo that may be classified as hazardous materials and restricted from some roads. Available vehicleLoadType values are US Hazmat classes 1 through 9, plus generic classifications for use in other countries. Use these for routing in US
  • USHazmatClass1 Explosives
  • USHazmatClass2 Compressed gas
  • USHazmatClass3 Flammable liquids
  • USHazmatClass4 Flammable solids
  • USHazmatClass5 Oxidizers
  • USHazmatClass6 Poisons
  • USHazmatClass7 Radioactive
  • USHazmatclass8 Corrosives
  • USHazmatClass9 Miscellaneous
Use these for routing in all other countries
  • otherHazmatExplosive Explosives
  • otherHazmatGeneral Miscellaneous
  • otherHazmatHarmfulToWater Harmful to water
This parameter is currently only considered for travelMode truck.
options.vehicleMaxSpeed
Number
default:None
The maximal allowed vehicle speed in km/h.
Maximum speed of the vehicle in km/hour. A value of 0 means that an appropriate value for the vehicle will be determined and applied during route planning. A non-zero value may be overridden during route planning. This parameter is currently only considered for travelMode truck.
options.vehicleWeight
Number
default:None
The vehicle weight in kg (kilograms).
Weight of the vehicle in kg. A value of 0 means that weight restrictions are not considered during route planning. This parameter is currently only considered for travelMode truck.
options.vehicleWidth
Number
default:None
The vehicle width in meters.
Width of the vehicle in meters. A value of 0 means that width restrictions are not considered during route planning. This parameter is currently only considered for travelMode truck.
options.windingness
String
default:None
The level of windingness on a thrilling route.
Level of turns for thrilling route. Possible values: low, normal, high. This parameter can only be used in conjunction with routeType thrilling.