Routing
Contents
Routing is done using Trimble Maps data for commercial vehicles. This data includes bridge heights and clearances, load limits, weight limits and allowances, one-way road designations, left-hand and dangerous turn restrictions, urban road classifications, as well as hazmat, truck-restricted, truck-designated and truck-prohibited roads.
Route
The first step in adding routes to your map is to create a new Route object, providing a RouteOptions object as a constructor parameter.
const myRoute = new TrimbleMaps.Route({
// Put your RouteOptions attributes here
});
Showing and Hiding Routes
You can set the visibility of the route to either true (visible) or false (hidden) using the setVisibility method. You can tell if the route is visible by calling the isVisible method, and you can toggle a route between visible and invisible using the toggleVisibility method.
myRoute.setVisibility(false);
console.log('isVisible:', myRoute.isVisible());
myRoute.toggleVisibility();
You can also mark a route active or inactive with setRouteState. When a route is inactive (setRouteState(false)), the route line and stop icons are visually dimmed.
myRoute.setRouteState(false); // inactive / dimmed
myRoute.setRouteState(true); // active
Route Options
RouteOptions requires an array of stops with at least two locations to generate a route path. A routeId is recommended when you will remove or update the route later; if omitted, the SDK generates one automatically.
Stops may be TrimbleMaps.LngLat values or StopOptions objects (for example to pass placeId, label, costs, or isViaPoint). When any stop uses StopOptions, the request is sent with HTTP POST.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
]
});
Example using StopOptions and a place ID:
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.652582, 40.401172),
{
lngLat: [-74.562582, 40.401172],
placeId: 'YOUR_PLACE_ID'
},
new TrimbleMaps.LngLat(-74.452582, 40.401172)
]
});
For the full list of routing and display options (vehicle type, truck dimensions, Hours of Service, region, and more), see the Route API reference and the Route Options example.
Adding the Route to a Map
A route can be added to a map by calling the addTo method on the route object.
myMap.on('load', function () {
myRoute.addTo(myMap);
});
Events
A route raises a series of events during loading and rendering. The primary events are routeloading and route. The routeloading event is raised when the calls are started and the route event is raised when the route is completely loaded and rendered. These events are useful for adding loading indicators. The routeloading event could fire before you start listening.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.629749, 40.26118)
]
});
myRoute.on('routeloading', function () {
console.log('loading route');
});
myRoute.on('route', function () {
console.log('route complete');
});
Other useful route events include:
| Event | Description |
|---|---|
error |
Fired when a route or report request fails. |
click |
Fired when the route line or a stop is clicked. |
mouseenter / mouseleave |
Fired when the pointer enters or leaves the route line or a stop. |
visibility |
Fired when route visibility changes. |
stopInserting |
Fired while dragging a route, before a stop is inserted (see Interactive Routes). |
Reports
The requested reports for a route can be retrieved by listening to the report event on the route object. The report event returns the reports specified in the reportType property in the route options. This event is raised each time the route is updated. There is also a corresponding reportloading event that is raised when a report call is started.
Reports are only requested when reportType is set to a non-empty array.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.629749, 40.26118)
],
reportType: [
TrimbleMaps.Common.ReportType.MILEAGE,
TrimbleMaps.Common.ReportType.DETAIL
]
});
myRoute.on('report', function (reports) {
console.log(reports);
});
ReportTypes
| ReportType | Description |
|---|---|
TrimbleMaps.Common.ReportType.ROAD |
The Road Report provides a distance breakdown by road category for each leg of the route. |
TrimbleMaps.Common.ReportType.MILEAGE |
The Mileage Report provides the distance, time, and cost for each stop on a route. It can be set to retrieve distances in miles (default) or kilometers. |
TrimbleMaps.Common.ReportType.DIRECTIONS |
The Directions Report provides turn-by-turn directions for a route. |
TrimbleMaps.Common.ReportType.DETAIL |
The Detailed Report provides a comprehensive report for each leg of the route. |
TrimbleMaps.Common.ReportType.STATE |
The State Report provides detailed mileage information for each state or country traveled through on the route. |
TrimbleMaps.Common.ReportType.TOLL |
The Toll Detail Report provides toll cost information for the route. Additional trailer and emissions options are available for European toll detail reporting. |
Interactive Routes
By default, routes are static. The route is drawn on the map and the stops are indicated by the appropriate icons. To let users move stops or drag the route path, set the isDraggable option on the route to true.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.499440),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
],
isDraggable: true
});
You can also enable or disable dragging after the route is created:
myRoute.setDraggable(true);
myRoute.setDraggable(false);
When a drag could insert a stop on more than one overlapping route leg, listen for stopInserting and choose the insertion position with getRouteWithNewStop:
myRoute.on('stopInserting', function (e) {
myRoute.getRouteWithNewStop(
e.newStop,
e.routeLegPositions[e.routeLegPositions.length - 1]
);
});
Drag Options
Using the dragOptions setting, dragging behavior can be further customized. By default, when the mouse button is released, the route path is redrawn to include the point precisely beneath the cursor. In version 3.3, the ability was added to instead snap the route path to a nearby road link or place that is visible at the current map zoom level. By default, with dragging enabled, you can activate this snapping behavior by holding the SHIFT key while dragging.
The snapMode can be set to OFF, DISABLE_WITH_KEY, or ENABLE_WITH_KEY. The snippet below enables snapping by default and deactivates it when the ALT key is held:
dragOptions: {
snapKey: TrimbleMaps.Common.SnapKey.ALT,
snapMode: TrimbleMaps.Common.SnapMode.DISABLE_WITH_KEY
}
When dragging a route, the road segment to be snapped to is highlighted and the icon changes.

When in snapping mode, if the mouse cursor is too far from any visible link, the icon changes to the “prohibited” symbol (a red circle with a backslash) to indicate snapping to that location is not possible. If the mouse button is released in this state, the route is not redrawn.
Stops introduced by drag routing are marked internally as via points. You can allow users to remove those drag-inserted stops by setting viaPointModifierKey. Hold that key and click the stop to remove it.
dragOptions: {
snapMode: TrimbleMaps.Common.SnapMode.ENABLE_WITH_KEY,
snapKey: TrimbleMaps.Common.SnapKey.SHIFT,
viaPointModifierKey: TrimbleMaps.Common.ViaPointModifierKey.ALT
}
Note: Prefer either the undo/redo stack or via-point removal—not both at the same time. Calling
updatewith a plain array of coordinates clears drag-generated via flags, so those stops can no longer be removed that way afterward. AfterdragOptionsis set, it cannot be changed withupdate.
Undo and Redo
For interactive routes, you can enable an undo/redo stack:
myRoute.enableRouteStack();
if (myRoute.canUndo()) {
myRoute.undo();
}
if (myRoute.canRedo()) {
myRoute.redo();
}
myRoute.disableRouteStack();
Hub Routing
Set hubRouting: true to enable hub routing. The origin is labeled as a hub (H), and remaining stops are numbered. When hub routing is enabled, drag routing and route optimization are disabled.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
hubRouting: true,
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.528512, 40.386680),
new TrimbleMaps.LngLat(-74.629749, 40.26118)
]
});
Via Points
A via point (sometimes called a waypoint) influences the route path so it passes through a specified location without acting as a full stop for pickup, delivery, or rest.
You can send a via point on the route request by using StopOptions with isViaPoint: true. That value is passed through to the routing service as IsViaPoint. On the map, intermediate stops—including drag-inserted via points—are drawn with the standard numbered stop marker unless you hide default stops and supply custom styling.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
{ lngLat: [-74.65, 40.36] },
{ lngLat: [-74.42, 40.52], isViaPoint: true },
{ lngLat: [-73.99, 40.75] }
]
});
With hubRouting: true, via points are still sent on the request but are drawn like other numbered stops in hub mode.
See also Drag Options for viaPointModifierKey, which removes stops introduced by drag routing.
Remove Route
You can remove individual routes by calling the remove method. The route line and stop icons are removed altogether.
myRoute.remove();
Update Route
After a route is added, it can be updated by calling the update method. This method can update the stops for a route and several display settings, including:
- Route path color, opacity, and width
- Dashed-line styling (
routeDasharray/lineOptions) - Stop image icons (preferably PNG), icon size, icon offset, and icon/text opacity
- Route arrows (
showArrows/arrowOptions) - Whether the route is draggable (
isDraggable)
It cannot be used to change the built-in stop text label, text offset, or text size. Options such as showStops, frameOptions, and dragOptions are fixed after construction and are not changed by update.
myRoute.update({
routeId: 'myRoute',
routeColor: '#888',
routePathOpacity: 0.8,
showArrows: true
});
Route Arrows
Turn on or off arrows indicating the direction of travel along the route. Optionally customize appearance with arrowOptions.
myRoute = new TrimbleMaps.Route({
// ...
showArrows: true,
// arrowOptions: { /* spacing, size, fillColor, etc. */ }
});
Dashed Route Lines
You can draw the route path as a dashed line with routeDasharray, or through lineOptions (which can also set lineCap and lineJoin).
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
],
// Preset or custom dash pattern:
routeDasharray: 'dash', // or e.g. [2, 4]
// Or:
// lineOptions: {
// routeDasharray: [2, 4],
// lineCap: TrimbleMaps.Common.LineCap.ROUND,
// lineJoin: TrimbleMaps.Common.LineJoin.ROUND
// }
});
Route Framing
By default, the map shifts and zooms to frame a route (unless frameRoute is set to false). You can change framing behavior with frameOptions. After frameOptions is set, it cannot be changed with update.
myRoute = new TrimbleMaps.Route({
// ...
frameRoute: true,
frameOptions: {
animate: false,
padding: { top: 150, bottom: 150, left: 450, right: 150 }
}
});
You can also frame the route later by calling frame():
myRoute.frame();
Customize Route Stops
If more control over route stop styling is desired, construct a route with showStops set to false. You can then add custom stop icons using addStopIcon and style them using styleStopIcons. After showStops is set, it cannot be changed.
addStopIcon accepts a stopType of 'start', 'end', or 'stop'.
const showDefaultStops = false; // false allows custom stop icons
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.528512, 40.386680),
new TrimbleMaps.LngLat(-74.629749, 40.26118)
],
showStops: showDefaultStops
});
myMap.on('load', function () {
myRoute.addTo(myMap);
if (!showDefaultStops) {
myRoute.addStopIcon('start', 'https://developer.trimblemaps.com/maps-sdk/img/marker_blue.png');
myRoute.addStopIcon('end', 'https://developer.trimblemaps.com/maps-sdk/img/marker_blue.png');
myRoute.addStopIcon('stop', 'https://developer.trimblemaps.com/maps-sdk/img/marker_blue.png');
// For detailed information, see https://developer.trimblemaps.com/maps-sdk/style-spec/layers/#symbol
const stopLayerStyle = {
layout: {
'icon-size': [
'case',
['==', ['get', 'stopType'], 'start'], 0.5, // stopType: start, end, or stop
['==', ['get', 'stopType'], 'end'], 0.5,
0.4 // intermediate stops
],
'icon-offset': [0, -30]
}
};
myRoute.styleStopIcons(stopLayerStyle);
}
});
For more information about routing options that are available, see the Routing documentation and Route Options example.
Data Versions
The JavaScript Maps SDK can request routes and reports for a specific data version by setting dataVersion on RouteOptions (for example a regional current version or a PCM version such as PCM37). Region is controlled with region.
const myRoute = new TrimbleMaps.Route({
routeId: 'myRoute',
region: TrimbleMaps.Common.Region.NA,
dataVersion: 'PCM37',
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
],
reportType: [TrimbleMaps.Common.ReportType.MILEAGE]
});
If you need to call the RESTful APIs directly (for example from outside the SDK, or to use request shapes that differ between GET and POST), full details are in the RESTful APIs documentation. Remember that GET and POST requests can use different parameter names and structures.
Below is an example of retrieving a mileage report for an older data version (PCM29) using fetch, alongside an SDK route for the current data version.
const stopArray = [
new TrimbleMaps.LngLat(-74.566234, 40.459440),
new TrimbleMaps.LngLat(-74.635242, 40.358839),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
];
myMap.once('load', () => {
const myRoute = new TrimbleMaps.Route({
routeId: 'route1',
stops: stopArray,
reportType: [TrimbleMaps.Common.ReportType.MILEAGE]
}).addTo(myMap);
myRoute.once('report', (data) => {
console.log('--- Current Data Version ---');
console.log(`${data[0].ReportLines[2].TMiles} Miles`);
});
const baseUrl =
'https://pcmiler.alk.com/APIs/REST/v1.0/service.svc/route/routeReports';
// GET
const getParams = [];
getParams.push(
`stops=${encodeURIComponent(
stopArray.map((stop) => stop.toArray().join(',')).join(';')
)}`
);
getParams.push('reports=Mileage');
getParams.push('dataVersion=PCM29');
fetch(`${baseUrl}?${getParams.join('&')}`, {
method: 'GET',
headers: {
Authorization: 'YOUR_KEY_HERE'
}
})
.then((response) => response.json())
.then((data) => {
console.log('--- PCM29 Data Version (GET) ---');
console.log(`${data[0].ReportLines[2].TMiles} Miles`);
});
// POST
const postParams = {
ReportRoutes: [
{
Stops: stopArray.map((stop) => {
return {
Coords: {
Lat: stop.lat,
Lon: stop.lng
}
};
}),
Options: {
HighwayOnly: false // match GET default; see REST route reports overview
},
ReportTypes: [
{
__type: 'MileageReportType:http://pcmiler.alk.com/APIs/v1.0'
}
]
}
]
};
fetch(`${baseUrl}?dataVersion=PCM29`, {
method: 'POST',
headers: {
Authorization: 'YOUR_KEY_HERE',
'Content-Type': 'application/json'
},
body: JSON.stringify(postParams)
})
.then((response) => response.json())
.then((data) => {
console.log('--- PCM29 Data Version (POST) ---');
console.log(`${data[0].ReportLines[2].TMiles} Miles`);
});
});