Learn how to find a route and directions with the route service

Routing is the process of finding the path from an origin
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 need an ArcGIS Location Platform or ArcGIS Online account.
-
Ensure your development environment meets the system requirements.
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.
Set up authentication
To access the secure ArcGIS location services
You can implement API key authentication or user authentication in this tutorial. Compare the differences below:
API key authentication
- Users are not required to sign in.
- Requires creating an API key credential
API key credentials are an item that contains the parameters used to create and manage long-lived access tokens for API key authentication. They are a type of developer credential. with the correct privileges. - API keys
An API key is a long-lived access token created using API key credentials. They are valid for up to one year and are typically embedded directly into client applications. are long-lived access tokens. - Service usage is billed to the API key owner/developer.
- Simplest authentication method to implement.
- Recommended approach for new ArcGIS developers.
Learn more in API key authentication.
User authentication
- Users are required to sign in with an ArcGIS account
An ArcGIS account is an identity with a user type and set of privileges that can access specific ArcGIS products, tools, APIs, services, and resources. The main account types that can be used for development are an ArcGIS Location Platform account, ArcGIS Online account, and ArcGIS Enterprise account. ArcGIS Location Platform and ArcGIS Online accounts are also associated with a subscription. . - User accounts must have privilege
Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. to access the ArcGIS servicesA service, also known as an ArcGIS service, is software that supports an ArcGIS REST API and provides geospatial functionality or data. A service can be hosted by Esri or in ArcGIS Enterprise. used in application. - Requires creating OAuth credentials
OAuth credentials are an item that contains parameters required to implement user authentication or app authentication, including a .client_id,client_secret, and redirect URIs. They are a type of developer credential. - Application uses a redirect URL and client ID.
- Service usage is billed to the organization of the user signed into the application.
Learn more in User authentication.
To complete this tutorial, click on the tab in the switcher below for your authentication type of choice, either API key authentication or User authentication.
Create a new API key access token
-
Complete the Create an API key tutorial and create an API key with the following privilege(s)
Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. :- Privileges
- Location services > Basemaps
- Location services > Routing
- Privileges
-
Copy and paste the API key access token into a safe location. It will be used in a later step.
Create new OAuth credentials to access the secure resources used in this tutorial.
-
Complete the Create OAuth credentials for user authentication tutorial to obtain a Client ID and Redirect URL.
A
Client IDuniquely identifies your app on the authenticating server. If the server cannot find an app with the provided Client ID, it will not proceed with authentication.The
Redirect URL(also referred to as a callback url) is used to identify a response from the authenticating server when the system returns control back to your app after an OAuth login. Since it does not necessarily represent a valid endpoint that a user could navigate to, the redirect URL can use a custom scheme, such asmy-app://auth. It is important to make sure the redirect URL used in your app’s code matches a redirect URL configured on the authenticating server. -
Copy and paste the Client ID and Redirect URL into a safe location. They will be used in a later step.
All users that access this application need account privileges
Develop or download
You have two options for completing this tutorial:
Option 1: Develop the code
To start the tutorial, complete the Display a map tutorial. This creates a map to display the Santa Monica Mountains in California using the topographic basemap from the ArcGIS Basemap Styles service
Open a Visual Studio solution
- Open the Visual Studio solution you created by completing the Display a map tutorial.
- Continue with the following instructions to find a route and directions with the ArcGIS Routing service
A routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. .
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
MapViewModelclass, double-click the namespace name (DisplayAMap) to select it, and then right-click and choose Rename…. - Provide the new name for the namespace.
- Hit Enter to confirm the new name. This will rename the namespace throughout your project.
-
Build the project.
- Choose Build > Build solution (or press <F6>).
Set developer credentials
If you implemented API key authenticationRouteTask. To create an API Key access token that has the Basemaps and Routing privileges, see the Set up authentication step and then follow the instructions below.
-
In the Solution Explorer, expand the node for App.xaml, and double-click App.xaml.cs to open it.
-
In the App class, in the override for the
OnStartup()function, set theApiKeyproperty onArcGISRuntimeEnvironmentwith your new API key (with additional privileges besides basemap).App.xaml.cspublic partial class App : Application{protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";}}} -
Save and close the
App.xaml.csfile.
Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
-
From the Visual Studio Project menu, choose Add class …. Name the class
ArcGISLoginPrompt.csthen click Add. The new class is added to your project and opens in Visual Studio. -
Select all the code in the new class and delete it.
-
Copy all of the code below and paste it into the
ArcGISLoginPrompt.csclass in your project.ArcGISLoginPrompt.cs// Copyright 2021 Esri.//// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific// language governing permissions and limitations under the License.using Esri.ArcGISRuntime.Portal;using Esri.ArcGISRuntime.Security;using Microsoft.Web.WebView2.Core;using Microsoft.Web.WebView2.Wpf;using System;using System.Collections.Generic;using System.Threading.Tasks;using System.Windows;using System.Windows.Threading;namespace UserAuth{internal static class ArcGISLoginPrompt{private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";// Specify the Client ID and Redirect URL to use with OAuth authentication.// See the instructions here for creating OAuth app settings:// https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/private const string AppClientId = "YOUR_CLIENT_ID";private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL";public static async Task<bool> EnsureAGOLCredentialAsync(){bool loggedIn = false;try{// Create the portal, prompting the user to log in if they haven't already.var portal = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl), loginRequired: true);// If the user logged in successfully, the portal's User property will be non-null.loggedIn = portal.User != null;}catch (OperationCanceledException){// OAuth login was canceled, no need to display error to user.}catch (Exception ex){// Login failureMessageBox.Show("Login failed: " + ex.Message);}return loggedIn;}public static void RegisterOAuthConfig(){var userConfig = new OAuthUserConfiguration(new Uri(ArcGISOnlineUrl), AppClientId, new Uri(OAuthRedirectUrl));AuthenticationManager.Current.OAuthUserConfigurations.Add(userConfig);AuthenticationManager.Current.OAuthHandler = new OAuthAuthorize();}#region OAuth handler// In a desktop (WPF) app, an IOAuthHandler component is used to handle some of the OAuth details. Specifically, it// implements AuthorizeAsync to show the login UI (generated by the server that hosts secure content) in a web control.// When the user logs in successfully, cancels the login, or closes the window without continuing, the IOAuthAuthorizeHandler// is responsible for obtaining the authorization from the server or raising an OperationCanceledException.public class OAuthAuthorize : IOAuthHandler{// Window to contain the OAuth UI.private Window? _authWindow;// Use a TaskCompletionSource to track the completion of the authorization.private TaskCompletionSource<IDictionary<string, string>> _tcs;// URL for the authorization callback result (the redirect URI configured for your application).private string _callbackUrl = "";// URL that handles the OAuth request.private string? _authorizeUrl;// Function to handle authorization requests, takes the URIs for the secured service, the authorization endpoint, and the redirect URI.public Task<IDictionary<string, string>> LoginAsync(OAuthLoginParameters parameters){if (_tcs != null && !_tcs.Task.IsCompleted)throw new Exception("Task in progress");_tcs = new TaskCompletionSource<IDictionary<string, string>>();// Store the authorization and redirect URLs._authorizeUrl = parameters.AuthorizeUri.AbsoluteUri;_callbackUrl = parameters.RedirectUri.AbsoluteUri;// Call a function to show the login controls, make sure it runs on the UI thread for this app.Dispatcher dispatcher = Application.Current.Dispatcher;if (dispatcher == null || dispatcher.CheckAccess()){AuthorizeOnUIThread(_authorizeUrl);}else{Action authorizeOnUIAction = () => AuthorizeOnUIThread(_authorizeUrl);dispatcher.BeginInvoke(authorizeOnUIAction);}// Return the task associated with the TaskCompletionSource.return _tcs.Task;}// Challenge for OAuth credentials on the UI thread.private void AuthorizeOnUIThread(string authorizeUri){// Initialize a WebView2 control to display the authorize page.WebView2 webBrowser = new WebView2() { MinWidth = 500, MinHeight = 500 };// Handle the navigation event for the browser to check for a response to the redirect URL.webBrowser.NavigationStarting += WebBrowserOnNavigationStarting;// Display the web browser in a new window._authWindow = new Window{Content = webBrowser,SizeToContent = SizeToContent.WidthAndHeight,WindowStartupLocation = WindowStartupLocation.CenterOwner};// Set the app's window as the owner of the browser window (if main window closes, so will the browser).if (Application.Current != null && Application.Current.MainWindow != null){_authWindow.Owner = Application.Current.MainWindow;}// Handle window loaded event as the WebView2 control can only be initialized after it is visible in the UI_authWindow.Loaded += async (s, e) =>{await webBrowser.EnsureCoreWebView2Async();webBrowser.CoreWebView2.Navigate(authorizeUri);};// Handle the window closed event_authWindow.Closed += OnWindowClosed;// Display the window._authWindow.ShowDialog();}// Handle the browser window closing.private void OnWindowClosed(object? sender, EventArgs e){// If the browser window closes, return the focus to the main window.if (_authWindow != null && _authWindow.Owner != null){_authWindow.Owner.Focus();}// If the task wasn't completed, the user must have closed the window without logging in.if (!_tcs.Task.IsCompleted){// Set the task completion source exception to indicate a canceled operation._tcs.SetCanceled();}_authWindow = null;}// Handle browser navigationprivate void WebBrowserOnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e){// Check for a response to the callback url.const string portalApprovalMarker = "/oauth2/approval";Uri uri = new Uri(e.Uri);// If no browser, uri, or an empty url, return.if (sender == null || uri == null || string.IsNullOrEmpty(uri.AbsoluteUri))return;// Check for redirect.bool isRedirected = uri.AbsoluteUri.StartsWith(_callbackUrl) ||_callbackUrl.Contains(portalApprovalMarker) && uri.AbsoluteUri.Contains(portalApprovalMarker);// Check if browser was redirected to the callback URL. (This indicates succesful authentication.)if (isRedirected){e.Cancel = true;// Call a helper function to decode the response parameters.IDictionary<string, string> authResponse = DecodeParameters(uri);// Set the result for the task completion source._tcs.SetResult(authResponse);// Close the window.if (_authWindow != null){_authWindow.Close();}}}private static IDictionary<string, string> DecodeParameters(Uri uri){// Create a dictionary of key value pairs returned in an OAuth authorization response URI query string.string answer = "";// Get the values from the URI fragment or query string.if (!string.IsNullOrEmpty(uri.Fragment)){answer = uri.Fragment.Substring(1);}else{if (!string.IsNullOrEmpty(uri.Query)){answer = uri.Query.Substring(1);}}// Parse parameters into key / value pairs.Dictionary<string, string> keyValueDictionary = new Dictionary<string, string>();string[] keysAndValues = answer.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries);foreach (string kvString in keysAndValues){string[] pair = kvString.Split('=');string key = pair[0];string value = string.Empty;if (key.Length > 1){value = Uri.UnescapeDataString(pair[1]);}keyValueDictionary.Add(key, value);}// Return the dictionary of string keys/values.return keyValueDictionary;}}#endregion OAuth handler}} -
Add your values for the client ID (
AppClientId) and for the redirect URL (OAuthRedirectUrl). These are the user authentication settings you created in the Set up authentication step.ArcGISLoginPrompt.csinternal static class ArcGISLoginPrompt{private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";// Specify the Client ID and Redirect URL to use with OAuth authentication.// See the instructions here for creating OAuth app settings:// https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/private const string AppClientId = "YOUR_CLIENT_ID";private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL"; -
In the Solution Explorer, expand the node for App.xaml, and double-click App.xaml.cs to open it.
-
In the App class, in the override for the
OnStartup()function, call theSetChallengeHandler()method on your staticArcGISLoginPromptclass.App.xaml.cspublic partial class App : Application{protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();}}} -
Save and close the
App.xaml.csfile.
Best Practice: The OAuth credentials are stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
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 MapViewModel.cs to open the file.
-
In the
SetupMap()function, update theMapto use theBasemapStyle.ArcGISStreetsbasemap.MapViewModel.csprivate void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets); -
Update the
Viewpointthat theMapViewshows when the map initializes. This viewpoint will show an area around Los Angeles, California.MapViewModel.csprivate void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000); -
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
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 stopsGraphic objects for displaying route results.
-
Add additional required
usingstatements to the top of theMapViewModelclass.Classes in the
Esri.ArcGISRuntime.Tasks.NetworkAnalysisnamespace provide network analysis functionality, such as solving routes, finding closest facilities, or defining service areas on a street network.Esri.ArcGISRuntime.UIcontains theGraphicandGraphicsOverlayclasses.Esri.ArcGISRuntime.Symbologycontains the classes that define the symbols and renderers used to display features and graphics.MapViewModel.csusing System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI; -
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
An origin is a point that defines the start of a route. and destinationA destination is a point that defines the final stop in a route. locations for the routeA route is a polyline that defines the best path between two or more points in a street network. . If neither stopA stop is a single point along a route: it can be the origin, an intermediate stop, or destination. 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.MapViewModel.cs27 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;40 collapsed linespublic MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model's Map property with the map.Map = map;}}} -
Create additional member variables for the route result graphics. These graphics will show the stops
A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. (origin and destination locations) and the route result polylineA polyline is a type of geometry containing ordered point coordinates and a spatial reference. that connects them.MapViewModel.cs32 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();40 collapsed linespublic MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model's Map property with the map.Map = map;}}}
Add properties for graphics overlays and driving directions
A graphics overlayRoute 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 ofGraphicsOverlaythat will store pointA point is a type of geometry containing a single set of , linex,ycoordinates and a spatial reference.A polyline is a type of geometry containing ordered point coordinates and a spatial reference. , and polygonA polygon is a type of geometry containing an array of rings and a spatial reference. Each ring contains an array of point coordinates, where the first and last point are the same. graphics.MapViewModel.cs55 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}18 collapsed linesprivate void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model's Map property with the map.Map = map;}}} -
Create a property in
MapViewModelthat exposes a list of driving directions for aRoute.MapViewModel.cs66 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}18 collapsed linesprivate void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);// Set the view model's Map property with the map.Map = map;}}}
Create route graphics
You will define the symbology for each Route result Graphic and add them to a GraphicsOverlay.
-
Create a new
GraphicsOverlayto contain graphics for theRouteresult and stopsA stop is a single point along a route: it can be the origin, an intermediate stop, or destination. . Create aGraphicsOverlayCollectionthat contains the overlay and use it to set theMapViewModel.GraphicsOverlaysproperty.MapViewModel.cs88 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};7 collapsed lines// Set the view model's Map property with the map.Map = map;}}} -
Create each result
Graphicand define itsSymbol.The
Geometryfor each graphic is initiallynulland will not display until a valid geometryA geometry is a geometric shape, such as a point, polyline, or polygon, that contains one or more coordinates and a spatial reference. is assigned (for example, when the user clicks to define a stopA stop is a single point along a route: it can be the origin, an intermediate stop, or destination. location).MapViewModel.cs99 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));7 collapsed lines// Set the view model's Map property with the map.Map = map;}}} -
Add the graphics to the
GraphicsOverlay.MapViewModel.cs125 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });7 collapsed lines// Set the view model's Map property with the map.Map = map;}}} -
Create a function to reset the current route creation state. The function will set the
Geometryfor each resultGraphictonull, clear driving directions text from theMapViewModel.Directionsproperty, and set the status variable toRouteBuilderStatus.NotStarted.MapViewModel.cs131 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });// Set the view model's Map property with the map.Map = map;}private void ResetState(){_startGraphic.Geometry = null;_endGraphic.Geometry = null;_routeGraphic.Geometry = null;Directions = null;_currentState = RouteBuilderStatus.NotStarted;}3 collapsed lines}}
Find a route between two stops
You will create a function that uses the route service
-
Create a new asynchronous function called
FindRoute().When calling methods asynchronously inside a function (using the
awaitkeyword), theasynckeyword is required in the signature.Asynchronous functions that don’t return a value should have a return type of
Task. Although avoidreturn type would continue to work, this is not considered best practice. Exceptions thrown by anasync voidmethod 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 whereasync voidis acceptable is when using an event handler, such as a button click.See the Microsoft documentation for more information about Asynchronous programming with async and await.
MapViewModel.cs137 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });// Set the view model's Map property with the map.Map = map;}private void ResetState(){_startGraphic.Geometry = null;_endGraphic.Geometry = null;_routeGraphic.Geometry = null;Directions = null;_currentState = RouteBuilderStatus.NotStarted;}public async Task FindRoute(){}3 collapsed lines}} -
Create route
Stopobjects using the start and end graphics’ geometry.MapViewModel.cs146 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });// Set the view model's Map property with the map.Map = map;}private void ResetState(){_startGraphic.Geometry = null;_endGraphic.Geometry = null;_routeGraphic.Geometry = null;Directions = null;_currentState = RouteBuilderStatus.NotStarted;}public async Task FindRoute(){if(_startGraphic.Geometry == null || _endGraphic.Geometry == null) return;var stops = new [] { _startGraphic, _endGraphic }.Select(graphic =>{var geometry = graphic.Geometry as MapPoint;return new Stop(geometry!);});5 collapsed lines}}} -
Create a new
RouteTaskthat uses the route serviceA routing service is a service that uses network analysis and streets data to calculate the most effective path and turn-by-turn directions on a street network, optimize fleet routing and deliveries, find the closest facilities, calculate service areas, and more. It is hosted by Esri as the ArcGIS Routing service and can also be hosted in ArcGIS Enterprise. . CreateRouteParameters,SetStopsand request toReturnRoutesandReturnDirectionswith the result.MapViewModel.cs149 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });// Set the view model's Map property with the map.Map = map;}private void ResetState(){_startGraphic.Geometry = null;_endGraphic.Geometry = null;_routeGraphic.Geometry = null;Directions = null;_currentState = RouteBuilderStatus.NotStarted;}public async Task FindRoute(){if(_startGraphic.Geometry == null || _endGraphic.Geometry == null) return;var stops = new [] { _startGraphic, _endGraphic }.Select(graphic =>{var geometry = graphic.Geometry as MapPoint;return new Stop(geometry!);});var routeTask = await RouteTask.CreateAsync(new Uri("https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"));RouteParameters parameters = await routeTask.CreateDefaultParametersAsync();parameters.SetStops(stops);parameters.ReturnDirections = true;parameters.ReturnRoutes = true;5 collapsed lines}}} -
Use the
RouteTaskto solve the route. If theRouteResultcontains aRoute, set the routeA route is a polyline that defines the best path between two or more points in a street network. graphic geometryA geometry is a geometric shape, such as a point, polyline, or polygon, that contains one or more coordinates and a spatial reference. with the result geometry, set theMapViewModel.Directionsproperty with theDirectionManeuvers, and reset the current state. If no route was found, reset the state and throw an exception to alert the user.MapViewModel.cs156 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });// Set the view model's Map property with the map.Map = map;}private void ResetState(){_startGraphic.Geometry = null;_endGraphic.Geometry = null;_routeGraphic.Geometry = null;Directions = null;_currentState = RouteBuilderStatus.NotStarted;}public async Task FindRoute(){if(_startGraphic.Geometry == null || _endGraphic.Geometry == null) return;var stops = new [] { _startGraphic, _endGraphic }.Select(graphic =>{var geometry = graphic.Geometry as MapPoint;return new Stop(geometry!);});var routeTask = await RouteTask.CreateAsync(new Uri("https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"));RouteParameters parameters = await routeTask.CreateDefaultParametersAsync();parameters.SetStops(stops);parameters.ReturnDirections = true;parameters.ReturnRoutes = true;var result = await routeTask.SolveRouteAsync(parameters);if (result?.Routes?.FirstOrDefault() is Route routeResult){_routeGraphic.Geometry = routeResult.RouteGeometry;Directions = routeResult.DirectionManeuvers.Select(maneuver => maneuver.DirectionText).ToList();_currentState = RouteBuilderStatus.NotStarted;}else{ResetState();throw new Exception("Route not found");}5 collapsed lines}}}
Handle user taps on the map
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
-
Create a function in
MapViewModelto handleMapPointinput from the user. Depending on the currentRouteBuilderStatus, the point sets the geometry for the start or end location graphic. If the current point defines the end location, a call toFindRoute()solves the route.MapViewModel.cs165 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.ComponentModel;using System.Runtime.CompilerServices;using System.Text;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using System.Linq;using System.Threading.Tasks;using Esri.ArcGISRuntime.Symbology;using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;using Esri.ArcGISRuntime.UI;namespace FindARouteAndDirections{class MapViewModel : INotifyPropertyChanged{enum RouteBuilderStatus{NotStarted, // No locations have been defined.SelectedStart, // Origin point exists.SelectedStartAndEnd // Origin and destination exist.}private RouteBuilderStatus _currentState = RouteBuilderStatus.NotStarted;private Graphic _startGraphic = new();private Graphic _endGraphic = new();private Graphic _routeGraphic = new();public MapViewModel(){SetupMap();}public event PropertyChangedEventHandler? PropertyChanged;protected void OnPropertyChanged([CallerMemberName] string propertyName = ""){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}private Map? _map;public Map? Map{get { return _map; }set{_map = value;OnPropertyChanged();}}private GraphicsOverlayCollection? _graphicsOverlayCollection;public GraphicsOverlayCollection? GraphicsOverlays{get { return _graphicsOverlayCollection; }set{_graphicsOverlayCollection = value;OnPropertyChanged();}}private List<string>? _directions;public List<string>? Directions{get { return _directions; }set{_directions = value;OnPropertyChanged();}}private void SetupMap(){var map = new Map(BasemapStyle.ArcGISStreets);// Set the initial viewpoint around the Santa Monica Mountains in California.var mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);map.InitialViewpoint = new Viewpoint(mapCenterPoint, 100000);GraphicsOverlay routeAndStopsOverlay = new GraphicsOverlay();this.GraphicsOverlays = new GraphicsOverlayCollection{routeAndStopsOverlay};var startOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Blue, 2);_startGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Diamond,Color = System.Drawing.Color.Orange,Size = 8,Outline = startOutlineSymbol});var endOutlineSymbol = new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid, color: System.Drawing.Color.Red, width: 2);_endGraphic = new Graphic(null, new SimpleMarkerSymbol{Style = SimpleMarkerSymbolStyle.Square,Color = System.Drawing.Color.Green,Size = 8,Outline = endOutlineSymbol});_routeGraphic = new Graphic(null, new SimpleLineSymbol(style: SimpleLineSymbolStyle.Solid,color: System.Drawing.Color.Blue,width: 4));routeAndStopsOverlay.Graphics.AddRange(new [] { _startGraphic, _endGraphic, _routeGraphic });// Set the view model's Map property with the map.Map = map;}private void ResetState(){_startGraphic.Geometry = null;_endGraphic.Geometry = null;_routeGraphic.Geometry = null;Directions = null;_currentState = RouteBuilderStatus.NotStarted;}public async Task FindRoute(){if(_startGraphic.Geometry == null || _endGraphic.Geometry == null) return;var stops = new [] { _startGraphic, _endGraphic }.Select(graphic =>{var geometry = graphic.Geometry as MapPoint;return new Stop(geometry!);});var routeTask = await RouteTask.CreateAsync(new Uri("https://route-api.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"));RouteParameters parameters = await routeTask.CreateDefaultParametersAsync();parameters.SetStops(stops);parameters.ReturnDirections = true;parameters.ReturnRoutes = true;var result = await routeTask.SolveRouteAsync(parameters);if (result?.Routes?.FirstOrDefault() is Route routeResult){_routeGraphic.Geometry = routeResult.RouteGeometry;Directions = routeResult.DirectionManeuvers.Select(maneuver => maneuver.DirectionText).ToList();_currentState = RouteBuilderStatus.NotStarted;}else{ResetState();throw new Exception("Route not found");}}public async Task HandleTap(MapPoint tappedPoint){switch (_currentState){case RouteBuilderStatus.NotStarted:ResetState();_startGraphic.Geometry = tappedPoint;_currentState = RouteBuilderStatus.SelectedStart;break;case RouteBuilderStatus.SelectedStart:_endGraphic.Geometry = tappedPoint;_currentState = RouteBuilderStatus.SelectedStartAndEnd;await FindRoute();break;case RouteBuilderStatus.SelectedStartAndEnd:// Ignore map clicks while routing is in progressbreak;}}3 collapsed lines}} -
In the Visual Studio > Solution Explorer, double-click MainWindow.xaml.cs to open the file.
-
Add a handler for the
GeoView.GeoViewTappedevent. The event will fire when the user taps (or clicks) theMapView. The tapped location will be passed toMapViewModel.HandleTap().Asynchronous functions should return
TaskorTask<T>. For event handlers, such as theButton.Clickhandler, the function must returnvoidto conform to the delegate signature. See the Microsoft documentation regarding Async return types.MainWindow.xaml.cs41 collapsed lines// Copyright 2021 Esri// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// https://www.apache.org/licenses/LICENSE-2.0//// Unless required by applicable law or agreed to in writing, software// distributed under the License is distributed on an "AS IS" BASIS,// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.// See the License for the specific language governing permissions and// limitations under the License.using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using Esri.ArcGISRuntime.Geometry;using Esri.ArcGISRuntime.Mapping;using Esri.ArcGISRuntime.UI.Controls;namespace FindARouteAndDirections{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}public async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e){try{var viewmodel = Resources["MapViewModel"] as MapViewModel;if (viewmodel != null && e?.Location != null){await viewmodel.HandleTap(e.Location);}}catch (Exception ex){MessageBox.Show("Error", ex.Message);}}3 collapsed lines}}
Bind UI elements to the view model
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
GraphicsOverlaysproperty of theMapViewModelto theMapViewcontrol. Handle theGeoViewTappedevent with theMyMapView_GeoViewTappedfunction.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
A map view is a user interface that displays map layers and graphics in 2D. It controls the area (extent) of the map that is visible and supports user interactions such as pan and zoom. through data binding.MainWindow.xaml10 collapsed lines<Window x:Class="FindARouteAndDirections.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:FindARouteAndDirections"xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><local:MapViewModel x:Key="MapViewModel" /></Window.Resources><Grid><esri:MapView x:Name="MyMapView"Map="{Binding Map, Source={StaticResource MapViewModel}}"GraphicsOverlays="{Binding GraphicsOverlays, Source={StaticResource MapViewModel}}"GeoViewTapped="MyMapView_GeoViewTapped" />11 collapsed lines<Border Background="White"BorderBrush="Black"Margin="10"HorizontalAlignment="Right"VerticalAlignment="Top"Width="300" Height="200"></Border></Grid></Window> -
Add a
ListViewelement and bind itsItemSourceto theMapViewModel.Directionsproperty. When a route is successfully solved, the turn-by-turn directions will appear here.MainWindow.xaml19 collapsed lines<Window x:Class="FindARouteAndDirections.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:FindARouteAndDirections"xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><local:MapViewModel x:Key="MapViewModel" /></Window.Resources><Grid><esri:MapView x:Name="MyMapView"Map="{Binding Map, Source={StaticResource MapViewModel}}"GraphicsOverlays="{Binding GraphicsOverlays, Source={StaticResource MapViewModel}}"GeoViewTapped="MyMapView_GeoViewTapped" /><Border Background="White"BorderBrush="Black"Margin="10"HorizontalAlignment="Right"VerticalAlignment="Top"Width="300" Height="200"><ListView ItemsSource="{Binding Directions, Mode=OneWay, Source={StaticResource MapViewModel}}" />4 collapsed lines</Border></Grid></Window>
Run the app
-
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
Clicks on the map should alternate between creating an origin
Alternatively, you can download the tutorial solution, as follows.
Option 2: Download the solution
-
Click the Download solution link in the right-hand panel of the page.
-
Unzip the file to a location on your machine.
-
Open the
.slnfile in Visual Studio.
Since the downloaded solution does not contain authentication credentials, you must add the developer credentials that you created in the Set up authentication section.
Set developer credentials in the solution
To allow your app users to access ArcGIS location services
-
In Visual Studio, in the Solution Explorer, click App.xaml.cs to open the file.
-
Set the
ArcGISEnvironment.ApiKeyproperty with your API key access token.App.xaml.csprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();} -
Remove the code that sets up user authentication.
App.xaml.csprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();}
Best Practice: The access token is stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
-
From the Visual Studio Solution explorer window, open the
ArcGISLoginPrompt.csfile. -
Set your values for the client ID (
OAuthClientID) and the redirect URL (OAuthRedirectUrl). These are the user authentication settings you created in the Set up authentication step.ArcGISLoginPrompt.csinternal static class ArcGISLoginPrompt{private const string ArcGISOnlineUrl = "https://www.arcgis.com/sharing/rest";// Specify the Client ID and Redirect URL to use with OAuth authentication.// See the instructions here for creating OAuth app settings:// https://developers.arcgis.com/documentation/security-and-authentication/user-authentication/tutorials/create-oauth-credentials-user-auth/private const string AppClientId = "YOUR_CLIENT_ID";private const string OAuthRedirectUrl = "YOUR_REDIRECT_URL"; -
In Visual Studio, in the Solution Explorer, click App.xaml.cs to open the file.
-
Remove the line of code that sets an API key access token.
App.xaml.csprotected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// Set the access token for ArcGIS Maps SDK for .NET.Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_ACCESS_TOKEN";// Call a function to set up the AuthenticationManager for OAuth.UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();}
Best Practice: The OAuth credentials are stored directly in the code as a convenience for this tutorial. Do not store credentials directly in source code in a production environment.
Run the solution
Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app. If your app uses user authentication, enter your ArcGIS Online credentials when prompted.
Clicks on the map should alternate between creating an origin
What’s next?
To explore more API features and ArcGIS location services, try the following tutorial: