public async Task<RouteResult> GetRoute(IEnumerable<MapPoint> stops, CancellationToken cancellationToken)
		{
			if (stops == null)
				throw new ArgumentNullException("stops");

			List<Graphic> stopList = new List<Graphic>();
			foreach (var stop in stops)
			{
				stopList.Add(new Graphic(stop));
			}
			if (stopList.Count < 2)
				throw new ArgumentException("Not enough stops");

			//determine which route service to use. Long distance routes should use the long-route service
			Polyline line = new Polyline() { SpatialReference = SpatialReferences.Wgs84 };
			line.Paths.AddPart(stops.Select(m => m.Coordinate));
			var length = GeometryEngine.GeodesicLength(line);
			string svc = routeService;
			if (length > 200000)
				svc = longRouteService;

			//Calculate route
			RouteTask task = new OnlineRouteTask(new Uri(svc)) { HttpMessageHandler = messageHandler };
			var parameters = await task.GetDefaultParametersAsync().ConfigureAwait(false);
			parameters.Stops = new Esri.ArcGISRuntime.Tasks.NetworkAnalyst.FeaturesAsFeature(stopList);
			parameters.ReturnStops = true;
			parameters.OutputLines = OutputLine.TrueShapeWithMeasure;
			parameters.OutSpatialReference = SpatialReferences.Wgs84;
			parameters.DirectionsLengthUnit = LinearUnits.Meters;
			parameters.UseTimeWindows = false;
			parameters.RestrictionAttributeNames = new List<string>(new string[] { "OneWay " });
			return await task.SolveAsync(parameters, cancellationToken);
		}
        public DrivingDirections()
        {
            this.InitializeComponent();
            _directionPointSymbol = LayoutRoot.Resources["directionPointSymbol"] as Symbol;
            _stopsOverlay = MyMapView.GraphicsOverlays["StopsOverlay"];
            _routesOverlay = MyMapView.GraphicsOverlays["RoutesOverlay"];
            _directionsOverlay = MyMapView.GraphicsOverlays["DirectionsOverlay"];

            _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));
        }
		private async void SetupRouteTask()
		{
			try
			{
				_routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));
				_routeParams = await _routeTask.GetDefaultParametersAsync();
			}
			catch (Exception ex)
			{
				var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
			}
		}
        private async void SetupRouteTask()
        {
			try
			{
				_routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));
				_routeParams = await _routeTask.GetDefaultParametersAsync();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}	
        }
        private async void mapView1_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e)
        {
            var mp = e.Location;
            Graphic stop = new Graphic() { Geometry = mp };
            var stopsGraphicsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
            stopsGraphicsLayer.Graphics.Add(stop);

            if (stopsGraphicsLayer.Graphics.Count > 1)
            {
                try
                {
                    var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"));
                    var routeParams = await routeTask.GetDefaultParametersAsync();

                    FeaturesAsFeature stopsFeatures = new FeaturesAsFeature();
                    stopsFeatures.Features = stopsGraphicsLayer.Graphics;
                    routeParams.Stops = stopsFeatures;
                    routeParams.UseTimeWindows = false;
                    routeParams.OutSpatialReference = mapView1.SpatialReference;
                    routeParams.DirectionsLengthUnit = LinearUnits.Miles;
                    var result = await routeTask.SolveAsync(routeParams);
                    if (result != null)
                    {
                        if (result.Routes != null && result.Routes.Count > 0)
                        {
                            var firstRoute = result.Routes.FirstOrDefault();
                            var direction = firstRoute.RouteDirections.FirstOrDefault();

                            if (direction != null)
                            {
                                int totalMins = 0;
                                foreach (RouteDirection dir in firstRoute.RouteDirections)
                                    totalMins = totalMins + dir.Time.Minutes;

                                await new MessageDialog(string.Format("{0:N2} minutes", totalMins)).ShowAsync();

                            }

                            var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
                            routeLayer.Graphics.Add(firstRoute.RouteGraphic);
                        }
                    }

                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
        public RoutingClosestFacility()
        {
            this.InitializeComponent();
            _facilitiesGraphicsLayer = mapView1.Map.Layers["MyFacilitiesGraphicsLayer"] as GraphicsLayer;
            _stopsGraphicsLayer = mapView1.Map.Layers["MyIncidentsGraphicsLayer"] as GraphicsLayer;
            _routeGraphicsLayer = mapView1.Map.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;
            _barrierGraphicsLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;

            _stops = new List<Graphic>();
            _polylineBarriers = new List<Graphic>();
            _polygonBarriers = new List<Graphic>();
            random = new Random();
            _onlineRouteTask= new OnlineRouteTask(new Uri(NETWORKSERVICE));
        }
		private async void MyMapView_Tapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e)
		{
			_routeGraphicsOverlay = MyMapView.GraphicsOverlays["RouteGraphicsOverlay"];
			_stopsGraphicsOverlay = MyMapView.GraphicsOverlays["StopsGraphicsOverlay"];

			var graphicIdx = _stopsGraphicsOverlay.Graphics.Count + 1;
			_stopsGraphicsOverlay.Graphics.Add(CreateStopGraphic(e.Location, graphicIdx));

			if (_stopsGraphicsOverlay.Graphics.Count > 1)
			{
				try
				{
					progress.Visibility = Visibility.Visible;

					var routeTask = new OnlineRouteTask(
						new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route"));
					var routeParams = await routeTask.GetDefaultParametersAsync();

					routeParams.SetStops(_stopsGraphicsOverlay.Graphics);
					routeParams.UseTimeWindows = false;
					routeParams.OutSpatialReference = MyMapView.SpatialReference;
					routeParams.DirectionsLanguage = new CultureInfo("en-Us"); // CultureInfo.CurrentCulture;

					var result = await routeTask.SolveAsync(routeParams);
					if (result.Routes.Count > 0)
					{
						_routeGraphicsOverlay.Graphics.Clear();

						var route = result.Routes.First().RouteFeature;
						_routeGraphicsOverlay.Graphics.Add(new Graphic(route.Geometry));

						var meters = GeometryEngine.GeodesicLength(route.Geometry, GeodeticCurveType.Geodesic);
						txtDistance.Text = string.Format("{0:0.00} miles", LinearUnits.Miles.ConvertFromMeters(meters));

						panelRouteInfo.Visibility = Visibility.Visible;
					}
				}
				catch (Exception ex)
				{
					var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
				}
				finally
				{
					progress.Visibility = Visibility.Collapsed;
				}
			}
		}
        private async void OnSolveRouteClicked(object sender, RoutedEventArgs e)
        {

            var stopsLayer = mapView1.Map.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
            var barriersLayer = mapView1.Map.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;

            if (stopsLayer.Graphics.Count > 1)
            {
                try
                {
                    OnlineRouteTask routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"));
                    RouteParameters routeParams = await routeTask.GetDefaultParametersAsync();
                    FeaturesAsFeature featureAsFeature = new FeaturesAsFeature();
                    featureAsFeature.Features = stopsLayer.Graphics;
                    routeParams.Stops = featureAsFeature;

                    routeParams.UseTimeWindows = false;
                    routeParams.OutSpatialReference = mapView1.SpatialReference;
                    FeaturesAsFeature barrierFeatures = new FeaturesAsFeature();
                    barrierFeatures.Features = barriersLayer.Graphics;
                    routeParams.PointBarriers = barrierFeatures;
                    routeParams.OutputGeometryPrecision = 1;
                    //routeParams.OutputGeometryPrecisionUnit = LinearUnits.Miles;
                    routeParams.DirectionsLengthUnit = LinearUnits.Miles;
                    var result = await routeTask.SolveAsync(routeParams);

                    if (result != null)
                    {
                        GraphicsLayer routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
                        routeLayer.Graphics.Clear();


                        foreach (var route in result.Routes)
                            routeLayer.Graphics.Add(route.RouteGraphic);

                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }
            }
        }
        public NetworkingToolController(MapView mapView, MapViewModel mapViewModel)
        {
            this._mapView = mapView;

            _networkingToolView = new NetworkingToolView { ViewModel = { mapView = mapView } };

            var owner = Window.GetWindow(mapView);

            if (owner != null)
            {
                _networkingToolView.Owner = owner;
            }

            // hook mapview events
            mapView.MapViewTapped += mapView_MapViewTapped;
            mapView.MapViewDoubleTapped += mapView_MapViewDoubleTapped;

            // hook listDirections
            _networkingToolView.listDirections.SelectionChanged += listDirections_SelectionChanged;

            // hook view resources
            _directionPointSymbol = _networkingToolView.LayoutRoot.Resources["directionPointSymbol"] as Symbol;

            mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "RoutesOverlay", Renderer = _networkingToolView.LayoutRoot.Resources["routesRenderer"] as Renderer });
            mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "StopsOverlay" });
            mapView.GraphicsOverlays.Add(new GraphicsOverlay { ID = "DirectionsOverlay", Renderer = _networkingToolView.LayoutRoot.Resources["directionsRenderer"] as Renderer, SelectionColor = Colors.Red });

            _stopsOverlay = mapView.GraphicsOverlays["StopsOverlay"];
            _routesOverlay = mapView.GraphicsOverlays["RoutesOverlay"];
            _directionsOverlay = mapView.GraphicsOverlays["DirectionsOverlay"];

            _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));

            Mediator.Register(Constants.ACTION_ROUTING_GET_DIRECTIONS, DoGetDirections);

            _locatorTask = new OnlineLocatorTask(new Uri(OnlineLocatorUrl)) { AutoNormalize = true };
        }
        private async void GetDirections_Click(object sender, RoutedEventArgs e)
        {
            //Reset
            DirectionsStackPanel.Children.Clear();
            var _stops = new List<Graphic>();
            var _locator = new OnlineLocatorTask(new Uri("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer"), "");
            var routeLayer = mapView1.Map.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
            routeLayer.Graphics.Clear();
            try
            {
                var fields = new List<string> { "Loc_name" };
                //Geocode from address
                var fromLocation = await _locator.GeocodeAsync(ParseAddress(FromTextBox.Text), fields, CancellationToken.None);
                if (fromLocation != null && fromLocation.Count > 0)
                {
                    var result = fromLocation.FirstOrDefault();
                    Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol };
                    graphicLocation.Attributes["address"] = result.Address;
                    graphicLocation.Attributes["score"] = result.Score;
                    _stops.Add(graphicLocation);
                    routeLayer.Graphics.Add(graphicLocation);
                }
                //Geocode to address
                var toLocation = await _locator.GeocodeAsync(ParseAddress(ToTextBox.Text), fields, CancellationToken.None);
                if (toLocation != null && toLocation.Count > 0)
                {
                    var result = toLocation.FirstOrDefault();
                    Graphic graphicLocation = new Graphic() { Geometry = result.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol };
                    graphicLocation.Attributes["address"] = result.Address;
                    graphicLocation.Attributes["score"] = result.Score;
                    _stops.Add(graphicLocation);
                    routeLayer.Graphics.Add(graphicLocation);
                }

                var routeTask = new OnlineRouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"));
                RouteParameters routeParams = await routeTask.GetDefaultParametersAsync();
                routeParams.ReturnRoutes = true;
                routeParams.ReturnDirections = true;
                routeParams.DirectionsLengthUnit = LinearUnits.Miles;
                routeParams.UseTimeWindows = false;
                routeParams.OutSpatialReference = mapView1.SpatialReference;
                routeParams.Stops = new FeaturesAsFeature(routeLayer.Graphics);

                var routeTaskResult = await routeTask.SolveAsync(routeParams);
                _directionsFeatureSet = routeTaskResult.Routes.FirstOrDefault();

                _directionsFeatureSet.RouteGraphic.Symbol = LayoutRoot.Resources["RouteSymbol"] as Esri.ArcGISRuntime.Symbology.Symbol;
                routeLayer.Graphics.Add(_directionsFeatureSet.RouteGraphic);

                var totalLength = _directionsFeatureSet.GetTotalLength(LinearUnits.Miles);
                var calculatedLength = _directionsFeatureSet.RouteDirections.Sum(x => x.GetLength(LinearUnits.Miles));

                TotalDistanceTextBlock.Text = string.Format("Total Distance: {0:N3} miles", totalLength); 

                TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.TotalTime.TotalMinutes));
                TitleTextBlock.Text = _directionsFeatureSet.RouteName;

                int i = 1;
                foreach (var item in _directionsFeatureSet.RouteDirections)
                {
                    TextBlock textBlock = new TextBlock() { Text = string.Format("{0:00} - {1}", i, item.Text), Tag = item.Geometry, Margin = new Thickness(0, 15,0,0), FontSize = 20 };
                    textBlock.Tapped += TextBlock_Tapped;
                    DirectionsStackPanel.Children.Add(textBlock);

                    var secondarySP = new StackPanel() { Orientation = Orientation.Horizontal };
                    if (item.Time.TotalMinutes > 0)
                    {
                        var timeTb = new TextBlock { Text = string.Format("Time : {0:N2} minutes", item.Time.TotalMinutes), Margin= new Thickness(45,0,0,0) };
                        secondarySP.Children.Add(timeTb);
                        var distTb = new TextBlock { Text = string.Format("Distance : {0:N2} miles", item.GetLength(LinearUnits.Miles)), Margin = new Thickness(25, 0, 0, 0) };
                        secondarySP.Children.Add(distTb);

                        DirectionsStackPanel.Children.Add(secondarySP);
                    }
                    i++;
                }

                mapView1.SetView(_directionsFeatureSet.RouteGraphic.Geometry.Extent.Expand(1.2));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        private async void GetDirectionsButton_Click(object sender, RoutedEventArgs e)
        {
            var from = await this.FindAddress(this.FromTextBox.Text);
            var to = await FindAddress(ToTextBox.Text);

            try
            {
                if (from == null)
                {
                    throw new Exception("Unable to find a match for '" + this.FromTextBox.Text + "'.");
                }

                if (to == null)
                {
                    throw new Exception("Unable to find a match for '" + this.ToTextBox.Text + "'.");
                }

                // get the RouteResults graphics layer; add the from/to graphics
                var routeGraphics = MyMap.Layers["RouteResults"] as GraphicsLayer;
                if (routeGraphics == null)
                {
                    throw new Exception("A graphics layer named 'RouteResults' was not found in the map.");
                }

                // code here to show address locations on the map
                var fromMapPoint = GeometryEngine.Project(from.Geometry, new SpatialReference(102100));
                var toMapPoint = GeometryEngine.Project(to.Geometry, new SpatialReference(102100));

                var fromSym = new SimpleMarkerSymbol { Style = SimpleMarkerStyle.Circle, Size = 16, Color = Colors.Green };
                var toSym = new SimpleMarkerSymbol { Style = SimpleMarkerStyle.Circle, Size = 16, Color = Colors.Red };

                var fromMapGraphic = new Graphic { Geometry = fromMapPoint, Symbol = fromSym };
                var toMapGraphic = new Graphic { Geometry = toMapPoint, Symbol = toSym };

                routeGraphics.Graphics.Add(fromMapGraphic);
                routeGraphics.Graphics.Add(toMapGraphic);

                var uri = new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");
                var routeTask = new OnlineRouteTask(uri);

                var routeParams = await routeTask.GetDefaultParametersAsync();
                routeParams.OutSpatialReference = MyMapView.SpatialReference;
                routeParams.DirectionsLengthUnit = LinearUnits.Miles;
                routeParams.ReturnDirections = true;

                // add stop parameters
                var stopGraphics = new List<Graphic>();
                stopGraphics.Add(from);
                stopGraphics.Add(to);
                routeParams.SetStops(stopGraphics);

                // save the route
                var routeResult = await routeTask.SolveAsync(routeParams);

                if(routeResult == null || routeResult.Routes == null || routeResult.Routes.Count == 0)
                {
                    throw new Exception("Unable to solve the route.");
                }

                var firstRoute = routeResult.Routes[0];

                var routeFeature = firstRoute.RouteFeature;
                var routeSym = new SimpleLineSymbol
                {
                    Color = Colors.Navy,
                    Style = SimpleLineStyle.Dash,
                    Width = 2
                };
                var routeGraphic = new Graphic(routeFeature.Geometry, routeSym);

                routeGraphics.Graphics.Add(routeGraphic);
                await MyMapView.SetViewAsync(routeGraphic.Geometry.Extent);

                var directionsBuilder = new System.Text.StringBuilder();
                var totalMiles = 0.0;
                var totalMinutes = 0.0;
                var step = 1;

                foreach (var d in firstRoute.RouteDirections)
                {
                    // appends a step number followed by a tab followed by the directions, then a new line
                    directionsBuilder.AppendFormat("{0} \t {1}", step.ToString(), d.Text + "\n");
                    step++;

                    totalMiles += d.GetLength(LinearUnits.Miles);
                    totalMinutes += d.Time.TotalMinutes;
                }

                // update the app UI
                this.RouteDistance.Text = totalMiles.ToString("0.00") + " miles";
                this.RouteTime.Text = totalMinutes.ToString("0.00") + " minutes";
                this.DirectionsTextBlock.Text = directionsBuilder.ToString();

            }
            catch (Exception exp)
            {
                this.DirectionsTextBlock.Text = exp.Message;
            }
        }