Find a route

Routing is the process of finding paths through a transportation network. To calculate routes and obtain directions, the API provides a specific RouteTask class. Using this task, you can optimize the results to find the shortest or the fastest route, reorder stops to find the best sequence, avoid restricted areas and maneuvers, and specify time windows of arrival and departure for each stop.

The route task requires either a local ArcGIS Network Dataset on your machine to compute routes or access to a remote ArcGIS Network Analyst Service. When using a local network dataset, routes can be computed locally even when there is no network connectivity. Using remote services requires a network connection but is an opportunity for incorporating additional functionality such as real time traffic updates.

Network datasets are designed to model transportation networks. They are created from source features, which can include simple features representing roads, bridges, tunnels, bike paths, train tracks, and various other elements in the network. The geometry of the source features helps establish connectivity between these elements. When you compute a route, the analysis happens on an indexed, high-performance ArcGIS Network Dataset.

Network Analyst services are based on network datasets. They also contain analysis layers. These analysis layers correspond to specific types of network analysis such as generating a route or calculating a service area. Analysis layers are exposed in the service as operations. A RouteTask requires the service to contain a route analysis layer in order to compute routes.

Network Analyst services can be hosted in Esri's cloud platform, ArcGIS Online, or can be published on your own on-premises ArcGIS servers. These services provide an ArcGIS REST API for clients such as mobile and web app. To find the URL for a Network Analyst service, you can use the ArcGIS Services Directory.

Initialize a route task

Whether you are performing online or offline routing, you start by initializing a RouteTask object. Once you've initialized the appropriate online or offline route task class, the programming pattern is exactly the same.


To initialize an online RouteTask, declare an OnlineRouteTask object, instantiate it with the new keyword, and pass the uniform resource identifier (URI) to a REST endpoint that represents a route analysis layer in a Network Analyst service to the constructor. If the service is secured, you also need to handle authenticating with the service using the appropriate mechanism.

The following code sample shows how to create an online route task for the route analysis layer in the secured Route_World service on ArcGIS Online:

//create a new online route task for the route layer in the Route_World service
Esri.ArcGISRuntime.Tasks.NetworkAnalyst.OnlineRouteTask task = new Esri.ArcGISRuntime.Tasks.NetworkAnalyst.OnlineRouteTask
(new Uri(""));

You must have an ArcGIS Online organizational account in order to connect to the world route service used in the previous example. Visit the Esri website for information about pricing and trial subscriptions. Connecting to secured services is described in the Security topic.


To initialize an offline RouteTask, declare a LocalRouteTask object, instantiate it with the new keyword, and pass the path to the .geodatabase file of your local network dataset and the name of the network to the constructor.

The following code sample shows how to create an offline RouteTask:

//create a new online route task for the route layer in the ESRI_Route_NA service
Esri.ArcGISRuntime.Tasks.NetworkAnalyst.LocalRouteTask task = new Esri.ArcGISRuntime.Tasks.NetworkAnalyst.LocalRouteTask

Prepare the input parameters

The route task's execution method, SolveAsync, takes a RouteParameters object as input. You can instantiate a new RouteParameters object and modify its properties to provide the input. At a minimum, you need to specify the stops by calling the SetStops method, as this determines the locations between which a route will be calculated. You need at least two stops to calculate a valid route.

However, you may want to calculate routes using the defaults specified in the service. In such cases, you first need to use GetDefaultParametersAsync on the route task to get the default values. The default values are returned to the route task's delegate as a RouteParameters object.

The following code sample shows how to use GetDefaultParametersAsync on the RouteTask to get the default values:

//use GetDefaultParametersAsync to get the default values.
Esri.ArcGISRuntime.Tasks.NetworkAnalyst.RouteParameters myRouteParameters = await task.GetDefaultParametersAsync();

The following sections describe some of the inputs you can provide to a RouteTask.


Use the SetStops method to specify locations that must be visited along the route. You need at least two stops to calculate a valid route; however, you can add more if you like.

To specify stops for the route, you can specify a collection of MapPoints. The order indicates, by default, the sequence in which stops will be visited on the route. However, if you enable the FindBestSequence property on RouteParameters, the service will attempt to reorder stops to find the optimal route.

You can also enable the PreserveFirstStop and PreserveLastStop properties on RouteParameters if you don't want the origin and destination stops to be reordered.


Barriers represent ad-hoc restrictions that must be taken into consideration when calculating a route. A barrier can specify a set of roads or a region that must be completely avoided by the route, for example, a bridge that may be closed due to construction work. Some barriers may permit travel through them albeit at an added cost. For example, an accident on a freeway may temporarily slow down the traffic. This can be represented by a barrier that allows travel along the freeway but increases the travel time required.

As with stops, you can specify barriers with a collection of features. You need to provide barrier geometry including the location and shape of the barrier. The geometry can be a point, polyline, or polygon. You can define a feature and assign these barrier features to the RouteParameters object using SetPointBarriers , SetPolylineBarriers. or SetPolygonBarriers depending on the type of geometry that was assigned to the feature. You need to create separate features for point, polyline, and polygon barriers.

Map with stops and barriers displayed

Driving directions

RouteTask can return turn-by-turn driving directions for the route if you enable ReturnDirections on RouteParameters. You can specify the distance units to use through the DirectionsLengthUnits property. Depending on the languages supported by the ArcGIS Network Analyst service, you can also specify which language to use through the DirectionsLanguage property. Depending on the direction style supported by the ArcGIS Network Analyst Service, you can specify the DirectionsStyleName property. To learn more about driving directions, see the Get driving directions tutorial and the topic Display driving directions


The ImpedanceAttributeName property specifies a cost that should be minimized in the resulting route. For example, impedance could be set to Time to calculate the fastest route or to Length to calculate the shortest route. Impedances supported by the service are listed in the ArcGIS Services Directory under Network Dataset > Network Attributes with a Usage Type of esriNAUTCost.

U-turn policy

You can specify whether U-turns are allowed everywhere (AllowBacktrack), nowhere (NoBacktrack), only at dead ends (DeadEndsOnly) , or only at intersections and dead ends (AtDeadEndsAndIntersections). Allowing U-turns implies the vehicle can turn around at a junction and double back on the same street.

Result options

Line results

Using the OutputLines property, you can specify whether the geometry of the route feature should be simple straight lines connecting all the stops or follow the true shape of the underlying transportation network. This is only applicable when using an OnlineRouteTask and the RouteParameters.ReturnRoutes property is set to true. The following describes the available options for route geometry output.

  • OutputLine.None: No route geometry is returned (travel time and distance are still reported)
  • OutputLine.Straight: Straight lines connecting the stops are returned
  • OutputLine.TrueShape: The shape of the route matches the underlying transportation network from which it was derived
  • OutputLine.TrueShapeWithMeasure: Same as TrueShape but includes route measurements that describe accumulated travel cost across the routes

The output line options are available to help limit response size for information you don't need when working with online route tasks. Local route tasks will always return the full route result.

Geometry options

You can request that the geometry of the route feature be generalized by modifying the OutputGeometryPrecision and OutputGeometryPrecisionUnit properties on RouteParameters. Generalizing geometry removes vertices that add more detail beyond the precision you specify. Removing vertices makes the geometry smaller, saving time needed to transfer the geometry over the network, and makes it faster to draw as a map graphic.

Ignore invalid locations

Enabling the IgnoreInvalidLocations property allows the RouteTask to return a route even if some stops are invalid, for instance, if they are not reachable on the underlying transportation network. If this property is disabled, the RouteTask returns an error even if one stop is invalid.


Restrictions allow you to place constraints on the analysis. For example, you can specify that the route should avoid toll roads. If the route is for an emergency vehicle, you can specify that rules governing one-way streets should be relaxed. The restrictions supported by the service are listed in the ArcGIS Services Directory under Network Dataset>Network Attributes with a Usage Type of esriNAUTRestriction.

The following code sample applies restrictions to avoid passenger ferries and toll roads:

//create a list containing restrictions and assign these to the RestrictionsAttributeNames property
List<string> restrictions = new List<string>();
restrictions.Add("Avoid Ferries");
restrictions.Add("Avoid Toll Roads");
 _routeParams.RestrictionAttributeNames = restrictions;

The following sections describe some of the inputs you can provide to a RouteTask.

Time windows

A time window specifies a period of time within which a stop should be visited on a route. For example, if you made appointments to meet a number of customers at different locations, you can enable the UseTimeWindows property and specify a time window for each location to get a route that will allow you to honor your appointments.

To enable time windows in your analysis, do the following:

  • Enable the UseTimeWindows property on RouteParameters.

  • Specify the time of departure from the origin using the StartTime property on RouteParameters.

  • Assign a time window to each stop. The time windows are specified on stops using the TimeWindowStart and TimeWindowEnd attributes.

See the RouteParameters API Reference for a complete list of inputs for the RouteTask.

Calculate routes

Once you set up the input parameters, calculating routes is as simple as invoking SolveAsync on the RouteTask and passing in the RouteParameters object to use in the calculation.

Retrieve results and handle errors

The SolveAsync method determines the path from one stop to the next. This method will run the task asynchronously using the await keyword. This allows you to make the asynchronous method call and pause the code and for control to be returned to the user until the method completes and the code execution can continue.

The following code sample calls the asynchronous function to solve the RouteTask:

Esri.ArcGISRuntime.Tasks.NetworkAnalyst.RouteResult routeResult = await _routeTask.SolveAsync(myRouteParameters);

The operation's results are returned in a RouteResult instance, indicated by the Task<RouteResult>return type.

The following code sample handles the result:

try {
    // Ensure you got at least one route back.
    if (routeResult.Routes.Count > 0)
        // Create a new graphic based on the first route and add to the route Graphicslayer 
        Esri.ArcGISRuntime.Layers.Graphic graphic = routeResult.Routes[0].RouteGraphic;
catch (System.AggregateException ex)
     // There was a problem, display the results to the user.
    var innermostExceptions = ex.Flatten().InnerExceptions;
    if (innermostExceptions != null && innermostExceptions.Count > 0)
catch (System.Exception ex)
    // There was a problem, display the results to the user.
    System.Windows.MessageBox.Show("Error: " + ex.Message);

The RouteResult object contains an array of Route objects representing the routes that were calculated. Each Route object contains the following:

  • A graphic representing the route feature. The graphic's attributes provide information about route properties.

  • A list of graphics representing the stops that are visited by the route. Each graphic contains attributes that correspond to stop properties. These properties provide valuable information about the stop as it pertains to the computed route.
  • A set of turn-by-turn driving directions (if you enabled ReturnDirections on RouteParameters).
  • The RouteResult object also contains an array of messages providing information about any warnings or errors encountered while calculating the route.

Tasks throw exceptions if a problem is encountered as opposed to raising failed style events. Therefore it is important to make appropriate use of the try/catch statement and handle these exceptions gracefully in your code.

The following image shows the map with route and directions displayed:

Map with route and driving directions displayed in the Textblock

Related topics