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.
Property | Type | Description |
---|---|---|
routeId
| string
| A unique string values used to identify a route. It is needed when removing or updating a route. |
async
| boolean
| Default: 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. |
success
| function
| Function 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. |
failure
| function
| Function to be called when error happens. |
style
| ALKMaps.StyleMap
| {strokeColor: "#00C000", strokeOpacity: 0.6} Currently, strokeOpacity and strokeColor are the supported styling options. Note: See Route Colors for more information. |
frameRoute
| boolean
| Default: true Indicates whether the center point and zoom level of the map will be adjusted to show the route in full frame. |
showHandles
| boolean
| Default: 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.
Parameter | Type/Values | Description |
---|---|---|
vehicleType
| [0 | 1 | 2 | 3| 4 ]
|
Default: 0 Restricts the route to roads that are accessible by the selected vehicle type.
|
routingType
| [0 | 1 | 2]
|
Default: 0 Generated the route to match the type.
|
routeOptimization
| [0 | 1 | 2]
|
Default: 0
|
tollDiscourage
| boolean
|
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 Later. Use tollDiscourage for older versions.
|
classOverrides
| [0 | 1 | 2]
|
Default: 0
|
bordersOpen
| boolean
|
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.
|
overrideRestrict
| boolean
|
Default: false
Indicates whether or not to override truck restrictions |
highwayOnly
| boolean
|
Default: false Restricts the route to only highway roads. |
hazMatType
| Array 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
|
tunnelCategory
| Array of [0 | 1 | 2 | 3 | 4]
|
Default: 0
Indicates the tunnel categories, which are applicable for EU region only.
|
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.
|
governorSpeedLimit
| number
| Maximum 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 .
|
avoidState
| Array 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 Later. Examples: ['NJ', 'PA'] |
avoidCountry
| Array 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 Later. Examples: ['BE', 'AT'] |
favorState
| Array 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 Later. Examples: ['NJ', 'PA'] |
favorCountry
| Array 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 Later. Examples: ['BE', 'AT'] |
distanceUnits
| [0 | 1]
|
Default: 0
Distance units as miles or kilometers.
|
trkUnits
| [0 | 1]
|
Default: 0
Vehicle dimension units; can be English or Metric.
|
trkHeight
| number
| The height of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148. |
trkLength
| number
| The length of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148. |
trkWidth
| number
| The width of the vehicle in feet and inches or meters depending on units. Example 13'6" or 4.1148. |
trkWeight
| number
| The weight of the vehicle in pounds or kilograms depending on units. |
trkAxles
| number
|
Default: 5 The number of axles on the vehicle; acceptable values are 2 through 14. |
inclFerryDist
| boolean
|
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.
|
truckConfig
| [0 | 1 | 2 | 3 | 4| 5| 6| 7| 8]
|
Default: 0
The vehicle style.
|
inclTollData
| boolean
|
Default: true
Indicates whether or not reports should calculate toll costs. Note: This parameter is only used for Reports |
fuelEconLoad
| number
|
The fuel efficiency (distance units per fuel units) when loaded. Note: This parameter is only used for Reports |
fuelEconEmpty
| number
|
The fuel efficiency (distance units per fuel units) when empty.
Note: This parameter is only used for Reports |
costPerFuelUnit
| number
|
The cost per fuel unit of fuel.
Note: This parameter is only used for Reports |
costGHG
| number
|
The cost of greenhouse gas in lbs. per fuel unit. Note: This parameter is only used for Reports |
costMaintLoad
| number
|
The maintenance cost per distance unit when loaded.
Note: This parameter is only used for Reports |
costMaintEmpty
| number
|
The maintenance cost per distance unit when empty. Note: This parameter is only used for Reports |
costTimeLoad
| number
|
The time cost per mile/km when loaded. Note: This parameter is only used for Reports |
costTimeEmpty
| number
|
The time cost per mile/km when empty. Note: This parameter is only used for Reports |
tollCurrency
| [0 | 1]
|
Default: 0
The toll currency.
|
exchangeRate
| number
|
The change rate to convert US dollars to Canadian dollars. Note: This parameter is only used for Reports |
tollPlan
| String
| 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) |
citeInt
| number
|
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 |
estimatedTimeOpts
| String
|
Estimated time options allow you to select when you would like to depart from your origin or arrive at your destination. You must select one of three options for your arrival or departure: The current time and day; a day of the week and time of day; or a specific date and time of day. 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 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 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 Default: All
|
The alert certainty filter to be used when generating a weather alerts report. Note: This parameter is only used for Reports |
eventNames
| Array{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 |
useTraffic
| Boolean
| Indicates 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.)
|
elevLimit
| Number
|
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
|
ferryDiscourage
| Boolean
|
Indicates whether or not to discourage the use of ferries when creating the route.
Default: false
|
afSetIDs
| Array{Number}
| The avoid/favor set ids to apply to the route. |
region
|
[NA | EU | OC | SA
|
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. |
useSites
| Boolean
|
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
Parameter | Type/Values | Description |
---|---|---|
type
|
[Mileage | Directions | Detail | State |
|
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 |
|
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) |
|
Default: ENUS The language of the report returned with the route. |
condenseDirs
| Boolean
|
Default: false Indicate whether or not to get the condensed version of the directions report. |
trlType
| String
|
Default: None Type of the trailer. Available values are None, Caravan, Trailer. Note: This parameter is for EU TollDetail report only. |
trlMaxWt
| Number
|
Max weight of the trailer in pounds or kilograms depending on units. Note: This parameter is for EU TollDetail report only. |
trlMaxHt
| Number 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. |
trlMaxAxles
| Number
|
Default: 1 Max number of axles on the trailer. Acceptable values are 1 - 8. |
trlCount
| Number
|
Default: 0 Number of trailers and semi-trailers. Note: This parameter is for EU TollDetail report only. |
isHybrid
| Boolean
|
Default: false Indicates whether vehicle has a hybrid engine. Note: This parameter is for EU TollDetail report only. |
minPoll
| Boolean
|
Default: false Indicates whether the vehicle is a minimum vehicle pollution. Note: This parameter is for EU TollDetail report only. |
emiType
| String
|
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.
Property | Type | Description |
---|---|---|
content
| String
| A string containing an SVG element. |
size
| ALKMaps.Size
| Size of the SVG element. The default size is the bounding box of the element. |
offset
| ALKMaps.Pixel
| The 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.
Property | Type/Values | Description |
---|---|---|
arrows
| "line"/"end"/null
| This 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.
|
arrowSize
| number/string
| The 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%”. |
arrowSpacing
| number
| For “line” arrows only. The distance in pixels between arrows along the route. Default is 100. |
arrowStrokeColor
| string
| Hex stroke color. Used as the color for the outline of the arrow(s). Default is “black”. |
arrowStrokeWidth
| number
| Pixel stroke width. Used as the thickness for the outline of the arrow(s). Default is 1. |
arrowStrokeOpacity
| number
| Stroke opacity (0-1). Used as the opacity for the outline of the arrow(s). Default is 1. |
arrowFillColor
| string
| Hex fill color. Used as the color for the inside of the arrow(s). Default is “white”. |
arrowFillOpacity
| number
| Fill 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%”.