Skip to main content
Version: 1.8.3.X

Routing

Route helpers let you manage saved multi-stop routes inside a map control. A route can include a name, waypoint list, route color, transport mode, waypoint optimization, and avoid preferences.

Why you'd use these helpers​

  • Save repeatable route plans for dispatch, inspections, or service runs.
  • Update a route definition when stops or constraints change.
  • Quickly navigate the map to a selected route context.
  • Keep route behavior predictable by explicitly setting transport, optimize, and avoid options.

Usage pattern​

const control = globalThis.MaptaskrControlManager.getControl(controlId);

All examples below assume you already have a valid control reference.

Types​

export interface CustomWaypoint {
name: string;
lng: number;
lat: number;
waypointType?: 'source' | 'waypoint' | 'destination';
}

export interface RouteAvoidOptions {
motorways?: boolean;
tollRoads?: boolean;
ferries?: boolean;
}

export type RouteScope = 'MyRoute' | 'RecordRoute' | 'MapRoute' | 'MapRouteByCode';

export interface CustomRoute {
routeId?: string;
routeName: string;
waypoints: CustomWaypoint[];
routeColor?: string;
transportationMethod?: 'car' | 'truck' | 'walk';
optimize?: boolean;
avoid?: RouteAvoidOptions;
scope?: RouteScope;
select?: boolean;
}

Waypoint roles and normalisation​

Each stop is a CustomWaypoint. Use waypointType to say where your journey starts, which stops you visit and whether it has a fixed finish.

waypointTypeMeaning
'source'Your starting point (Source). It stays first.
'waypoint'A stop you visit between the start and finish.
'destination'Your fixed finishing point (Destination). It stays last.
OmittedIf all roles are omitted, the first stop becomes Source and the others are ordinary stops, without a fixed Destination.

Use one Source and, if you need a fixed finish, one Destination. Without a Destination, the route finishes at its last ordinary stop; optimisation may change which stop that is, depending on your provider. See provider differences. Azure Maps can retain the final ordinary stop during optimisation without making it a Destination.

getRoutes() copies stored roles to public waypoints, and addOrUpdateRoute() copies submitted roles back to internal waypoints. Neither conversion infers missing roles. Keep the roles when updating a route so that its start and finish are not accidentally changed.

The route model and route calculation normalise roles separately from these conversions. For a non-empty list, including mixed or duplicated roles:

  1. The first explicit 'source' becomes Source. If none exists, the first stop that is not a 'destination' is used; if every stop is a Destination, the first stop becomes Source.
  2. The first explicit 'destination' that is a different stop from the chosen Source becomes Destination. If none exists, there is no fixed Destination.
  3. Every remaining stop becomes an ordinary 'waypoint', including extra Source/Destination roles and omitted roles.
  4. Source is placed first and any Destination last. The ordinary stops retain their relative order until provider optimisation.

If all roles are omitted, these rules use the first stop as Source without creating a Destination. A single stop becomes Source, even if submitted as a Destination; an empty list has no endpoints.

API reference​

getRoutes​

List all currently available routes for the current map context.

Parameters: None

Returns: CustomRoute[]

Usage:

const routes = control.getRoutes();

routes.forEach((route) => {
console.log(`${route.routeName} (${route.routeId})`, route.waypoints.length);
});

Example response:

[
{
routeId: 'eb00c94d-1459-41ad-95c6-d112967717e6',
routeName: 'New Route 2',
scope: 'MyRoute',
transportationMethod: 'car',
routeColor: 'rgb(0, 230, 52)',
optimize: false,
avoid: { motorways: false, tollRoads: false, ferries: true },
waypoints: [
{ name: 'test3', lng: 115.9086, lat: -31.9753, waypointType: 'source' },
{ name: 'Test Account 1', lng: 115.83754, lat: -32.11547, waypointType: 'destination' },
],
},
];
info

Some optional fields may be omitted if they were not set when the route was created.

addOrUpdateRoute​

Create a new route or update an existing route by ID.

When updating, pass the existing routeId and the full public route payload you want saved, including every waypoint and its role. The supplied waypoints array replaces the entire list; it is not a partial waypoint update.

Public read/update is not a lossless internal round trip

Conversion creates new internal waypoint IDs on every write. Internal waypoint IDs, per-stop durations and original feature properties are not exposed by CustomWaypoint and are not restored by passing a route from getRoutes() back to addOrUpdateRoute(), even for a rename-only update. Names, coordinates and roles are copied, not every internal property.

Authentication and update permissions​

An authenticated user is required to create or update routes. Anonymous users cannot use this operation.

For non-record routes, the creator can edit the route; admins can also edit other users' MapRoute and MapRouteByCode routes. RecordRoute routes are collaborative: authenticated users can edit them within the matching record context.

An existing route must belong to the current map configuration. For an existing RecordRoute, its record ID, entity type, and field name must match the map's currentEntityId, currentEntityType, and currentEntityFieldName. This applies even when making the route private, and admins cannot bypass the context checks. Updating a record route preserves its association rather than rebinding it to another record.

These checks also apply when a supplied routeId identifies a saved route that is not already loaded in the map.

Parameters:

FieldTypeRequiredDescription
routeIdstringNoIf provided, updates that route. If omitted/empty, creates a new route.
routeNamestringYesDisplay name for the route.
waypointsCustomWaypoint[]YesOrdered waypoint list (maximum 150).
routeColorstringNoRoute color, for example rgb(0, 230, 52).
transportationMethod'car' | 'truck' | 'walk'NoRouting mode to use.
optimizebooleanNoEnables/disables waypoint optimization.
avoidRouteAvoidOptionsNoOptional avoid flags: motorways, tollRoads, ferries.
scopeRouteScopeNoDefaults to MyRoute for a new route. If omitted on update, preserves the existing scope.
selectbooleanNoSelects/highlights the route after recalculation. Defaults to false.

Returns: Promise<void>. Read the saved route with getRoutes() after awaiting the operation. Returned routes include their scope; shared is not a public input or output field.

RouteCreated, RouteUpdated and RouteSaved report successful persistence with two positional strings, (routeId, routeName), including '' for an unnamed route. First database persistence emits Created then Saved; persistence of an existing database route emits Updated then Saved. Subscribe to RouteSaved alone for one notification per save.

Callbacks follow the write, post-save read and local reconciliation, before this API's later recalculation/rendering/selection necessarily completes. Their ID/name describe the submitted save snapshot, not newer local edits retained as dirty. Failed or missing readback emits no success even if the write already committed; see save timing and pending edits.

Route selection uses the existing FeatureSelected and FeaturesSelected callbacks with Feature / Feature[] payloads, not CustomRoute. They are not save-completion or endpoint-role round-trip notifications; shape SavingCompleted is also separate.

Route scope​

ScopeVisibility
MyRouteA private personal route in My Routes.
RecordRouteA shared route in Record Routes for the matching map/profile, record ID, entity type and field name, not the whole map.
MapRouteA shared route for the current map configuration, in Map Routes.
MapRouteByCodeA shared route in Map Routes, visible to its owner. Other users must add its route code before it appears in their list.

Sharing is determined by scope. To change an existing route's scope, pass its routeId and the new scope. When permitted, setting MyRoute makes it private; setting any other scope makes it shared subject to that scope's visibility rules.

Creating a RecordRoute, or changing another scope to RecordRoute, requires nonblank values for the map's current record ID, entity type, and field name (currentEntityId, currentEntityType, and currentEntityFieldName). The route is associated with that record, table and field within the current map/profile.

addOrUpdateRoute() still defaults a new route with omitted scope to MyRoute, even with complete record context; on update, omitted scope preserves the existing scope. Request RecordRoute explicitly and satisfy the context and sharing/permission checks below. This differs from new live-map routes, which automatically use RecordRoute with complete context, independently of manual-sharing settings.

This API persists the route; choosing a scope for a live-map working route does not. A host record save refreshes context for subsequent creation without automatically promoting private drafts or reassigning earlier record routes. The Add to Route creation limit is not a universal API quota or a bypass of API permissions.

Sharing permissions​

Changing sharing requires edit permission and the route's share or unshare permission. The following mapFeatureConfig settings also apply when sharing, unsharing, or changing between shared scopes:

SettingDefaultRequirement
canShareRoutestrueMust be enabled for any sharing change, including making a shared route private.
onlyAdminCanShareRoutesfalseWhen enabled, only admins can change sharing.
allowShareRoutesByCodetrueMust be enabled for MapRouteByCode, even for admins. When disabled, non-admins cannot change sharing for any scope.

Creating or changing to MapRoute also requires an admin. Admins can use MapRoute when code sharing is disabled, provided the other sharing checks pass.

Permitted edits that retain the existing scope and sharing state do not require sharing to be enabled.

Errors​

ErrorCause
Route changes require an authenticated userThe current user ID is missing, blank, or anon (case-insensitive).
Cannot update a route outside the current map or record contextThe existing route belongs to another map configuration, or its record context does not match the current record and field.
addOrUpdateRoute requires a valid route scopeThe supplied scope is not one of the four supported values.
Record routes require a current record id, entity type, and field nameCreating or changing to RecordRoute without all three nonblank record-context values.
You do not have permission to edit this routeThe caller does not have edit permission for the route.
Route sharing is not permitted for the requested scopeA sharing change is blocked by route permissions, map settings, or scope-specific admin requirements.

Usage - create a route:

const waypoints = [
{ name: 'Depot', lng: 115.9086, lat: -31.9753, waypointType: 'source' },
{ name: 'Test Account 1', lng: 115.83754, lat: -32.11547, waypointType: 'destination' },
];

await control.addOrUpdateRoute({
routeName: 'Adding a new route',
waypoints,
routeColor: 'rgb(0, 230, 52)',
transportationMethod: 'car',
optimize: false,
avoid: {
motorways: false,
tollRoads: false,
ferries: true,
},
});

Usage - update an existing route:

This retains the returned public fields, including waypoint roles and scope, while changing the name. The internal-property limitations above still apply. The read after the awaited write is not a reload/persistence or provider-success check.

const existing = control.getRoutes().find((route) => route.routeName === 'Adding a new route');
if (!existing?.routeId) {
throw new Error('Route to update was not found');
}

await control.addOrUpdateRoute({
...existing,
routeName: 'Adding a new route (Updated)',
});

const updated = control.getRoutes().find((route) => route.routeId === existing.routeId);
if (!updated) {
throw new Error('Updated route was not found');
}
console.log('Updated waypoint roles:', updated.waypoints.map((waypoint) => waypoint.waypointType));

Create or update a route by scope​

This example reuses one route ID per scope so repeated calls update the same route. To run all four calls, use an authenticated admin with route sharing and code sharing enabled, and nonblank current record ID, entity type, and field name for RecordRoute. Non-admins can use the permitted scopes individually; the MapRoute call requires an admin.

const routeIds = {};

async function addOrUpdateRouteByScope(scope = 'MyRoute') {
const validScopes = ['MyRoute', 'RecordRoute', 'MapRoute', 'MapRouteByCode'];
if (!validScopes.includes(scope)) {
throw new Error('Invalid route scope: ' + scope);
}

const routeId = routeIds[scope] || (routeIds[scope] = globalThis.crypto.randomUUID());

await control.addOrUpdateRoute({
routeId,
routeName: 'Custom code test - ' + scope,
scope,
select: true,
waypoints: [
{ name: 'Elizabeth Quay', lat: -31.958, lng: 115.857, waypointType: 'source' },
{ name: 'Perth Station', lat: -31.9518, lng: 115.8603, waypointType: 'waypoint' },
{ name: 'Hyde Park', lat: -31.9368, lng: 115.862, waypointType: 'destination' },
],
});

const savedRoute = control.getRoutes().find((route) => route.routeId === routeId);
console.log('Route test:', savedRoute || { routeId, scope });
return { routeId, route: savedRoute };
}

await addOrUpdateRouteByScope('MyRoute');
await addOrUpdateRouteByScope('RecordRoute');
await addOrUpdateRouteByScope('MapRoute');
await addOrUpdateRouteByScope('MapRouteByCode');

deleteRoute​

Deletes a single route by its route ID.

RouteDeleted fires after delete-if-present and local removal, including for an unsaved draft or an already-absent database record. Its two strings retain the last local ID/name, but getRoutes() no longer returns the route. Failed, missing-local or repeated deletion does not emit another deletion callback.

Parameters:

FieldTypeRequiredDescription
routeIdstringYesRoute ID of the route to remove.

Returns: Promise<void>

Usage:

const routes = control.getRoutes();

const routeId = routes[0].routeId;

await control.deleteRoute(routeId);

Navigate the map view to a saved route by ID.

Parameters:

FieldTypeRequiredDescription
routeIdstringYesRoute ID to navigate to.

Returns: Promise<void>

Usage:

const routes = control.getRoutes();
const target = routes.find((r) => r.routeName === 'Adding a new route (Updated)');

if (target?.routeId) {
await control.navigateToRoute(target.routeId);
console.log('Navigated to route:', target.routeName);
}

Common workflows​

Save or refresh a daily dispatch route​

This example fixes the Depot as Source but leaves the finish unfixed: Client B is an ordinary waypoint, not a Destination. With optimisation enabled, apply the provider differences.

const routes = control.getRoutes();
const existing = routes.find((r) => r.routeName === 'Daily Dispatch');
const routeId = existing?.routeId || globalThis.crypto.randomUUID();

await control.addOrUpdateRoute({
routeId,
routeName: 'Daily Dispatch',
waypoints: [
{ name: 'Depot', lng: 115.9086, lat: -31.9753, waypointType: 'source' },
{ name: 'Client A', lng: 115.83754, lat: -32.11547, waypointType: 'waypoint' },
{ name: 'Client B', lng: 115.7921, lat: -32.0522, waypointType: 'waypoint' },
],
transportationMethod: 'truck',
optimize: true,
avoid: { tollRoads: true },
});

const saved = control.getRoutes().find((route) => route.routeId === routeId);
console.log('Saved route:', saved);
async function navigateRouteByName(name) {
const routes = control.getRoutes();
const match = routes.find((r) => r.routeName === name);

if (!match?.routeId) {
console.warn(`Route not found: ${name}`);
return;
}

await control.navigateToRoute(match.routeId);
}

await navigateRouteByName('Daily Dispatch');

Delete a temporary route​

const routes = control.getRoutes();
const temp = routes.find((r) => r.routeName === 'Temporary Route');

if (temp?.routeId) {
await control.deleteRoute(temp.routeId);
console.log('Deleted route:', temp.routeName);
}

Best practices​

  • Keep the routeId you supply, or read it with getRoutes() after create, so updates and navigation are reliable.
  • Keep waypoint order explicit unless optimize is intentionally enabled.
  • Retain waypoint roles and the full waypoint list on updates; do not rely on internal waypoint IDs or unexposed properties surviving conversion.
  • Set transportationMethod and avoid options deliberately to prevent unexpected route behavior.
  • Use clear route naming conventions (for example team, shift, or workflow prefixes).
  • Wrap async route operations in your own error handling when wiring them to UI actions or automations.