Skip To Content ArcGIS for Developers Sign In Dashboard

ArcGIS Runtime SDK for .NET

Route around barriers

This code sample is available for these platforms:
View Sample on GitHub

Find a route that reaches all stops without crossing any barriers.

Image of route around barriers

Use case

You can define barriers to avoid unsafe areas, for example flooded roads, when planning the most efficient route to evacuate a hurricane zone. When solving a route, barriers allow you to define portions of the road network that cannot be traversed. You could also use this functionality to plan routes when you know an area will be inaccessible due to a community activity like an organized race or a market night.

In some situations, it is further beneficial to find the most efficient route that reaches all stops, reordering them to reduce travel time. For example, a delivery service may target a number of drop-off addresses, specifically looking to avoid congested areas or closed roads, arranging the stops in the most time-effective order.

How to use the sample

Tap 'Add stop' to add stops to the route. Tap 'Add barrier' to add areas that can't be crossed by the route. Tap 'Route' to find the route and display it. Select 'Allow stops to be re-ordered' to find the best sequence. Select 'Preserve first stop' if there is a known start point, and 'Preserve last stop' if there is a known final destination.

How it works

  1. Create the route task by calling RouteTask.CreateAsync(_serviceUrl) with the URL to a Network Analysis route service.
  2. Get the default route parameters for the service by calling _routeTask.CreateDefaultParametersAsync.
  3. When the user adds a stop, add it to the route parameters.
    1. Normalize the geometry; otherwise the route job would fail if the user included any stops over the 180th degree meridian.
    2. Get the name of the stop by counting the existing stops - _stepsOverlay.Graphics.Count + 1.
    3. Create a composite symbol for the stop. This sample uses a pushpin marker and a text symbol.
    4. Create the graphic from the geometry and the symbol.
    5. Add the graphic to the stops graphics overlay.
  4. When the user adds a barrier, create a polygon barrier and add it to the route parameters.
    1. Normalize the geometry (see 3i above).
    2. Buffer the geometry to create a larger barrier from the tapped point by calling GeometryEngine.BufferGeodetic(mapLocation, 500, LinearUnits.Meters).
    3. Create the graphic from the geometry and the symbol.
    4. Add the graphic to the barriers overlay.
  5. When ready to find the route, configure the route parameters.
    1. Set the ReturnStops and ReturnDirections to true.
    2. Create a Stop for each graphic in the stops graphics overlay. Add that stop to a list, then call _routeParameters.SetStops(routeStops).
    3. Create a PolygonBarrier for each graphic in the barriers graphics overlay. Add that barrier to a list, then call _routeParameters.SetPolygonBarriers(routeBarriers).
    4. If the user will accept routes with the stops in any order, set FindBestSequence to true to find the most optimal route.
    5. If the user has a definite start point, set PreserveFirstStop to true.
    6. If the user has a definite final destination, set PreserveLastStop to true.
  6. Calculate and display the route.
    1. Call _routeTask.SolveRouteAsync(_routeParameters) to get a RouteResult.
    2. Get the first returned route by calling calculatedRoute.Routes.First().
    3. Get the geometry from the route as a polyline by accessing the firstResult.RouteGeometry property.
    4. Create a graphic from the polyline and a simple line symbol.
    5. Display the steps on the route, available from firstResult.DirectionManeuvers.

Relevant API

  • DirectionManeuver
  • PolygonBarrier
  • Route
  • Route.DirectionManeuver
  • Route.RouteGeometry
  • RouteParameters.ClearPolygonBarriers
  • RouteParameters.FindBestSequence
  • RouteParameters.PreserveFirstStop
  • RouteParameters.PreserveLastStop
  • RouteParameters.ReturnDirections
  • RouteParameters.ReturnStops
  • RouteParameters.SetPolygonBarriers
  • RouteResult
  • RouteResult.Routes
  • RouteTask
  • Stop
  • Stop.Name

About the data

This sample uses an Esri-hosted sample street network for San Diego.


barriers, best sequence, directions, maneuver, network analysis, routing, sequence, stop order, stops

Sample Code

<ContentPage xmlns=""
        <esriUI:MapView x:Name="MyMapView" Style="{StaticResource MapWithFormStyle}"
                        BindingContext="{x:Reference Name=ResponsiveFormContainer}"
        <resources:ResponsiveFormContainer x:Name="ResponsiveFormContainer">
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                <Label x:Name="StatusLabel"
                           Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3"
                <Button x:Name="AddStopButton"
                        Text="Add stop"
                        Grid.Row="1" Grid.Column="0"
                        Clicked="AddStop_Clicked" />
                <Button x:Name="AddBarrierButton"
                        Text="Add barrier"
                        Grid.Row="1" Grid.Column="1"
                        Clicked="AddBarrier_Clicked" />
                <Button x:Name="ResetRoutingButton"
                        Grid.Row="1" Grid.Column="2"
                        Clicked="ResetRoute_Clicked" />
                <StackLayout Orientation="Horizontal"
                             Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3">
                    <Switch x:Name="AllowReorderStopsCheckbox"
                    <Label Text="Allow stops to be re-ordered" 
                           VerticalOptions="Center" VerticalTextAlignment="Center" />
                <StackLayout Orientation="Horizontal"
                             Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3">
                    <Switch x:Name="PreserveFirstStopCheckbox"
                            VerticalOptions="Center" />
                    <Label Text="Preserve first stop"
                           VerticalOptions="Center" VerticalTextAlignment="Center" />
                <StackLayout Orientation="Horizontal"
                             Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="3">
                    <Switch x:Name="PreserveLastStopCheckbox"
                            VerticalOptions="Center" />
                    <Label Text="Preserve last stop"
                           VerticalOptions="Center" VerticalTextAlignment="Center" />
                <Button x:Name="CalculateRouteButton"
                        Grid.Row="5" Grid.Column="0"
                        Clicked="RouteButton_Clicked" />
                <Button x:Name="ShowDirectionsButton"
                        Text="Show directions"
                        Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="2"
                <Grid x:Name="BusyOverlay"
                      Grid.Row="0" Grid.RowSpan="6" Grid.Column="0" Grid.ColumnSpan="3"
                      HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"
                    <Label Text="Calculating route"
                               TextColor="White" />
// Copyright 2019 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:
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific 
// language governing permissions and limitations under the License.

using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalysis;
using Esri.ArcGISRuntime.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xamarin.Forms;
using Color = System.Drawing.Color;

namespace ArcGISRuntimeXamarin.Samples.RouteAroundBarriers
        name: "Route around barriers",
        category: "Network analysis",
        description: "Find a route that reaches all stops without crossing any barriers.",
        instructions: "Tap 'Add stop' to add stops to the route. Tap 'Add barrier' to add areas that can't be crossed by the route. Tap 'Route' to find the route and display it. Select 'Allow stops to be re-ordered' to find the best sequence. Select 'Preserve first stop' if there is a known start point, and 'Preserve last stop' if there is a known final destination.",
        tags: new[] { "barriers", "best sequence", "directions", "maneuver", "network analysis", "routing", "sequence", "stop order", "stops" })]
    public partial class RouteAroundBarriers : ContentPage
        // Track the current state of the sample.
        private SampleState _currentSampleState;

        // Graphics overlays to maintain the stops, barriers, and route result.
        private GraphicsOverlay _routeOverlay;
        private GraphicsOverlay _stopsOverlay;
        private GraphicsOverlay _barriersOverlay;

        // The route task manages routing work.
        private RouteTask _routeTask;

        // The route parameters defines how the route will be calculated.
        private RouteParameters _routeParameters;

        // Symbols for displaying the barriers and the route line.
        private Symbol _routeSymbol;
        private Symbol _barrierSymbol;

        // URL to the network analysis service.
        private const string RouteServiceUrl = "";

        private ContentPage _directionsPage;

        public RouteAroundBarriers()

        private async void Initialize()
                // Update interface state.

                // Create the map with a basemap.
                Map sampleMap = new Map(Basemap.CreateTopographic());
                sampleMap.InitialViewpoint = new Viewpoint(32.7157, -117.1611, 1e5);
                MyMapView.Map = sampleMap;

                // Create the graphics overlays. These will manage rendering of route, direction, stop, and barrier graphics.
                _routeOverlay = new GraphicsOverlay();
                _stopsOverlay = new GraphicsOverlay();
                _barriersOverlay = new GraphicsOverlay();

                // Add graphics overlays to the map view.

                // Create and initialize the route task.
                _routeTask = await RouteTask.CreateAsync(new Uri(RouteServiceUrl));

                // Get the route parameters from the route task.
                _routeParameters = await _routeTask.CreateDefaultParametersAsync();

                // Prepare symbols.
                _routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Blue, 2);
                _barrierSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Cross, Color.Red, null);

                // Enable the UI.
            catch (Exception e)
                ShowMessage("Couldn't load sample", "Couldn't start the sample. See the debug output for detail.");

        private async void HandleMapTap(MapPoint mapLocation)
            // Normalize geometry - important for geometries that will be sent to a server for processing.
            mapLocation = (MapPoint)GeometryEngine.NormalizeCentralMeridian(mapLocation);

            switch (_currentSampleState)
                case SampleState.AddingBarriers:
                    // Buffer the tapped point to create a larger barrier.
                    Geometry bufferedGeometry = GeometryEngine.BufferGeodetic(mapLocation, 500, LinearUnits.Meters);

                    // Create the graphic to show the barrier.
                    Graphic barrierGraphic = new Graphic(bufferedGeometry, _barrierSymbol);

                    // Add the graphic to the overlay - this will cause it to appear on the map.
                case SampleState.AddingStops:
                    // Get the name of this stop.
                    string stopName = $"{_stopsOverlay.Graphics.Count + 1}";

                    // Create the marker to show underneath the stop number.
                    PictureMarkerSymbol pushpinMarker = await GetPictureMarker();

                    // Create the text symbol for showing the stop.
                    TextSymbol stopSymbol = new TextSymbol(stopName, System.Drawing.Color.White, 15,
                        HorizontalAlignment.Center, VerticalAlignment.Middle);
                    stopSymbol.OffsetY = 15;

                    CompositeSymbol combinedSymbol = new CompositeSymbol(new MarkerSymbol[] { pushpinMarker, stopSymbol });

                    // Create the graphic to show the stop.
                    Graphic stopGraphic = new Graphic(mapLocation, combinedSymbol);

                    // Add the graphic to the overlay - this will cause it to appear on the map.

        private void ConfigureThenRoute()
            // Guard against error conditions.
            if (_routeParameters == null)
                ShowMessage("Not ready yet", "Sample isn't ready yet; define route parameters first.");

            if (_stopsOverlay.Graphics.Count < 2)
                ShowMessage("Not enough stops", "Add at least two stops before solving a route.");

            // Clear any existing route from the map.

            // Configure the route result to include directions and stops.
            _routeParameters.ReturnStops = true;
            _routeParameters.ReturnDirections = true;

            // Create a list to hold stops that should be on the route.
            List<Stop> routeStops = new List<Stop>();

            // Create stops from the graphics.
            foreach (Graphic stopGraphic in _stopsOverlay.Graphics)
                // Note: this assumes that only points were added to the stops overlay.
                MapPoint stopPoint = (MapPoint)stopGraphic.Geometry;

                // Create the stop from the graphic's geometry.
                Stop routeStop = new Stop(stopPoint);

                // Set the name of the stop to its position in the list.
                routeStop.Name = $"{_stopsOverlay.Graphics.IndexOf(stopGraphic) + 1}";

                // Add the stop to the list of stops.

            // Configure the route parameters with the stops.

            // Create a list to hold barriers that should be routed around.
            List<PolygonBarrier> routeBarriers = new List<PolygonBarrier>();

            // Create barriers from the graphics.
            foreach (Graphic barrierGraphic in _barriersOverlay.Graphics)
                // Get the polygon from the graphic.
                Polygon barrierPolygon = (Polygon)barrierGraphic.Geometry;

                // Create a barrier from the polygon.
                PolygonBarrier routeBarrier = new PolygonBarrier(barrierPolygon);

                // Add the barrier to the list of barriers.

            // Configure the route parameters with the barriers.

            // If the user allows stops to be re-ordered, the service will find the optimal order.
            _routeParameters.FindBestSequence = AllowReorderStopsCheckbox.IsToggled;

            // If the user has allowed re-ordering, but has a definite start point, tell the service to preserve the first stop.
            _routeParameters.PreserveFirstStop = PreserveFirstStopCheckbox.IsToggled;

            // If the user has allowed re-ordering, but has a definite end point, tell the service to preserve the last stop.
            _routeParameters.PreserveLastStop = PreserveLastStopCheckbox.IsToggled;

            // Calculate and show the route.

        private async void CalculateAndShowRoute()
                // Calculate the route.
                RouteResult calculatedRoute = await _routeTask.SolveRouteAsync(_routeParameters);

                // Get the first returned result.
                Route firstResult = calculatedRoute.Routes.First();

                // Get the route geometry - this is the line that shows the route.
                Polyline calculatedRouteGeometry = firstResult.RouteGeometry;

                // Create the route graphic from the geometry and the symbol.
                Graphic routeGraphic = new Graphic(calculatedRouteGeometry, _routeSymbol);

                // Clear any existing routes, then add this one to the map.

                // Add the directions to the textbox.
            catch (Exception e)
                ShowMessage("Routing error", $"Couldn't calculate route. See debug output for details. Message: {e.Message}");

        private void PrepareDirectionsList(IReadOnlyList<DirectionManeuver> directions)
            // Create the Xamarin.Forms page for showing the directions.
            _directionsPage = new ContentPage();

            // Create the list view for showing directions.
            ListView directionsList = new ListView();

            // Populate the list view with directions text.
            directionsList.ItemsSource = directions.Select(directionObject => directionObject.DirectionText);

            // Add the list view to the page.
            _directionsPage.Content = directionsList;

        private void MyMapView_OnGeoViewTapped(object sender, Esri.ArcGISRuntime.Xamarin.Forms.GeoViewInputEventArgs e) => HandleMapTap(e.Location);

        private void AddStop_Clicked(object sender, EventArgs e) => UpdateInterfaceState(SampleState.AddingStops);

        private void AddBarrier_Clicked(object sender, EventArgs e) => UpdateInterfaceState(SampleState.AddingBarriers);

        private void ResetRoute_Clicked(object sender, EventArgs e)
            _directionsPage = null;

        private void RouteButton_Clicked(object sender, EventArgs e)
        private void ShowDirections_Clicked(object sender, EventArgs e)
            if (_directionsPage != null)
                ShowMessage("Route not ready", "Add stops and barriers, then select 'Route' to calculate the route before accessing directions.");

        private async Task<PictureMarkerSymbol> GetPictureMarker()
            // Get current assembly that contains the image
            Assembly currentAssembly = Assembly.GetExecutingAssembly();

            // Get image as a stream from the resources
            // Picture is defined as EmbeddedResource and DoNotCopy
            Stream resourceStream = currentAssembly.GetManifestResourceStream(

            // Create new symbol using asynchronous factory method from stream
            PictureMarkerSymbol pinSymbol = await PictureMarkerSymbol.CreateAsync(resourceStream);
            pinSymbol.Width = 50;
            pinSymbol.Height = 50;
            pinSymbol.LeaderOffsetX = 30;
            pinSymbol.OffsetY = 14;

            return pinSymbol;

        private void UpdateInterfaceState(SampleState newState)
            // Manage the UI state for the sample.
            _currentSampleState = newState;
            switch (_currentSampleState)
                case SampleState.NotReady:
                    AddStopButton.IsEnabled = false;
                    AddBarrierButton.IsEnabled = false;
                    ResetRoutingButton.IsEnabled = false;
                    AllowReorderStopsCheckbox.IsEnabled = false;
                    PreserveFirstStopCheckbox.IsEnabled = false;
                    PreserveLastStopCheckbox.IsEnabled = false;
                    ShowDirectionsButton.IsEnabled = false;
                    CalculateRouteButton.IsEnabled = false;
                    StatusLabel.Text = "Preparing sample...";
                case SampleState.AddingBarriers:
                    StatusLabel.Text = "Tap the map to add a barrier.";
                case SampleState.AddingStops:
                    StatusLabel.Text = "Tap the map to add a stop.";
                case SampleState.Ready:
                    AddStopButton.IsEnabled = true;
                    AddBarrierButton.IsEnabled = true;
                    ResetRoutingButton.IsEnabled = true;
                    AllowReorderStopsCheckbox.IsEnabled = true;
                    PreserveLastStopCheckbox.IsEnabled = true;
                    PreserveFirstStopCheckbox.IsEnabled = true;
                    ShowDirectionsButton.IsEnabled = true;
                    CalculateRouteButton.IsEnabled = true;
                    StatusLabel.Text = "Click 'Add stop' or 'Add barrier', then tap on the map to add stops and barriers.";
                    BusyOverlay.IsVisible = false;
                case SampleState.Routing:
                    BusyOverlay.IsVisible = true;

        // Enum represents various UI states.
        private enum SampleState

        private async void ShowMessage(string title, string detail)
            await Application.Current.MainPage.DisplayAlert(title, detail, "OK");