Routing Around Barriers

Download Samples Repository

Description

Shows routing and re-routing between stops and around user defined barriers using the OnlineLocatorTask.

"Desktop" "Store" "Phone" Available for Desktop, Store, Phone

Sample Code

<UserControl x:Class="ArcGISRuntime.Samples.Desktop.RoutingWithBarriers"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:esri="http://schemas.esri.com/arcgis/runtime/2013">
    <Grid>
        <Grid.Resources>
            <esri:SimpleLineSymbol x:Key="RouteSymbol" Color="#990000FF" Style="Solid" Width="3" />
            <esri:SimpleRenderer x:Key="RouteRenderer" Symbol="{StaticResource RouteSymbol}" />

            <esri:SimpleMarkerSymbol x:Key="BarrierSymbol" Color="Black" Style="X" Size="20" />
            <esri:SimpleRenderer x:Key="BarrierRenderer" Symbol="{StaticResource BarrierSymbol}" />
        </Grid.Resources>

        <esri:MapView x:Name="MyMapView" MapViewTapped="MyMapView_MapViewTapped">
			<esri:Map InitialViewpoint="-117.24377026205757,32.61710761167467,-116.95879261773452,32.841266856294624,4326">
				<esri:ArcGISTiledMapServiceLayer
                    ServiceUri="http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer" />
			</esri:Map>
			<esri:MapView.GraphicsOverlays>
				<esri:GraphicsOverlay ID="RouteGraphicsOverlay" Renderer="{StaticResource RouteRenderer}" />
				<esri:GraphicsOverlay ID="StopGraphicsOverlay"  />
				<esri:GraphicsOverlay ID="BarrierGraphicsOverlay" Renderer="{StaticResource BarrierRenderer}"/>
			</esri:MapView.GraphicsOverlays>
		</esri:MapView>

		<Border Background="White" BorderBrush="Black" BorderThickness="1"
				HorizontalAlignment="Right" VerticalAlignment="Top"
				Margin="30" Padding="20" Width="250">
			<Border.Effect>
				<DropShadowEffect/>
			</Border.Effect>
			<StackPanel>
                <TextBlock Text="Tap stop and barrier points on the map to see the calculated route." 
                           TextWrapping="Wrap" />

                <StackPanel Orientation="Horizontal" Margin="0,12,0,0" HorizontalAlignment="Center">
                    <RadioButton x:Name="rbStops" Content="Add Stops" Margin="0,0,20,0" IsChecked="True" />
                    <RadioButton x:Name="rbBarriers" Content="Add Barriers" />
                </StackPanel>

                <Button Content="Clear" Click="ClearButton_Click" HorizontalAlignment="Center" Padding="20,4" Margin="0,12,0,0"/>

                <ProgressBar x:Name="progress" IsIndeterminate="True" Visibility="Collapsed" Margin="0,12,0,0" />
            </StackPanel>
        </Border>
    </Grid>
</UserControl>
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.NetworkAnalyst;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace ArcGISRuntime.Samples.Desktop
{
    /// <summary>
    /// Shows routing and re-routing between stops and around user defined barriers using the OnlineLocatorTask.
    /// </summary>
    /// <title>Routing Around Barriers</title>
    /// <category>Tasks</category>
    /// <subcategory>Network Analyst</subcategory>
    public partial class RoutingWithBarriers : UserControl
    {
		private const string OnlineRoutingService = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route";

        private GraphicsOverlay _routeGraphicsOverlay;
		private GraphicsOverlay _stopGraphicsOverlay;
		private GraphicsOverlay _barrierGraphicsOverlay;

        private OnlineRouteTask _routeTask;
        private RouteParameters _routeParams;

        public RoutingWithBarriers()
        {
            InitializeComponent();

			_routeGraphicsOverlay = MyMapView.GraphicsOverlays["RouteGraphicsOverlay"];
			_stopGraphicsOverlay = MyMapView.GraphicsOverlays["StopGraphicsOverlay"];
			_barrierGraphicsOverlay = MyMapView.GraphicsOverlays["BarrierGraphicsOverlay"];

            SetupRouteTask();
        }

        private async void SetupRouteTask()
        {
			try
			{
				_routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));
				_routeParams = await _routeTask.GetDefaultParametersAsync();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}	
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            _routeGraphicsOverlay.Graphics.Clear();
            _stopGraphicsOverlay.Graphics.Clear();
            _barrierGraphicsOverlay.Graphics.Clear();
        }

        private async void MyMapView_MapViewTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e)
        {
            try
            {
                if (rbStops.IsChecked == true)
                {
                    var graphicIdx = _stopGraphicsOverlay.Graphics.Count + 1;
                    _stopGraphicsOverlay.Graphics.Add(CreateStopGraphic(e.Location, graphicIdx));
                }
                else
                {
                    _barrierGraphicsOverlay.Graphics.Add(new Graphic(e.Location));
                }

                await SolveRoute();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        public async Task SolveRoute()
        {
            if (_stopGraphicsOverlay.Graphics.Count < 2)
                return;

            try
            {
                progress.Visibility = Visibility.Visible;

                _routeParams.SetStops(_stopGraphicsOverlay.Graphics);
                _routeParams.SetPointBarriers(_barrierGraphicsOverlay.Graphics);
                _routeParams.OutSpatialReference = MyMapView.SpatialReference;

                RouteResult routeResult = await _routeTask.SolveAsync(_routeParams);

                if (routeResult.Routes.Count > 0)
                {
                    _routeGraphicsOverlay.Graphics.Clear();

                    var route = routeResult.Routes.First().RouteFeature;
                    _routeGraphicsOverlay.Graphics.Add(new Graphic(route.Geometry));
                }
            }
            catch (AggregateException ex)
            {
                var innermostExceptions = ex.Flatten().InnerExceptions;
                if (innermostExceptions != null && innermostExceptions.Count > 0)
                    MessageBox.Show(innermostExceptions[0].Message);
                else
                    MessageBox.Show(ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
            finally
            {
                progress.Visibility = Visibility.Collapsed;
            }
        }

        private Graphic CreateStopGraphic(MapPoint location, int id)
        {
            var symbol = new CompositeSymbol();
            symbol.Symbols.Add(new SimpleMarkerSymbol() { Style = SimpleMarkerStyle.Circle, Color = Colors.Blue, Size = 16 });
            symbol.Symbols.Add(new TextSymbol()
            {
                Text = id.ToString(),
                Color = Colors.White,
                VerticalTextAlignment = VerticalTextAlignment.Middle,
                HorizontalTextAlignment = HorizontalTextAlignment.Center,
                YOffset = -1
            });

            var graphic = new Graphic()
            {
                Geometry = location,
                Symbol = symbol
            };

            return graphic;
        }
    }
}
Feedback on this topic?