Routing

Routing is done using ALK Maps Data. 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 as of version 1.2 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.

Available in 1.2, is 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.

Parameter 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] Default: 0
Restricts the route to roads that are accessible by the selected vehicle type.
  • 0 - Truck
  • 1 - Light Truck
  • 2 - Automobile
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
tollDiscourage boolean Default: false
Generates the route by trying to avoid toll roads.
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.
bordersOpen boolean Default: true
Indicates whether borders are open for travel.
overrideRestrict boolean Default: false
Indicates whether or not to override truck restrictions
highwayOnly boolean Default: false
Restricts the route to only highway roads.
hazMatType [0 | 1 | 2 | 3 | 4 | 5 | 6 | 7] Default: 0
Restricts the route to roads that allow transportation of the selected hazardous material. See details in Glossary.
  • 0 - None
  • 1 - General
  • 2 - Caustic
  • 3 - Explosives
  • 4 - Flammable
  • 5 - Inhalants
  • 6 - Radioactive
European Region
  • 0 - None
  • 1 - General
  • 3 - Explosives
  • 4 - Flammable
  • 7 - HarmfulToWater
tunnelCategory [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
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.
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.
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.
  • 0 - Gallons
  • 1 - Liters
Note: This parameter is only used for Reports
truckConfig [0 | 1 | 2 | 3 | 4] Default: 0
The vehicle style.
  • 0 - Indicates that no particular vehicle style is chosen.
  • 1 - 28' double trailer.
  • 2 - 40' straight trailer.
  • 3 - 48' semitrailer.
  • 4 - 53' semitrailer
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.
  • 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
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 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
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 use traffic when calculating trip transit times.
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. 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
| 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.
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.

If you are a global highway customer that would like to use routing in another region, you can set dataset to "Current" inside of routeOptions to use global highway data.

Report Options

Parameter Type/Values Description
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 PCM27]
Default: current
The data version against which this request should be performed.
Note: Reports might be different from the route if older data version is 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.
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. Note:
This parameter is for EU TollDetail report only.
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 EuroI, EuroII, EuroIII, EuroIV, EuroV, EuroVI. Note:
This parameter is for EU TollDetail report only.

Please visit Route Reports and EU Toll Detail Report example pages and view the source code for more information.

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 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]
        },
	
	...

});

The first parameter of setRouteHandle is the routeId of the route containing the handle to change.


The second parameter indicate which handle to change. This can be specified by either the type or index of the point. Valid types are "O" for origin, "D" for destination, or "W" for waypoint, or "A" for all types. If the route contains several stop/waypoints, all graphics will be updated. In addition to types, you may also specify the index to select the handle. The index is zero-based starting at the origin.


The third parameter is an object representing the style properties to be set. Valid style properties are:

Property Description
externalGraphic The URL of the image to be used as the handle.
graphicWidth The width of the image.
graphicHeight The height of the image.
graphicXOffset The X offset from the stop point.
graphicYOffset The Y offset from the stop point.

Graphic Defaults

In version 1.2 there is the option of setting the default graphic used for each handle type. This means that if the neither the setRouteHandle function is called or the externalImages parameter of addRoute is not specified for a given stop, you can choose the image that will be used instead for origins, waypoints, and destinations by default. One of the biggest advantages of this feature is that when a new waypoint is generated from dragging an interactive route, your default waypoint image will be used.

To set the default images for the origin, waypoint, and destination handles when declaring your routing layer, you must specify the image location for the originURL, waypointURL, and destinationURL parameters respectively.

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"
		}
	},
	
	...

});

Currently, strokeOpacity, strokeColor, strokeLinecap, strokeWidthand strokeDashstyle are the supported styling options. Stroke opacity value ranges are from 0 to 1. Stroke color takes hex code in string, like "#ee9900". Valid value for line cap is "butt", "round", or "square". Valid value for dash style is "dot", "dash", "dashdot", "longdash", "longdashdot" or "solid" and most SLD patterns will render correctly. If stroke width is supplied, default width in the context will be replaced.

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 layed 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%".