Skip to main content

Routing

Contents

Routing is done using Trimble Maps data specifically designed 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.

Routing Layer

The first step in generating routes is to add a routing layer to your map. The routing layer will be responsible for both retrieving and drawing the routes based on the stops and properties you define.

var routingLayer = new ALKMaps.Layer.Routing("Route Layer");
myMap.addLayer(routingLayer);

Add Route

Once you have a routing layer added to your map, the next step is to add routes. To generate a route you will need at least two stops (an origin and a destination).

The addRoute method of the routing layer takes up to four parameters for creating a route: stops, functionOptions, routeOptions, and reportOptions.

Please note that the addRoute callback will return stops as an array of ALKMaps.Geometry.Point objects, and the coordinates will be in meters if your map is in Spherical Mercator. Previously the format of stops array in the return object was [[lon,lat],[lon,lat],...], and the coordinates were always in degrees regardless of map projection.

You also have the ability to transform entire arrays of ALKMaps.LonLat or ALKMaps.Geometry.Point objects to another projection. This can be done by passing an array followed by the source and destination projections to either the ALKMaps.LonLat.transformArray or ALKMaps.Geometry.Point.transformArray functions.

Stops

The stops parameter of the addRoute method should contain an array of ALKMaps.LonLat objects representing the stops of the route.

Function Options

The functionOptions parameter contains options related to the functionality of the route.

PropertyTypeDescription
routeIdstringA unique string values used to identify a route. It is needed when removing or updating a route.
asyncbooleanDefault: true
Determine whether the route request will be asynchronous. If so, a callback function can be specified.
If a type of web browser, like IE, uses XDomainRequest to issue HTTP request, it is required to make asynchronous calls due to limitations of the browser.
successfunctionFunction to be called on the success of the asynchronous routing request. The callback function will be passed a results object that contains the id, stops, and the reports.
Function name “callback” has been deprecated.
failurefunctionFunction to be called when error happens.
styleALKMaps.StyleMap{strokeColor: "#00C000", strokeOpacity: 0.6}
Currently, strokeOpacity and strokeColor are the supported styling options.
Note: See Route Colors for more information.
frameRoutebooleanDefault: true
Indicates whether the center point and zoom level of the map will be adjusted to show the route in full frame.
showHandlesbooleanDefault: true
Indicates whether to show the origin/waypoint/destination graphics.

Route Options

The routeOptions parameter contains options related to the generation of the route and optional reports.

ParameterType/ValuesDescription
vehicleType[0 | 1 | 2 | 3| 4 ] Default: 0
Restricts the route to roads that are accessible by the selected vehicle type.
  • 0 - Truck (Default)
  • 1 - Light Truck
  • 2 - Automobile
  • 3 - Midsize Truck
  • 4 - School Bus
routingType[0 | 1 | 2] Default: 0
Generated the route to match the type.
  • 0 - Practical
  • 1 - Shortest
  • 2 - Fastest
routeOptimization[0 | 1 | 2] Default: 0
  • 0 - None
  • 1 - Optimize All Stops
  • 2 - Optimize Intermediate Stops
tollDiscourageboolean Default: false
Generates the route by trying to avoid toll roads.
tollRoads[1 | 2 | 3] Default: Null
Indicates whether or not to avoid toll roads when generating a route. If this parameter is specified, the value in tollDiscourage will be ignored. If this parameter is null, the value in tollDiscourage will be used. Available in dataVersion PCM34 and higher. Use tollDiscourage for older versions.
  • 1 - Always Avoid
  • 2 - Avoid if Possible
  • 3 - Use
classOverrides[0 | 1 | 2] Default: 0
  • 0 - Indicates that no class overrides are present.
  • 1 - Indicates a 53' class override.
  • 2 - Indicates a National Network class override.
  • 3 - Indicates a 53' and National Network class override.
bordersOpenboolean Default: true
Set to True to allow international border crossings, False to avoid or reduce number of international border crossings. For example, if all your stops are in the “lower 48” United States, the resulting route will stay in the United States even if the most practical or shortest route would normally involve some Canadian mileage. For EU travel, setting this to False will reduce the number of EU border crossings where possible and the route will follow the best path within the country from which the route originates.
overrideRestrictboolean Default: false
Indicates whether or not to override truck restrictions
highwayOnlyboolean Default: false
Restricts the route to only highway roads.
hazMatTypeArray of [0 | 1 | 2 | 3 | 4 | 5 | 6 | 7] Default: 0
Restricts the route to roads that allow transportation of the selected hazardous material.
North America
  • 0 - None
  • 1 - General
  • 2 - Caustic
  • 3 - Explosives
  • 4 - Flammable
  • 5 - Inhalants
  • 6 - Radioactive
Europe
  • 0 - None
  • 1 - General
  • 3 - Explosives
  • 4 - Flammable
  • 7 - HarmfultoWater
tunnelCategoryArray of [0 | 1 | 2 | 3 | 4] Default: 0
Indicates the tunnel categories, which are applicable for EU region only.
  • 0 - None
  • 1 - TunnelBCDE
  • 2 - TunnelCDE
  • 3 - TunnelDE
  • 4 - TunnelE
sideOfStreetAdherence[0 | 1 | 2 | 3 | 4 | 5 | 6] Default: 0
How strict to be in order to avoid the destination being on the opposite side of the street.
  • 0 - Off
  • 1 - Minimal
  • 2 - Moderate
  • 3 - Average
  • 4 - Strict
  • 5 - Adhere
  • 6 - Strongly Adhere
governorSpeedLimitnumberMaximum average road speed to use in route calculations that overrides all other road speeds when they are above this value. Default is disabled and valid value is between 1 and 100 mph or 1 and 161 kph based on distanceUnits.
avoidStateArray of string Default: empty list
A comma-separated list of ISO2 codes for states that should be avoided when generating a route. Default is an empty list. This parameter is for North America only. Available in PCM34 and higher. Examples: ['NJ', 'PA']
avoidCountryArray of string Default: empty list
A comma-separated list of ISO2 codes for countries that should be avoided when generating a route. Default is an empty list. Available in PCM34 and higher. Examples: ['BE', 'AT']
favorStateArray of string Default: empty list
A comma-separated list of ISO2 codes for states that should be favored when generating a route. Default is an empty list. This parameter is for North America only. Available in PCM34 and higher. Examples: ['NJ', 'PA']
favorCountryArray of string Default: empty list
A comma-separated list of ISO2 codes for countries that should be favored when generating a route. Default is an empty list. This parameter is for regions outside of North America. Available in PCM34 and higher. Examples: ['BE', 'AT']
distanceUnits[0 | 1] Default: 0
Distance units as miles or kilometers.
  • 0 - Miles
  • 1 - Kilometers
trkUnits[0 | 1] Default: 0
Vehicle dimension units; can be English or Metric.
  • 0 - Indicates that vehicle dimension units should be English, e.g., 13'6".
  • 1 - Indicates that vehicle dimension units should be metric.
trkHeightnumberThe height of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148.
trkLengthnumberThe length of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148.
trkWidthnumberThe width of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148.
trkWeightnumberThe weight of the vehicle in pounds or kilograms depending on units.
trkAxlesnumber Default: 5
The number of axles on the vehicle; acceptable values are 2 through 14.
inclFerryDistboolean Default: true
Indicates whether or not to include ferry distances in mileage calculations.
Note: This parameter is only used for Reports
fuelUnits[0 | 1] Default: 0
Fuel units as gallons and liters.
  • 0 - Gallons
  • 1 - Liters
Note: This parameter is only used for Reports
truckConfig[0 | 1 | 2 | 3 | 4| 5| 6| 7| 8] Default: 0
The vehicle style.
  • 0 - Indicates that no particular vehicle style is chosen.
  • 1 - 28' Double Trailer.
  • 2 - 40' Straight Truck.
  • 3 - 48' Semi-Trailer.
  • 4 - 53' Semi-Trailer
  • 5 - Full Size Van
  • 6 - 26' Straight Truck
  • 7 - Conventional School Bus (NA Only)
  • 8 - Small School Bus (NA Only)
inclTollDataboolean Default: true
Indicates whether or not reports should calculate toll costs.
Note: This parameter is only used for Reports
fuelEconLoadnumber The fuel efficiency (distance units per fuel units) when loaded.
Note: This parameter is only used for Reports
fuelEconEmptynumber The fuel efficiency (distance units per fuel units) when empty.
Note: This parameter is only used for Reports
costPerFuelUnitnumber The cost per fuel unit of fuel.
Note: This parameter is only used for Reports
costGHGnumber The cost of greenhouse gas in lbs. per fuel unit.
Note: This parameter is only used for Reports
costMaintLoadnumber The maintenance cost per distance unit when loaded.
Note: This parameter is only used for Reports
costMaintEmptynumber The maintenance cost per distance unit when empty.
Note: This parameter is only used for Reports
costTimeLoadnumber The time cost per mile/km when loaded.
Note: This parameter is only used for Reports
costTimeEmptynumber The time cost per mile/km when empty.
Note: This parameter is only used for Reports
tollCurrency[0 | 1] Default: 0
The toll currency.
  • 0 - Indicates that the currency should be United States dollars.
  • 1 - Indicates that the currency should be Canadian dollars.
Note: This parameter is only used for Reports
exchangeRatenumber The change rate to convert US dollars to Canadian dollars.
Note: This parameter is only used for Reports
tollPlanString The toll discount plan which is a comma-separated list of toll discount programs. Use All for everything otherwise valid values are (407ETR Transponder,A25 Transponder,BreezeBy,C-Pass,Cruise Card,E-Pass,E-Pass Canada,EXpress Toll,EZ Tag,EZPass,EZPass-NJ,EZPass-WV,FAST LANE,FasTrak,GeauxPass,Good To Go,GO-PASS,I-Pass,I-Zoom,K-TAG,Laredo Trade Tag,LeeWay,MACPASS,NC Quick Pass,NEXPress,Palmetto Pass,Peach Pass,PikePass,Quickpass,Smart Tag,StraitPASS,SunPass,TollTag,TxTag,Wabash Pass)
citeIntnumber The cite interval to be used when generating a geotunnel report. The minimum value is 0.1.
Note: This parameter is only used for Reports
estimatedTimeOptsString Estimated time options allow you to specify either a day of the week or a specific date and the time for which you would like you depart from your origin or arrive at your destination.
Format: [Depart/Arrive]|[SpecificDateTime/(DayOfWeek|TimeOfDay)].
Ex: Depart|Monday|18:30 to depart given day of week and time of day; or Arrive|2014-03-04T08:15:30-05:00 to arrive at specific date/time, or Arrive or Depart to arrive or depart with system time.
Note: This parameter also determines the results for the WeatherAlerts report by only returning alerts that are effective within the timespan of the route.
urgency [All | Extreme | Severe
| Moderate | Minor | Unknown]


Default: All
The alert urgency filter to be used when generating a weather alerts report.
Note: This parameter is only used for Reports
severity [All | Immediate | Expected
| Future | Past | Unknown]


Default: All
The alert severity filter to be used when generating a weather alerts report.
Note: This parameter is only used for Reports
certainty [All | Observed | Likely
| Possible| Unlikely | Unknown]


Default: All
The alert certainty filter to be used when generating a weather alerts report.
Note: This parameter is only used for Reports
eventNamesArray{String} Such as ["Winter Storm Warning", "Flood Watch"]
Used when generating a weather alerts report. Weather alert events with exact matching names will be returned.

Default: NULL (return all alerts)
Note: This parameter is only used for Reports
useTrafficBooleanIndicates whether or not to use traffic data. When set to true, the routing algorithm will consider traffic closures when selecting the route and use historical traffic patterns to calculate the trip’s ETA and travel time. If set to true, and the trip’s departure time is also set to within 15 minutes of the current time, real-time traffic data will be used for the first 15 miles and historical traffic patterns will be used for the remainder of the route. (By default, useTraffic is false, and ETA and travel time are computed using Trimble Maps’s average road speeds by road class.)


Traffic data is only used to select the route path a truck will take when the routing algorithm (routeType) is set to Fastest. (Fastest routing is recommended for autos and vans only.)

elevLimitNumber Indicates the elevation limit when generating a route. Elevation unit can be either meters or feet is determined by the {distUnits} parameter. Miles = feet, Kilometers = meters. Available for dataversions Current, PCM_NA, PCM29 and beyond. Limit will be ignored if: Routing is deemed impractical with the limit, or a stop is located at an elevation higher than the limit.

Default: null
ferryDiscourageBoolean Indicates whether or not to discourage the use of ferries when creating the route.

Default: false
afSetIDsArray{Number}The avoid/favor set ids to apply to the route.
region [NA | EU | OC | SA
| AS | AF | ME]
Default: NA
The data region in which the route stops are located.
Note: If region is not provided, region value will be inherited from baseLayer region parameter.
useSitesBoolean Indicates whether to use sites as part of the route calculation. If useSites is enabled and any of the stops on the route fall within an ALK site or applicable customer site, then the route itself will be affected by those sites. Entry / exit gates to / from that stop will be added as part of the route. Eventually the preferred first mile / last mile route path and reports will be affected.

Default: false
Note: Site path will not be returned as part of route visualization.

Report Options

ParameterType/ValuesDescription
type [Mileage | Directions | Detail | State |
CalcMiles | LeastCost | Geotunnel | WeatherAlerts | TollDetail]
Comma-separated list of requested report types.
Note:
You must have Weather Alerts permissions in order to get the WeatherAlerts report.
TollDetail report is for EU region only and it requires the trailer dimensions to be supplied in report options.
format[json | html] Default: json
The format of the report returned with the route.
dataVersion [Current | PCM_EU | PCM_OC | PCM_SA |
PCM_GT | PCM_AF | PCM_AS | PCM_ME | PCM_JP
and PCM18 through the current version number
Default: current
The data version against which this request should be performed.
Note: Reports might be different from the route if data versions 18 to 22 are used.
lang [ENUS (English United States) |
ENGB (English Great Britain) | DE (German) |
FR (French) | ES (Spanish) | IT (Italian)]
Default: ENUS
The language of the report returned with the route.
condenseDirsBoolean Default: false
Indicate whether or not to get the condensed version of the directions report.
trlTypeString Default: None
Type of the trailer. Available values are None, Caravan, Trailer.
Note:
This parameter is for EU TollDetail report only.
trlMaxWtNumber Max weight of the trailer in pounds or kilograms depending on units.
Note:
This parameter is for EU TollDetail report only.
trlMaxHtNumber or String Max height of the trailer in feet and inches, or meters depending on units.
Note:
This parameter is for EU TollDetail report only.
trlMaxAxlesNumber Default: 1
Max number of axles on the trailer. Acceptable values are 1 - 8.
trlCountNumber Default: 0
Number of trailers and semi-trailers. Note:
This parameter is for EU TollDetail report only.
isHybridBoolean Default: false
Indicates whether vehicle has a hybrid engine. Note:
This parameter is for EU TollDetail report only.
minPollBoolean Default: false
Indicates whether the vehicle is a minimum vehicle pollution. Note:
This parameter is for EU TollDetail report only.
emiTypeString The emission type of the engine. Available values are Euro0, EuroI, EuroII, EuroIII, EuroIV, EuroV, EuroVI, EuroEEV. Note:
This parameter is for EU TollDetail report only.

Remove Route

You can remove individual routes in a particular routing layer by calling the removeRoute method with the routeId of the route you would like to remove.

routingLayer.removeRoute("myRoute");

Set Route Visibility

You can set the visibility of individual routes in a particular routing layer by calling the setRouteVisibility method with the routeId of the route as the first parameter and a boolean indicating whether or not the route should be visible as the second. True indicates that the route should be shown, and false indicates that the route should be hidden.

routingLayer.setRouteVisibility("myRoute", false); //hides the route

Interactive Routes

By default, routes are static. The route will be drawn on the map and the stops will be indicated by the appropriate markers. If you would like to your users to interact with the routes by moving the location of a stop or dragging the routes, you just need to set the isDraggable property of the routing layer in the constructor to true.

var routingLayer = new ALKMaps.Layer.Routing("Route Layer", {
  isDraggable: true
});
myMap.addLayer(routingLayer);

The interactivity of a routing layer can also be set dynamically by calling the setDraggable method on an existing routing layer.

routingLayer.setDraggable(false);

Once the user has moved around the stops, you may want to retrieve the new location of the stops, as well as any new stops that may have been created while dragging. The get this information you will need to use the getRouteElements method on the routing layer. This method take the routeId of the route.

var routeElements = routingLayer.getRouteElements("PhiladelphiaToAtlanticCity");

var numberOfStops = routeElements.stops.length;

for (var i = 0; i < numberOfStops; i++) {
  console.log("Stop " + i);
  console.log("Lon: " + routeElements.stops[i].geometry.x);
  console.log("Lat: " + routeElements.stops[i].geometry.y);
}

Route Handles

The route handles (icons displayed at the origin, destination, and waypoints) can be shown/hidden or changed.

Visibility

The visibility of route handles can be set when the route is added via the showHandles option in the functionOptions of the addRoute call.

routingLayer.addRoute({
...
    functionOptions:{
      routeId: "PhiladelphiaToAtlanticCity",
      showHandles: false
    },
    ...
});

The visibility can also be changed after the route has been created via a call to the setRouteHandleVisibility on the routing layer. The function takes the routeId and a boolean value indicating the visibility as parameters.

routingLayer.setRouteHandleVisibility("PhiladelphiaToAtlanticCity", false);

Graphics

In addition to being hidden, the route handle graphics can be changed via the setRouteHandle function on the routing layer or by using the externalImages parameter of addRoute. Changes to the route handle graphics only affect handles that are currently part of the route. Handles added after the graphic change will need to be set after they are added.

routingLayer.setRouteHandle("MyRoute", "O", {
  externalGraphic: "https://maps.alk.com/api/1.2/img/fav.png"
});

The only field of the externalImages object is images, an array of image locations that at each index matches up to the corresponding element of the stops array. To use the ALKMaps default image for only certain handles, simply place null at that index of the images array.

routingLayer.addRoute({
  stops: ALKMaps.LonLat.transformArray([
    new ALKMaps.LonLat(-75.173297, 39.942892),
    new ALKMaps.LonLat(-74.83153, 39.61703),
    new ALKMaps.LonLat(-74.83153, 39.45703),
    new ALKMaps.LonLat(-74.438942, 39.362469)
    ], new ALKMaps.Projection("EPSG:4326"), map.getProjectionObject()),
    externalImages:
    {
      images: [ALKMaps.IMAGE.TRUCK_BLUE, ALKMaps.IMAGE.FAVORITE, null, ALKMaps.IMAGE.TRUCK_GREEN]
    },
  ...

});

SVG

You now have the ability to specify custom SVG content to render your route handles using the handleSvg property of the functionOptions parameter of addRoute. The available properties of the handleSvg object are explained in the table below.

PropertyTypeDescription
contentStringA string containing an SVG element.
sizeALKMaps.SizeSize of the SVG element. The default size is the bounding box of the element.
offsetALKMaps.PixelThe offset of the SVG element. Default ALKMaps.Pixel(width/2, height/2)

Route Colors

Different route colors are generated by the toolkit for each new route created. If you would like to specify a particular color for a route, you can pass in the color as a style object when the route is created.

routingLayer.addRoute({
  ...
  functionOptions:{
    routeId: "PhiladelphiaToAtlanticCity",
    style: {
      strokeOpacity: 0.9,
      strokeColor: "#0000FF"
    }
  },
  ...
});

Route Arrows

You now have ability to either have arrows spaced evenly along your route, or have a single arrow placed at the end of your route. These arrows are customizable in terms of style, spacing, and size. Everything is done through the style parameter inside the functionOptions of the addRoute function call. The settings/options are laid out in the table below.

PropertyType/ValuesDescription
arrows"line"/"end"/nullThis setting is used to enable the arrow functionality and indicate whether arrows should be placed along the line (“line”), or if a single arrow should be placed at the end of the route (“end”). The default value for this setting is null, which indicates that NO arrows should be drawn on the route.
arrowSizenumber/stringThe size of the arrow(s) either as a number representing the point radius of the arrow, or a string indicating the size of the arrow as a percentage of the route line’s stroke width. Default “100%”.
arrowSpacingnumberFor “line” arrows only. The distance in pixels between arrows along the route. Default is 100.
arrowStrokeColorstringHex stroke color. Used as the color for the outline of the arrow(s). Default is “black”.
arrowStrokeWidthnumberPixel stroke width. Used as the thickness for the outline of the arrow(s). Default is 1.
arrowStrokeOpacitynumberStroke opacity (0-1). Used as the opacity for the outline of the arrow(s). Default is 1.
arrowFillColorstringHex fill color. Used as the color for the inside of the arrow(s). Default is “white”.
arrowFillOpacitynumberFill opacity (0-1). Used as the opacity for the inside of the arrow(s). Default is 1.

Arrows Along Route

The following piece of sample code demonstrates a route with arrows spaced at 50 pixels and sized at “100%”.

Arrow at End of Route

The following piece of sample code demonstrates a route with a single arrow at the end of the route sized at “250%”.

Last updated October 27, 2022.
Contents