Routing.Router

Constructor

Routing.Router

This is the main entry point to the API. Your code should create an instance of this class and call one of its methods to calculate a path.

The network will remain loaded for the lifetime of the object so, when calculating multiple paths, the same instance should be reused to avoid unnecessary reloads.

The methods of the Routing.Router class return an instance of the Routing.Path class.

Note

This function requires a HERE streets layer included with a Maptitude Country Package. For a list of available Country packages, please visit https://www2.caliper.com/store/product/maptitude-country-package/HERE country packages

Properties

Name Type Contents
Minimize string The variable to minimize when calculating paths, either "Time" (the default) or "Distance"
StartTime datetime Driving start time. Default is 9 AM
EndTime datetime Driving end time. Default is 5 PM
Flexibility numeric Default value is 15, Cushion time
NoNightBreak boolean If true, no night breaks are computed. Default is false.
TimeBetweenRests numeric Default value is 240, Max driving time before a break
DefaultStopTime numeric Default value is 30, Default stay time for each stop
RestStopDuration numeric Default value is 15
FuelConsumptionCity numeric Default value is 17, FuelConsumptionCity consumption, in MPG
FuelConsumptionHighway numeric Default value is 23
FuelPrice numeric Default value is 3.0, Price of fuel in currency and tank units
FixedDrivingCost numeric Default value is 0.2, Monetary cost per mile/km
IncludeRestStops boolean Default value is false, Rest after driving for some hours
useStopTime boolean Default value is false, all stop time for all stops
ReportStreetNameField string Optional. Name of a custom field in the streets layer to be used for directions report
DistanceBasedCostCalculation string Default is false. If true calculate cost based on fixed per distance value otherwise based on fuel consumption
FuelTankUnits string US Gallons, UK Gallons, Liters
FuelConsumptionHighway string Highway Fuel Consumption in units of fuel units
FuelConsumptionCity string City Fuel Consumption in units of fuel units
TimeBetweenRests int Max driving time before a break. Default value is 240 min
SkipDirectionGeneration boolean If true, then do not generate directions report information
SkipPathDisplay boolean If true, no path annotation will be generated
SingleThreaded boolean If true, shortest path will be run in single threaded mode
AllowDuplicateStops boolean Default is false. If true, allow multiple stops at the same coordinate
MajorHighwaySpeedLevel int Optional. Default value is 4. Defines speed level from 1 to 7, slow to fast
SecondaryHighwaySpeedLevel int Optional. Default value is 4. Defines speed level from 1 to 7, slow to fast
LocalHighwaySpeedLevel int Optional. Default value is 4. Defines speed level from 1 to 7, slow to fast
ArterialSpeedLevel int Optional. Default value is 4. Defines speed level from 1 to 7, slow to fast
LocalRoadSpeedLevel int Optional. Default value is 4. Defines speed level from 1 to 7, slow to fast

Methods

Calculate(array Points, array opts)

Calculates the path between an array of Points with the options.

Option Type Description
Points
Coordinate coord Point coordinate
DepartureTime int Departure time
ArrivalTime int Arrival time
StopDuration int Stop duration in minutes
StopName string Optional. Stop name for report
opts array
Loop bool Whether to create a route that loops back to the first stop (default is False).It only applies if Fix is First, ignored otherwise.
Fix string "First": route should start at the first stop in list. "Last": route should end at the last stop in list. "Both": route should start at the first stop and end at the last stop in list. If Fix is not null then the route is optimized. If it is null, then the route is in the order of the stop list.

CalculatePath(Coord From, Coord To)

Calculates the path between two coordinates based on the current minimization variable. If successful, returns an instance of Routing.Path.

Option Type Description
From Coord Coordinate of origin point
To Coord Coordinate of destination point

CreateReport(array opts)

Creates a report in PDF format..

Option Type Description
opts array
PathObj Routing.Path Routing.Path class instance (returned from CalculatePath())
OpenReport bool Defaults to False. If true, display the report document
FileName string Optional name of the output PDF file name

ExportToExcel(array opts)

Export the path results to an Excel sheet.

Option Type Description
opts array
PathObj Routing.Path Routing.Path class instance (returned from CalculatePath())
OpenExcel bool Defaults to False. If true, display the Excel document
FileName string Optional name of the output Excel file name

DistanceTable(array opts)

Calculates the table(s) of distances between points

Option Type Description
opts array
Origins string Origin layerset name
IsEuclid bool Defaults to False. If True, Euclidian distances are computed. If False, network distances are computed.
Destinations string Destinations layerset name
MaxImpedanceValue real Cutoff threshold, do not search paths whose length value is longer than this
OutputFileName string The output filename, if only one file
ClosestDestinations integer Sets the number of closest destinations to be output for each origin.

Returns

DistanceTable() returns an option array

Option Type Description
OutFileName string Full path and filename of the output distance table

Examples

GISDK, VBA and Python examples provided below.

The examples below work for the US. If your current Country Package is other than the US, you would need to change the coordinates and addresses where appropriate.

GISDK
// Generate a shortest path via 5 routing points and display on the current map window
Macro "RoutingExample1"
on error do
ShowMessage(GetLastError())
return()
end
p1.Coordinate = Coord(-71259994, 42298892)
p1.StopDuration = 30
p1.StopName = "Babson College"
p2.Coordinate = Coord(-71250024, 42341178)
p2.StopName = "Lasell College"
p2.StopDuration = 120
p3.Coordinate = Coord(-71187232, 42298633)
p3.StopDuration = 43
p3.StopName = "Mount Ida College"
p4.Coordinate = Coord(-71197377, 42340143)
p4.StopName = "Boston College"
p5.Coordinate = Coord(-71310381, 42298016)
p5.StopName = "Wellesley College"
RoutingPoints = {p1, p2, p3, p4, p5}
router = CreateObject("Routing.Router")
router.Minimize = "Time"
router.IncludeRestStops = true
router.TimeBetweenRests = 5
router.RestStopDuration = 20
router.FuelPrice = 3.29
router.SingleThreaded = true
// Modify speed factor by link type 1: slow, 4: Normal, 7: fast
router.MajorHighwaySpeedLevel = 4
router.SecondaryHighwaySpeedLevel = 4
router.LocalHighwaySpeedLevel = 4
router.ArterialSpeedLevel = 4
router.LocalRoadSpeedLevel = 4
spOpts = null
spOpts.Fix = "First"
spOpts.Loop = True
path = router.Calculate(RoutingPoints, spOpts)
if path.Error then
Throw(router.ErrorMessage)
// create a report
ret = router.CreateReport({PathObj: path, OpenReport: true,
FileName: GetRandFileName("*.xlsx")})
if ret.Error then Throw(ret.ErrorMessage)
// ret = router.ExportToExcel({FileName: GetTempFileName("*.xlsx"), OpenExcel: true})
// if ret.Error then Throw(ret.ErrorMessage)
// Display path on current map
path.PathDisplayWidth = 60
shared cc_Colors
path.PathDisplayColor = cc_Colors.Red
path.DisplayPath()
// path.ClearPathDisplay()
endmacro
// simple path from an origin coordinate to a destination coordinate
macro "RoutingExample2"
on error do
ShowMessage(GetLastError())
return()
end
// Example near Newton, MA
OriginCoord = Coord(-71206120, 42321660)
DestCoord = Coord(-71164968, 42331357)
// StopTimes = {30, 20, null, 25}
router = CreateObject("Routing.Router")
router.Minimize = "Time"
router.FuelPrice = 3.29
path = router.CalculatePath(OriginCoord, DestCoord)
if path.Error then Throw(path.ErrorMessage)
// create a report
ret = router.CreateReport({PathObj: path, OpenReport: true})
if ret.Error then
Throw(ret.ErrorMessage)
// Display path on current map
path.PathDisplayWidth = 60
shared cc_Colors
path.PathDisplayColor = cc_Colors.Red
path.DisplayPath()
//path.ClearPathDisplay()
endmacro
// This example creates a shortest time route between two addresses
Macro "CalculateTimeDistance"
on error do
ShowMessage(GetLastError())
return()
end
finder = CreateObject("Data.Finder")
finder.SetRegion()
args.silent = true
args.address = "407 Marlborough Street"
args.city = "Boston MA"
p1 = finder.Find("ADDRESS", args)
args.silent = true
args.address = "1172 Beacon Street"
args.city = "Newton MA"
p2 = finder.Find("ADDRESS", args)
myRouter = CreateObject("Routing.Router")
myRouter.Minimize = "Time"
myRouter.MajorHighwaySpeedLevel = 1
myRouter.SecondaryHighwaySpeedLevel = 1
myRouter.LocalHighwaySpeedLevel = 1
myRouter.ArterialSpeedLevel = 1
myRouter.LocalRoadSpeedLevel = 1
path = myRouter.CalculatePath(p1.Coord, p2.Coord)
endmacro
// Computes a distance table for all points in a selection set
// Before running this macro
// - Open a map of the US,
// - Make the City/Town layer the working layer
// - Create a "My Towns" Selection Set using the Selection Toolbar
Macro "ComputeDistanceTable"
SetLayer("City/Town")
 router=CreateObject("Routing.Router")
 router.Minimize="Time"
 router.IncludeRestStops = true
 router.TimeBetweenRests = 5
 router.RestStopDuration = 20
 router.FuelPrice = 3.29
 router.SingleThreaded = true
 
 // Modify speed factor by link type 1: slow, 4: Normal, 7: fast
 router.MajorHighwaySpeedLevel=4
 router.SecondaryHighwaySpeedLevel=4
 router.LocalHighwaySpeedLevel=4
 router.ArterialSpeedLevel=4
 router.LocalRoadSpeedLevel=4
 
 opts.Origins = "My Towns"
 opts.Destinations = "My Towns"
 opts.IsEuclid = 0
 opts.ClosestDestinations = 2
opts.OutputFileName = GetRandFileName("*.bin")
ret = router.DistanceTable(opts)
tableObj = CreateObject("Table", ret.OutFileName)
 tableObj.View()
endmacro
.NET

Please, follow this link for a C# example: Using the CaliperForm.Connection.Gisdk Class: Calculate_Route()

For information about running Maptitude form .NET, please refer to Accessing Maptitude from .NET

VBA
Dim dk As Object
Private Sub UserForm_Initialize()
 Gisdk.RunMacro "MinimizeWindow", "Frame|"
 Gisdk.RunMacro "SetMapUnits", "Miles"
 
 ' Open the map used by this application
'Note: The map is installed under C:\Users\your_user_name\Documents\Caliper\Maptitude 20YY\Tutorial\, where 20YY is the Maptitude version
 folder = Gisdk.Macro("G30 Tutorial Folder", "")
 Gisdk.RunMacro "OpenMap", folder + "BMP_SVR.MAP", Null
' Change its size to the size required by the client
 Gisdk.RunMacro "SetWindowSizePixels", Null, 600, 600
' Change the current layer to the cities and towns layer
 Gisdk.RunMacro "SetLayer", "Cities & Towns"
End Sub
Private Sub CommandButton1_Click()
CreatePath
End Sub
Private Sub CreatePath()
On Error GoTo Error_handler:
Set dk = CreateObject("Maptitude.AutomationServer")
dk.RunMacro "SetMapUnits", "Miles"
units = dk.RunMacro("GetMapUnits", Null)
Dim dP1, dP2, dP3, dP4, dP5
Set dP1 = CreateObject("Scripting.Dictionary")
Set dP2 = CreateObject("Scripting.Dictionary")
Set dP3 = CreateObject("Scripting.Dictionary")
Set dP4 = CreateObject("Scripting.Dictionary")
Set dP5 = CreateObject("Scripting.Dictionary")
With dP1
.Add "Coordinate", dk.RunMacro("Coord", -71259994, 42298892)
.Add "StopDuration", 30
.Add "StopName", "Babson College"
End With
With dP2
.Add "Coordinate", dk.RunMacro("Coord", -71250024, 42341178)
.Add "StopDuration", 30
.Add "StopName", "Lasell College"
End With
With dP3
.Add "Coordinate", dk.RunMacro("Coord", -71187232, 42298633)
.Add "StopDuration", 30
.Add "StopName", "Mount Ida College"
End With
With dP4
.Add "Coordinate", dk.RunMacro("Coord", -71197377, 42340143)
.Add "StopDuration", 30
.Add "StopName", "Boston College"
End With
With dP5
.Add "Coordinate", dk.RunMacro("Coord", -71310381, 42298016)
.Add "StopDuration", 30
.Add "StopName", "Wellesley College"
End With
Dim P1, P2, P3, P4, P5
P1 = CreateOptFromDictionary(dP1)
P2 = CreateOptFromDictionary(dP2)
P3 = CreateOptFromDictionary(dP3)
P4 = CreateOptFromDictionary(dP4)
P5 = CreateOptFromDictionary(dP5)
Dim RoutingPoints
RoutingPoints = Array(P1, P2, P3, P4, P5)
'RoutingPoints = Array(P1, P2)
Dim router
Set router = dk.CreateObject("Routing.Router", "")
router.Set "Minimize", "Time"
router.Set "IncludeRestStops", True
router.Set "TimeBetweenRests", 5
router.Set "RestStopDuration", 20
router.Set "FuelPrice", 3.29
Dim pth, PathRep, repOpts, ret
Set pth = router.Method("Calculate", RoutingPoints, spOpts)
Set PathRep = CreateObject("Scripting.Dictionary")
PathRep.Add "PathObj", pth
PathRep.Add "FileName", "c:\\temp\\Path.xlsx"
PathRep.Add "OpenReport", True
repOpts = CreateOptFromDictionary(PathRep)
ret = router.Method("CreateReport", repOpts)
Exit Sub
Error_handler:
MsgBox "Path calculation returned an error"
End Sub
Function CreateOptFromDictionary(dict) As Variant
Dim nItems, i As Integer
Dim Key, items
Dim options
nItems = dict.Count
i = 0
ReDim options(nItems - 1, 1)
For Each Key In dict.Keys()
options(i, 0) = Key
If TypeOf dict(Key) Is Object Then
Set options(i, 1) = dict(Key)
Else
options(i, 1) = dict(Key)
End If
i = i + 1
Next
CreateOptFromDictionary = options
End Function
Python

Please, refer to the "Programming Maptitude in Python" section in the GISDK Help for further reference on how to access Maptitude from Python

# PYTHON 3 Routing Example
import sys
import os
import traceback
import caliperpy
import ctypes
from ctypes.wintypes import HWND, LPWSTR, UINT
_user32 = ctypes.WinDLL('user32', use_last_error=True)
_MessageBoxW = _user32.MessageBoxW
_MessageBoxW.restype = UINT
_MessageBoxW.argtypes = (HWND, LPWSTR, LPWSTR, UINT)
MB_OK = 0
#
# NOTE: *****************************
# Open Maptitude and a map of the USA
#
dk = caliperpy.Gisdk("Maptitude")
p = dk.GetProgram()
try:
dk.SetMapUnits("Miles")
units = dk.GetMapUnits(None)
p1 = {"Coordinate": dk.Coord(-71259994, 42298892), "StopDuration": 30,
"StopName": "Babson College"}
p2 = {"Coordinate": dk.Coord(-71250024, 42341178), "StopDuration": 30,
"StopName": "Lasell College"}
p3 = {"Coordinate": dk.Coord(-71187232, 42298633), "StopDuration": 30,
"StopName": "Mount Ida College"}
p4 = {"Coordinate": dk.Coord(-71197377, 42340143), "StopDuration": 30,
"StopName": "Boston College"}
p5 = {"Coordinate": dk.Coord(-71310381, 42298016), "StopDuration": 30,
"StopName": "Wellesley College"}
RoutingPoints = [p1, p2, p3, p4, p5]
router = dk.CreateGisdkObject("gis_ui", "Routing.Router")
router.Minimize = "Time"
router.IncludeRestStops = True
router.TimeBetweenRests = 5
router.RestStopDuration = 20
router.FuelPrice = 3.29
path = router.Calculate(RoutingPoints, None)
if path is not None:
time = path.Time
dist = path.Distance
ret = router.CreateReport({"PathObj":path, "OpenReport":1,
"FileName": dk.GetRandFileName("*.xlsx")})
retOpts = dict(ret)
if ( not retOpts is None ) and ( 'ErrorMessage' in retOpts ):
_MessageBoxW(0, retOpts["ErrorMessage"], "Error", MB_OK)
else:
_MessageBoxW(0, "Path length: " + str(dist) + " : " + "Path Time: " + str(time),
"Information", MB_OK)
else:
raise Exception("Please open a map window first")
except Exception as Error:
_MessageBoxW(0, repr(error), "Information", MB_OK)
# Computes a distance table for all points in a selection set
# Before running this macro
# - Open a map of the US,
# - Make the City/Town layer the working layer
# - Create a "My Towns" Selection Set using the Selection Toolbar
import caliperpy
def compute_distance_table(dk, opts):
 
 # Create and configure the routing object
 router = dk.CreateGisdkObject("gis_ui", "Routing.Router")
 router.Minimize = "Time"
 router.IncludeRestStops = True
 router.TimeBetweenRests = 5 # minutes
 router.RestStopDuration = 20 # minutes
 router.FuelPrice = 3.29
 router.SingleThreaded = True
# Speed levels: 1=slow, 4=normal, 7=fast
 router.MajorHighwaySpeedLevel = 4
 router.SecondaryHighwaySpeedLevel = 4
 router.LocalHighwaySpeedLevel = 4
 router.ArterialSpeedLevel = 4
 router.LocalRoadSpeedLevel = 4
 
 ret = router.DistanceTable(opts)
 
 # Get the name of the output table file 
 distance_table = next((v for k, v in ret if k == "OutFileName"), None)
 
 dk_table = dk.CreateGisdkObject("gis_ui", "Table", {"FileName":distance_table})
 dk_table.View()
# Initialize GISDK session
 dk = caliperpy.Maptitude.connect() pro = dk.Getprogram()
 print(pro)
# Set up distance table options
 opts = {
 "Origins": "My Towns",
 "Destinations": "My Towns", 
 "IsEuclid": "False",
 "OutputFileName": r"C:\temp\outdist.bin"
 }
table_file = compute_distance_table(dk, opts)

See Also:

AddLayerDB

AddTables

Calculate Tables

Caliper.Charts

CC.ModifyTableOperations

CC.Table

Clustering

Data.Finder

Data.Geocoder

PostgreSQL Connect

PostgreSQL Command

Routing.Bands

Routing.Path

Routing.Router

Table

Utilities.Mail

Using the CaliperForm.Connection.Gisdk Class: Calculate_Route()