Learn how to find a route and directions with the route 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. Learn more .

find a route and directions

Routing is the process of finding the path from an origin An origin is a point that defines the start of a route. Learn more to a destination A destination is a point that defines the final stop in a route. Learn more in a street network. You can use the 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. Learn more to find routes A route is a polyline that defines the best path between two or more points in a street network. Learn more , 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:

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 ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more used in this tutorial, you must implement API key authentication API key authentication is a type of authentication that uses an API key to authenticate requests to ArcGIS services and secure portal items. Learn more or user authentication User authentication is a type of authentication that allows users with an ArcGIS account to sign into an application and allow it to access ArcGIS content, services, and resources on their behalf. The typical authorization protocol used is OAuth2.0. Learn more using an ArcGIS Location Platform An ArcGIS Location Platform account, formerly known as an ArcGIS Developer account, is an identity associated with an ArcGIS Location Platform subscription. Learn more or an ArcGIS Online An ArcGIS Online account, also known as an ArcGIS Organization account, is an identity associated with an ArcGIS Online subscription. It can be used to access ArcGIS tools and develop applications with ArcGIS location services for an organization. Learn more account.

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 An access token is an authorization string that provides access to secure ArcGIS content, data, and services. Its capabilities are determined by the privileges it supports. It is obtained by implementing API key authentication, User authentication, or App authentication. Learn more with privileges Privileges are a set of permissions assigned to ArcGIS accounts, developer credentials, and applications that grant access to secure resources and functionality in ArcGIS. Learn more to access the secure resources used in this tutorial.

  1. 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. Learn more :

    • Privileges
      • Location services > Basemaps
      • Location services > Routing
  2. Copy and paste the API key access token into a safe location. It will be used in a later step.

Develop or download

You have two options for completing this tutorial:

  1. Option 1: Develop the code or
  2. Option 2: Download the completed solution

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 The ArcGIS Basemap Styles service, also referred to as the Basemap Styles service, is a location service that provides basemap styles and data for the world. It returns styles as Mapbox styles and web maps, and data as vector tiles and/or map tiles. It supports all of the styles in the ArcGIS Basemap style and Open Basemap style family. An ArcGIS Location Platform or ArcGIS Online account is required to use the service. Learn more .

Open a Visual Studio solution

  1. Open the Visual Studio solution you created by completing the Display a map tutorial.
  2. 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. Learn more .

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.

Set developer credentials

If you implemented API key authentication API key authentication is a type of authentication that uses an API key to authenticate requests to ArcGIS services and secure portal items. Learn more in the Display a map tutorial, the API key access token will only have the Basemaps privilege. The Find a route and directions tutorial requires the Routing privilege to find a route using the RouteTask. 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.

  1. In the Solution Explorer, expand the node for App.xaml, and double-click App.xaml.cs to open it.

  2. In the App class, in the override for the OnStartup() function, set the ApiKey property on ArcGISRuntimeEnvironment with your new API key (with additional privileges besides basemap).

    App.xaml.cs
    public 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";
    }
    }
    }
  3. Save and close the App.xaml.cs file.

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.

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.

  1. In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.

  2. In the SetupMap() function, update the Map to use the BasemapStyle.ArcGISStreets basemap.

    MapViewModel.cs
    private void SetupMap()
    {
    var map = new Map(BasemapStyle.ArcGISStreets);
  3. Update the Viewpoint that the MapView shows when the map initializes. This viewpoint will show an area around Los Angeles, California.

    MapViewModel.cs
    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);
  4. 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 stops A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. Learn more and several Graphic objects for displaying route results.

  1. Add additional required using statements to the top of the MapViewModel class.

    MapViewModel.cs
    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;
  2. 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.

    MapViewModel.cs
    27 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 lines
    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 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;
    }
    }
    }
  3. 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. Learn more (origin and destination locations) and the route result polyline A polyline is a type of geometry containing ordered point coordinates and a spatial reference. Learn more that connects them.

    MapViewModel.cs
    32 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 lines
    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 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 overlay A graphics overlay is a client-side, temporary container of graphics to display on a map view or scene view. Learn more is a container for graphics A graphic is a visual element composed of a geometry, symbol, and attributes that is displayed on a map or scene. Learn more that are always displayed on top of all the other layers A layer is a reference to a collection of geographic data that is used to access and display data. The data for layers are typically provided by the basemap layer service and data services. Learn more in the map A map is a collection of layers that are displayed in 2D. It is typically composed of a basemap layer and data layers. Learn more . You will use graphics overlays to display graphics for a Route and its stops A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. Learn more .

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.

  1. In the view model, create a new property named GraphicsOverlays. This will be a collection of GraphicsOverlay that will store point A point is a type of geometry containing a single set of x,y coordinates and a spatial reference. Learn more , line A polyline is a type of geometry containing ordered point coordinates and a spatial reference. Learn more , and polygon A 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. Learn more graphics.

    MapViewModel.cs
    55 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 lines
    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;
    }
    }
    }
  2. Create a property in MapViewModel that exposes a list of driving directions for a Route.

    MapViewModel.cs
    66 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 lines
    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 route graphics

You will define the symbology for each Route result Graphic and add them to a GraphicsOverlay.

  1. Create a new GraphicsOverlay to contain graphics for the Route result and stops A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. Learn more . Create a GraphicsOverlayCollection that contains the overlay and use it to set the MapViewModel.GraphicsOverlays property.

    MapViewModel.cs
    88 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;
    }
    }
    }
  2. Create each result Graphic and define its Symbol.

    MapViewModel.cs
    99 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;
    }
    }
    }
  3. Add the graphics to the GraphicsOverlay.

    MapViewModel.cs
    125 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;
    }
    }
    }
  4. 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.

    MapViewModel.cs
    131 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 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. Learn more to find the best route between two stops A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. Learn more .

  1. Create a new asynchronous function called FindRoute().

    MapViewModel.cs
    137 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
    }
    }
  2. Create route Stop objects using the start and end graphics’ geometry.

    MapViewModel.cs
    146 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
    }
    }
    }
  3. Create a new RouteTask that uses the route 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. Learn more . Create RouteParameters, SetStops and request to ReturnRoutes and ReturnDirections with the result.

    MapViewModel.cs
    149 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
    }
    }
    }
  4. Use the RouteTask to solve the route. If the RouteResult contains a Route, set the route A route is a polyline that defines the best path between two or more points in a street network. Learn more graphic geometry A geometry is a geometric shape, such as a point, polyline, or polygon, that contains one or more coordinates and a spatial reference. Learn more 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.

    MapViewModel.cs
    156 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 A stop is a single point along a route: it can be the origin, an intermediate stop, or destination. Learn more for solving the route.

  1. 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.

    MapViewModel.cs
    165 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 progress
    break;
    }
    }
    3 collapsed lines
    }
    }
  2. In the Visual Studio > Solution Explorer, double-click MainWindow.xaml.cs to open the file.

  3. 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().

    MainWindow.xaml.cs
    41 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.

  1. In the Visual Studio > Solution Explorer, double-click MainWindow.xaml to open the file.

  2. Use data binding to bind the GraphicsOverlays property of the MapViewModel to the MapView control. Handle the GeoViewTapped event with the MyMapView_GeoViewTapped function.

    MainWindow.xaml
    10 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>
  3. 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.

    MainWindow.xaml
    19 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

  1. 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 An origin is a point that defines the start of a route. Learn more and destination A destination is a point that defines the final stop in a route. Learn more point. When both points are defined, the route task uses the route 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. Learn more to find the best route and provide turn-by-turn directions.

Alternatively, you can download the tutorial solution, as follows.

Option 2: Download the solution

  1. Click the Download solution link in the right-hand panel of the page.

  2. Unzip the file to a location on your machine.

  3. Open the .sln file 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 ArcGIS Location Services, also referred to as Location Services, are services hosted by Esri that provide geospatial functionality for developing mapping applications. They include the ArcGIS Basemap Styles service, ArcGIS Static Basemap Tiles service, ArcGIS Places service, ArcGIS Geocoding service, ArcGIS Routing service, ArcGIS GeoEnrichment service, and ArcGIS Elevation service. An ArcGIS Location Platform or ArcGIS Online account is required to use the services. Learn more , use the developer credentials that you created in the Set up authentication step to authenticate requests for resources.

  1. In Visual Studio, in the Solution Explorer, click App.xaml.cs to open the file.

  2. Set the ArcGISEnvironment.ApiKey property with your API key access token.

    App.xaml.cs
    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";
    // Call a function to set up the AuthenticationManager for OAuth.
    UserAuth.ArcGISLoginPrompt.RegisterOAuthConfig();
    }
  3. Remove the code that sets up user authentication.

    App.xaml.cs
    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";
    // 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.

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 An origin is a point that defines the start of a route. Learn more and destination A destination is a point that defines the final stop in a route. Learn more point. When both points are defined, the route task uses the route 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. Learn more to find the best route and provide turn-by-turn directions.

What’s next?

To explore more API features and ArcGIS location services, try the following tutorial: