Maptitude GISDK Help |
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.
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
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 nigh 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 ant 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 |
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 |
Default 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 |
Default 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 |
Default 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 |
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.
// 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 tyoe 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
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
//Modifyspeedfactorbylinktyoe1:slow,4:Normal,7:fast
router.MajorHighwaySpeedLevel=4
router.SecondaryHighwaySpeedLevel=4
router.LocalHighwaySpeedLevel=4
router.ArterialSpeedLevel=4
router.LocalRoadSpeedLevel=4
router.DistanceTable(optArropts)
opts.Origins="My Towns"
opts.Destinations="My Towns"
opts.IsEuclid=0
opts.OutoutFIleName="C:\\temp\\outdist.bin"
router.DistanceTable(opts)
endmacro
Please, refer to the "Accesing Maptitude from .NET" section in the GISDK Help for further reference.
using System;
using System.Collections.Generic;
using System.Text;
using CaliperForm;
///
/// Calculate the fastest route between 2 addresses
///
static void Calculate_Route()
{
CaliperForm.Connection Conn = new CaliperForm.Connection { MappingServer = "Maptitude" };
Boolean opened = false;
try
{
opened = Conn.Open();
if (opened)
{
// You must declare dk as "dynamic" or the compiler will throw an error
dynamic dk = Conn.Gisdk;
OptionsArray region_prefs = new OptionsArray(dk.Macro("Get Geocoding Preferences"));
if (!region_prefs.ContainsKey("region_file")) {
Console.Out.WriteLine("Region File missing from 'Get Geocoding Preferences'");
Conn.Close();
return;
}
string region_file = region_prefs["region_file"] as string;
string map_wizard_map_file = System.IO.Path.GetDirectoryName(region_file) +
"\\Map Wizard Maps\\MapWizardUSMap.map";
// Open the map wizard map witht the layers for this country package
var map_options = new OptionsArray();
map_options["Auto Project"] = "true";
// path used to look for layers used in the map, before other locations usually searched for
map_options["Force Directory"] = data_directory;
string map_name = dk.OpenMap(map_wizard_map_file, map_options);
if (map_name == null) {
Console.Out.WriteLine("Cannot open map wizard map file " + map_wizard_map_file
+ ". Perhaps some layers are missing?");
Conn.Close();
return;
}
// geocode an address
dynamic finder = dk.CreateObject("Data.Finder");
finder.SetRegion();
var args = new OptionsArray();
args["silent"] = true;
args["address"] = "200 Beacon Street";
args["city"] = "Boston MA";
var found_origin = new OptionsArray(finder.Find("ADDRESS", args));
args["address"] = "100 Seaport Blvd";
var found_destination = new OptionsArray(finder.Find("ADDRESS", args));
if (found_origin["Coord"] == null || found_destination["Coord"] == null) {
Console.Out.WriteLine("Unable to locate origin or destination address.");
Conn.Close();
return;
}
//Calculate path using the Routing API
var router = dk.CreateObject("Routing.Router");
router.Minimize = "Time";
var options = new OptionsArray();
string xml_directions_file = dk.Macro("G30 Tutorial Folder") + "Example Directions.xml";
options["Directions"] = xml_directions_file;
options["DirectionsField"] = "NAME";
options["StopDescriptions"] = new string[] { "100 Beacon St" , "200 Seaport Blvd" };
dynamic path = router.CalculatePath(found_origin["Coord"], found_destination["Coord"],options);
if (path == null) {
Console.Out.WriteLine("Router error: {0}", router.ErrorMessage);
Conn.Close();
return;
}
string map_units = dk.GetMapUnits("Plural");
Console.Out.WriteLine("Fastest Travel Time Path between two addresses: {0:F2} minutes, {1:F2} {2}.", path.Time, path.Distance, map_units);
//add annotation
var annotationOpts = new OptionsArray();
annotationOpts["Points"] = path.Coords;
annotationOpts["Line Color"] = dk.ColorRGB(65535, 32768, 0);
object[] lineStyles = dk.Macro("G30 setup line styles");
annotationOpts["Line Style"] = lineStyles[1];
annotationOpts["Line Width"] = 8;
dk.AddAnnotation("Map|" + map_name, "Polyline", annotationOpts);
//calculate scope from path points
dynamic scope = dk.GetArrayScope(path.Coords);
//back up a little
scope.Width = scope.Width * 1.05;
scope.Height = scope.Height * 1.05;
//zoom map to scope of path
dk.SetMapScope(map_name, scope);
dk.RedrawMap(map_name);
// Dump the directions to the standard output
if (System.IO.File.Exists(xml_directions_file)) {
Console.Out.WriteLine("XML Turn by Turn Directions:");
Console.Out.WriteLine(System.IO.File.ReadAllText(xml_directions_file));
}
Conn.Close();
}
}
catch (System.Exception error)
{
Console.Out.WriteLine(error.Message);
}
}
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
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 an 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)
See Also:
©2025 Caliper Corporation | www.caliper.com |