Find a route and directions

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

find a route and directions

Routing is the process of finding the path from an origin to a destination in a street network. You can use the Routing service to find routes, get driving directions, calculate drive times, and solve complicated, multiple vehicle routing problems. To create a route, you typically define a set of stops (origin and one or more destinations) and use the service to find a route with directions. You can also use a number of additional parameters such as barriers and mode of travel to refine the results.

In this tutorial, you define an origin and destination by clicking on the map. These values are used to get a route and directions from the route service. The directions are also displayed on the map.

Prerequisites

Before starting this tutorial, you should:

  • Have an ArcGIS account and an API key to access ArcGIS services. If you don't have an account, sign up for free.
  • Ensure your development environment meets the system requirements.

Optionally, you may want to install the ArcGIS Runtime SDK for .NET to get access to project templates in Visual Studio (Windows only) and offline copies of the NuGet packages.

Steps

Open a Visual Studio solution

  1. To start the tutorial, complete the Display a map tutorial or download and unzip the solution.

  2. Open the .sln file in Visual Studio.

  3. If you downloaded the solution project, set your API key.

    An API Key enables access to services, web maps, and web scenes hosted in ArcGIS Online.

    If necessary, set the API Key.
    1. Go to your developer dashboard to get your API key. For these tutorials, use your default API key. It is scoped to include all of the services demonstrated in the tutorials.

    2. In Visual Studio, in the Solution Explorer, click App.xaml.cs.

    3. In the App class, add an override for the OnStartup() function to set the ApiKey property on ArcGISRuntimeEnvironment.

      App.xaml.cs
                                              
      Add line.Add line.Add line.Add line.Add line.Add line.Add line.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      //   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.Configuration;
      using System.Data;
      using System.Linq;
      using System.Threading.Tasks;
      using System.Windows;
      
      namespace DisplayAMap
      {
          /// <summary>
          /// Interaction logic for App.xaml
          /// </summary>
      
          public partial class App : Application
          {
      
              protected override void OnStartup(StartupEventArgs e)
              {
                  base.OnStartup(e);
                  // Note: it is not best practice to store API keys in source code.
                  // The API key is referenced here for the convenience of this tutorial.
                  Esri.ArcGISRuntime.ArcGISRuntimeEnvironment.ApiKey = "YOUR_API_KEY";
              }
      
          }
      }
      

If developing with Visual Studio for Windows, ArcGIS Runtime for .NET provides a set of project templates for each of the supported .NET platforms. These templates provide all of the code needed for a basic Model-View-ViewModel (MVVM) app. You need to install the ArcGIS Runtime for .NET Visual Studio Extension to add the templates to Visual Studio (Windows only). See Install and set up for details.

Update the tutorial name used in the project (optional)

The Visual Studio solution, project, and the namespace for all classes currently use the name DisplayAMap. Follow the steps below if you prefer the name to reflect the current tutorial. These steps are not required, your code will still work if you keep the original name.

The tutorial instructions and code use the name FindARouteAndDirections for the solution, project, and namespace. You can choose any name you like, but it should be the same for each of these.

  1. 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.
  2. Rename the namespace used by classes in the project.

    • In the Solution Explorer, expand the project node.
    • Double-click MapViewModel.cs in the Solution Explorer to open the file.
    • In the MapViewModel class, double-click the namespace name (DisplayAMap) to select it, and then right-click and choose Rename....
    • Provide the new name for the namespace.
    • Click Apply in the Rename: DisplayAMap window that appears in the upper-right of the code window. This will rename the namespace throughout your project.
  3. Build the project.

    • Choose Build > Build solution (or press <F6>).

Update the basemap and initial extent

For displaying routes and driving directions, a streets basemap usually works best. You will update the Map to use the ArcGISStreets basemap and center the display on Los Angeles, California.

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

    A view defined with XAML, such as MainWindow, is composed of two files in a Visual Studio project. The visual elements (such as map views, buttons, text boxes, and so on) are defined with XAML markup in a .xaml file. This file is often referred to as the "page". The code for the XAML elements is stored in an associated .xaml.cs file that is known as the "code-behind", since it stores the code behind the controls. Keeping with the MVVM design pattern, user interface events (such as the code that responds to a button click) are handled in the code-behind for the view.

  2. Update the Viewpoint that the MapView initially shows when the app initializes. This viewpoint will show an area around Los Angeles, California.

    MainWindow.xaml.cs
                                                                      
    Change lineChange line
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    // 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();
    
                MapPoint mapCenterPoint = new MapPoint(-118.24532, 34.05398, SpatialReferences.Wgs84);
                MainMapView.SetViewpoint(new Viewpoint(mapCenterPoint, 144_447.638572));
    
            }
    
            public async void MainMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
            {
                try
                {
                    MapViewModel viewmodel = Resources["MapViewModel"] as MapViewModel;
    
                    await viewmodel.HandleTap(e.Location);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error", ex.Message);
                }
            }
    
        }
    }
    
  3. In the Visual Studio > Solution Explorer, double-click MapViewModel.cs to open the file.

    The project uses the Model-View-ViewModel (MVVM) design pattern to separate the application logic (view model) from the user interface (view). MapViewModel.cs contains the view model class for the application, called MapViewModel. See the Microsoft documentation for more information about the Model-View-ViewModel pattern.

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

    MapViewModel.cs
                                                                                                                                                                                               
    Change line
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    
  5. Click Debug > Start Debugging (or press <F5> on the keyboard) to run the app.

You should see a streets map centered on an area of Los Angeles.

Define member variables

You will need member variables in the MapViewModel class to store the status of user-defined route stops and several Graphic objects for displaying route results.

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

    Classes in the Esri.ArcGISRuntime.Tasks.NetworkAnalysis namespace provide network analysis functionality, such as solving routes, finding closest facilities, or defining service areas on a street network. Esri.ArcGISRuntime.UI contains the Graphic and GraphicsOverlay classes. Esri.ArcGISRuntime.Symbology contains the classes that define the symbols and renderers used to display features and graphics.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    
  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.

    The user will click the map to define the origin and destination locations for the route. If neither stop has been defined, a map click will be used for the origin ("from") location. If an origin is defined, the click will be used to define the destination ("to") location. If both are defined, you may choose to start over and use the click to define a new origin location. This enum has values that represent the context of these clicks so the code can respond appropriately.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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. Create additional member variables for the route result graphics. These graphics will show the stops (origin and destination locations) and the route result polyline that connects them.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    

Add properties for graphics overlays and driving directions

A graphics overlay is a container for graphics that are always displayed on top of all the other layers in the map. You will use graphics overlays to display graphics for a Route and its stops.

A Route provides turn-by-turn directions with its DirectionManeuvers property. You will expose the directions with a property in MapViewModel so they can be bound to a control in the app's UI.

  1. In the view model, create a new property named GraphicsOverlays. This will be a collection of GraphicsOverlay that will store point, line, and polygon graphics.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    
  2. Create a property in MapViewModel that exposes a list of driving directions for a Route.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    

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. Create a GraphicsOverlayCollection that contains the overlay and use it to set the MapViewModel.GraphicsOverlays property.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    
  2. Create each result Graphic and define its Symbol.

    The Geometry for each graphic is initially null and will not display until a valid geometry is assigned (for example, when the user clicks to define a stop location).

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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. Add the graphics to the GraphicsOverlay.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    
  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
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    // 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;
            private Graphic _endGraphic;
            private Graphic _routeGraphic;
    
            public MapViewModel()
            {
                SetupMap();
            }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            {
                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()
            {
    
                Map = new Map(BasemapStyle.ArcGISStreets);
    
                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 });
    
            }
    
            private void ResetState()
            {
                _startGraphic.Geometry = null;
                _endGraphic.Geometry = null;
                _routeGraphic.Geometry = null;
                Directions = null;
                _currentState = RouteBuilderStatus.NotStarted;
            }
    
            public async Task FindRoute()
            {
    
                var stops = new [] { _startGraphic, _endGraphic }.Select(graphic => new Stop(graphic.Geometry as MapPoint));
    
                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;
                }
            }
    
        }
    }
    

Find a route between two stops

You will create a function that uses the route service to find the best route between two stops.

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

    When calling methods asynchronously inside a function (using the await keyword), the async keyword is required in the signature.

    Asynchronous functions that don't return a value should have a return type of Task. Although a void return type would continue to work, this is not considered best practice. Exceptions thrown by an async void method cannot be caught outside of that method, are difficult to test, and can cause serious side effects if the caller is not expecting them to be asynchronous. The only circumstance where async void is acceptable is when using an event handler, such as a button click.

    See the Microsoft documentation for more information about Asynchronous programming with async and await.

    MapViewModel.cs
                                                                                                                                                                                               
    Add line.Add line.Add line.Add line.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65