Learn how to find a route and directions with the route service.
Routing is the process of finding the path from an origin to a destination in a street network. You can use the Routing service to find routes, get driving directions, calculate drive times, and solve complicated, multiple vehicle routing problems. To create a route, you typically define a set of stops (origin and one or more destinations) and use the service to find a route with directions. You can also use a number of additional parameters such as barriers and mode of travel to refine the results.
In this tutorial, you define an origin and destination by clicking on the map. These values are used to get a route and directions from the route service. The directions are also displayed on the map.
Prerequisites
Before starting this tutorial, you should:
Have an ArcGIS account and an API key to access ArcGIS services. If you don't have an account, sign up for free.
Optionally, you may want to install the ArcGIS Maps SDK for .NET to get access to project templates in Visual Studio (Windows only) and offline copies of the NuGet packages.
Steps
Open a Visual Studio solution
To start the tutorial, complete the Display a map tutorial or download and unzip the solution.
Open the .sln file in Visual Studio.
If you downloaded the solution project, set your API key.
An API Key enables access to services, web maps, and web scenes hosted in ArcGIS Online.
If necessary, set the API Key.
Go to your developer dashboard to get your API key.
For these tutorials, use your default API key. It is scoped to include all of the services demonstrated in the tutorials.
In Visual Studio, in the Solution Explorer, click App.xaml.cs.
In the App class, add an override for the OnStartup() function to set the ApiKey property on ArcGISRuntimeEnvironment.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
publicpartialclassApp : Application {
protectedoverridevoidOnStartup(StartupEventArgs e) {
base.OnStartup(e);
// Note: it is not best practice to store API keys in source code.// The API key is referenced here for the convenience of this tutorial. Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_API_KEY";
}
}
}
If you are developing with Visual Studio for Windows, ArcGIS Maps SDK for .NET provides a set of project templates for each supported .NET platform. These templates provide all of the code needed for a basic Model-View-ViewModel (MVVM) app. Install the ArcGIS Maps SDK for .NET Visual Studio Extension to add the templates to Visual Studio (Windows only). See Install and set up for details.
Update the tutorial name used in the project (optional)
The Visual Studio solution, project, and the namespace for all classes currently use the name DisplayAMap. Follow the steps below if you prefer the name to reflect the current tutorial. These steps are not required, your code will still work if you keep the original name.
The tutorial instructions and code use the name FindARouteAndDirections for the solution, project, and namespace. You can choose any name you like, but it should be the same for each of these.
Update the name for the solution and the project.
In Visual Studio, in the Solution Explorer, right-click the solution name and choose Rename. Provide the new name for your solution.
In the Solution Explorer, right-click the project name and choose Rename. Provide the new name for your project.
Rename the namespace used by classes in the project.
In the Solution Explorer, expand the project node.
Double-click MapViewModel.cs in the Solution Explorer to open the file.
In the MapViewModel class, double-click the namespace name (DisplayAMap) to select it, and then right-click and choose Rename....
Provide the new name for the namespace.
Click Apply in the Rename: DisplayAMap window that appears in the upper-right of the code window. This will rename the namespace throughout your project.
Build the project.
Choose Build > Build solution (or press <F6>).
Update the basemap and initial extent
For displaying routes and driving directions, a streets basemap usually works best. You will update the Map to use the ArcGISStreets basemap and center the display on Los Angeles, California.
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml.cs to open the file.
A view defined with XAML, such as MainWindow, is composed of two files in a Visual Studio project. The visual elements (such as map views, buttons, text boxes, and so on) are defined with XAML markup in a .xaml file. This file is often referred to as the "page". The code for the XAML elements is stored in an associated .xaml.cs file that is known as the "code-behind", since it stores the code behind the controls. Keeping with the MVVM design pattern, user interface events (such as the code that responds to a button click) are handled in the code-behind for the view.
Update the Viewpoint that the MapView initially shows when the app initializes. This viewpoint will show an area around Los Angeles, California.
In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.
The project uses the Model-View-ViewModel (MVVM) design pattern to separate the application logic (view model) from the user interface (view). MapViewModel.cs contains the view model class for the application, called MapViewModel. See the Microsoft documentation for more information about the Model-View-ViewModel pattern.
In the SetupMap() function, update the Map to use the BasemapStyle.ArcGISStreets basemap.
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.
You should see a streets map centered on an area of Los Angeles.
Define member variables
You will need member variables in the MapViewModel class to store the status of user-defined route stops and several Graphic objects for displaying route results.
Add additional required using statements to the top of the MapViewModel class.
Classes in the Esri.ArcGISRuntime.Tasks.NetworkAnalysis namespace provide network analysis functionality, such as solving routes, finding closest facilities, or defining service areas on a street network.
Create the enum with values that represent the three possible contexts for clicks on the map. Add a private variable to track the current click state.
The user will click the map to define the origin and destination locations for the route. If neither stop has been defined, a map click will be used for the origin ("from") location. If an origin is defined, the click will be used to define the destination ("to") location. If both are defined, you may choose to start over and use the click to define a new origin location. This enum has values that represent the context of these clicks so the code can respond appropriately.
Create additional member variables for the route result graphics. These graphics will show the stops (origin and destination locations) and the route result polyline that connects them.
Add properties for graphics overlays and driving directions
A graphics overlay is a container for graphics that are always displayed on top of all the other layers in the map. You will use graphics overlays to display graphics for a Route and its stops.
A Route provides turn-by-turn directions with its DirectionManeuvers property. You will expose the directions with a property in MapViewModel so they can be bound to a control in the app's UI.
In the view model, create a new property named GraphicsOverlays. This will be a collection of GraphicsOverlay that will store point, line, and polygon graphics.
Create a new GraphicsOverlay to contain graphics for the Route result and stops. Create a GraphicsOverlayCollection that contains the overlay and use it to set the MapViewModel.GraphicsOverlays property.
The Geometry for each graphic is initially null and will not display until a valid geometry is assigned (for example, when the user clicks to define a stop location).
Create a function to reset the current route creation state. The function will set the Geometry for each result Graphic to null, clear driving directions text from the MapViewModel.Directions property, and set the status variable to RouteBuilderStatus.NotStarted.
You will create a function that uses the route service to find the best route between two stops.
Create a new asynchronous function called FindRoute().
When calling methods asynchronously inside a function (using the await keyword), the async keyword is required in the signature.
Asynchronous functions that don't return a value should have a return type of Task. Although a void return type would continue to work, this is not considered best practice. Exceptions thrown by an async void method cannot be caught outside of that method, are difficult to test, and can cause serious side effects if the caller is not expecting them to be asynchronous. The only circumstance where async void is acceptable is when using an event handler, such as a button click.
Use the RouteTask to solve the route. If the RouteResult contains a Route, set the route graphic geometry with the result geometry, set the MapViewModel.Directions property with the DirectionManeuvers, and reset the current state. If no route was found, reset the state and throw an exception to alert the user.
The user will tap (or click) locations on the map to define start and end points for the route. The MapView control will accept the user input but the MapViewModel class will contain the logic to handle tap locations and to define stops for solving the route.
Create a function in MapViewModel to handle MapPoint input from the user. Depending on the current RouteBuilderStatus, the point sets the geometry for the start or end location graphic. If the current point defines the end location, a call to FindRoute() solves the route.
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml.cs to open the file.
Add a handler for the GeoView.GeoViewTapped event. The event will fire when the user taps (or clicks) the MapView. The tapped location will be passed to MapViewModel.HandleTap().
Asynchronous functions should return Task or Task<T>. For event handlers, such as the Button.Click handler, the function must return void to conform to the delegate signature. See the Microsoft documentation regarding Async return types.
MapViewModel has properties for graphics overlays (MapViewModel.GraphicsOverlays) and driving directions (MapViewModel.Directions) that must be bound to UI elements to be presented to the user. The GeoView.GeoViewTapped event must also be handled so the view model can accept map locations from the user.
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml to open the file.
Use data binding to bind the GraphicsOverlays property of the MapViewModel to the MapView control. Handle the GeoViewTapped event with the MainMapView_GeoViewTapped function.
Data binding and the Model-View-ViewModel (MVVM) design pattern allow you to separate the logic in your app (the view model) from the presentation layer (the view). Graphics can be added and removed from the graphics overlays in the view model, and those changes appear in the map view through data binding.
Add a ListView element and bind its ItemSource to the MapViewModel.Directions property. When a route is successfully solved, the turn-by-turn directions will appear here.
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.
Clicks on the map should alternate between creating an origin and destination point. When both points are defined, the route task uses the route service to find the best route and provide turn-by-turn directions.