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 checking the isVisible
property, and you can toggle a route between visible and invisible using the toggleVisibility
method.
myRoute.setVisibility(false);
console.log('isVisible:', myRoute.isVisible());
myRoute.toggleVisibility();
Route Options
The RouteOptions object requires a routeId and an array of stops. There are a number of optional parameters that can also be provided in order to change the route path or the way it is displayed.
const myRoute = new TrimbleMaps.Route({
routeId: "myRoute",
stops: [
new TrimbleMaps.LngLat(-74.566234, 40.49944),
new TrimbleMaps.LngLat(-74.629749, 40.261187)
]
});
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 will raise a series of events during the loading and rendering of the route. The primary events are the 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 can be useful for adding loading indicators to your application. 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");
});
Reports
The requested reports for a route can be retrieved by listening to the report
event on the route object. The report event will return an object containing all the reports specified in the reportType
property in the route options. This event will be raised each time the route is updated.
There is also a corresponding reportloading
event that is raised when a report call is started.
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);
});
Interactive Routes
By default, routes are static. The route will be drawn on the map and the stops will be indicated by the appropriate icons. If you would like to your users to interact with the routes by moving the location of a stop or by dragging the routes, you just need to set the isDraggable
option of the routing layer in the constructor 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
})
Drag Options
Using the dragOptions
setting, dragging behavior can be further customized. By default, when the mouse button is released, the route path will be redrawn to include the point precisely beneath the cursor. In version 3.3, we introduced the ability 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 either be set to OFF
, DISABLE_WITH_KEY
, or ENABLE_WITH_KEY
. The code snippet below changes the default behavior. It 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.
Remove Route
You can remove individual routes by calling the remove
method. Route line and stop icons will be removed all together.
myRoute.remove();
Update Route
After a route is added, it can be updated by calling the update
method. This method can be used to update the number of stops for a route. It can also be used to update a limited selection of route display styles, including route color, stop image icons (preferably in .PNG format), icon size and icon offset. It can’t be used to change the text label, text offset, or text size.
myRoute.update({
routeId: 'myRoute',
routeColor: '#888'
});
Route Arrows
Turn on or off arrows indicating the direction of travel along the route.
myRoute = new TrimbleMaps.Route({
...,
showArrows: true,
...
});
Route Framing
By default, the map will shift and zoom to frame a route. You can change that behavior by setting the frameOptions
.
myRoute = new TrimbleMaps.Route({
...,
frameOptions: {
animate: false,
padding: {top: 150, bottom: 150, left: 450, right: 150}
},
...
});
Customize Route
If more control over route stops styling is desired, instead of using the update
method, construct a route with showStops
set to false. You can then add custom stop icons using the addStopIcon
method and style them using the styleStopIcons
method.
const showDefaultStops = false; // If false, custom stop icons can be used, if other values, default icons and styles are used.
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) {
// add custom stop icons.
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');
// style custom stop icons. For detailed information, visit https://developer.trimblemaps.com/maps-sdk/style-spec/layers/#symbol
const stopLayerStyle = {
layout: {
'icon-size': [
'case',
['==', ['get', 'stopType'], 'start'], 0.5, // stopType is an internal property, it has start, end, and stop values for now.
['==', ['get', 'stopType'], 'end'], 0.5,
0.4 // stops
],
'icon-offset': [0, -30]
}
};
myRoute.styleStopIcons(stopLayerStyle);
}
});
For more information about routing options that are available take a look at our Routing Documentation and Route Options Example
Previous Data Versions
The JavaScript Maps SDK is designed to visualize routes based on the current data version. If you need to generate reports based on older data versions, this should be done by calling the RESTful APIs (Web Services) directly.
Full details about the endpoints and parameters can be found in the RESTful APIs documentation. Remember that GET and POST requests can use different parameter names and structures.
Below is an example of how to retrieve a mileage report for an older data version (PCM29) using the JavaScript fetch API. The example includes both GET and POST methods.
// Array of stops to be used in all report calls
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', ()=> {
// Create Route for Current data version
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 Call
const getParams = [];
getParams.push(`stops=${encodeURIComponent(stopArray.map((stop) => stop.toArray().join(',')).join(';'))}`);
getParams.push('reports=Mileage');
getParams.push('dataVersion=PCM29');
// Add the parameters as a query string to the URL
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 Call
const postParams = {
ReportRoutes: [{
Stops: stopArray.map((stop) => {
return {
Coords: {
Lat: stop.lat,
Lon: stop.lng
}
}
}),
Options: {
HighwayOnly: false // Setting the HighwayOnly property to match the default of the GET call (see https://developer.trimblemaps.com/restful-apis/routing/route-reports/overview/)
},
ReportTypes: [{
__type: "MileageReportType:http://pcmiler.alk.com/APIs/v1.0"
}]
}]
};
// Add the dataVersion to the URL
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`);
});
});