private async void chkOnline_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _routeGraphicsOverlay.Graphics.Clear();
                _stopsGraphicsOverlay.Graphics.Clear();
                panelRouteInfo.Visibility = Visibility.Collapsed;

                if (((Windows.UI.Xaml.Controls.CheckBox)sender).IsChecked == true)
                    _routeTask = await Task.Run<RouteTask>(() => new OnlineRouteTask(new Uri(OnlineRoutingService)));
                else
                {
                    try
                    {
                        var path = System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, LocalRoutingDatabase);
                        _routeTask = await Task.Run<LocalRouteTask>(() => new LocalRouteTask(path, LocalNetworkName));
                    }
                    catch
                    {
                        chkOnline.IsChecked = true;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
Exemplo n.º 2
0
        private async void SolveRouteClick(object sender, EventArgs e)
        {
            // Create a new route task using the San Diego route service URI
            RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);

            // Get the default parameters from the route task (defined with the service)
            RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();

            // Make some changes to the default parameters
            routeParams.ReturnStops      = true;
            routeParams.ReturnDirections = true;

            // Set the list of route stops that were defined at startup
            routeParams.SetStops(_routeStops);

            // Solve for the best route between the stops and store the result
            RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);

            // Get the first (should be only) route from the result
            Route firstRoute = solveRouteResult.Routes.First();

            // Get the route geometry (polyline)
            Polyline routePolyline = firstRoute.RouteGeometry;

            // Create a thick purple line symbol for the route
            SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Purple, 8.0);

            // Create a new graphic for the route geometry and add it to the graphics overlay
            Graphic routeGraphic = new Graphic(routePolyline, routeSymbol);

            _routeGraphicsOverlay.Graphics.Add(routeGraphic);

            // Get a list of directions for the route and display it in the list box
            DirectionsListBox.ItemsSource = firstRoute.DirectionManeuvers.Select(direction => direction.DirectionText);
        }
        private async void chkOnline_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _routeGraphicsOverlay.Graphics.Clear();
                _stopsGraphicsOverlay.Graphics.Clear();
                panelRouteInfo.Visibility = Visibility.Collapsed;

                if (((Windows.UI.Xaml.Controls.CheckBox)sender).IsChecked == true)
                {
                    _routeTask = await Task.Run <RouteTask>(() => new OnlineRouteTask(new Uri(OnlineRoutingService)));
                }
                else
                {
                    try
                    {
                        var path = System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, LocalRoutingDatabase);
                        _routeTask = await Task.Run <LocalRouteTask>(() => new LocalRouteTask(path, LocalNetworkName));
                    }
                    catch
                    {
                        chkOnline.IsChecked = true;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
Exemplo n.º 4
0
        private async Task CreateRouteTask()
        {
            try
            {
                Router = await RouteTask.CreateAsync(new Uri(Configuration.RouteUrl));
            }
            catch (Exception ex)
            {
                //TODO: Remove workaround when iOS bug is fixed
#if __IOS__
                exceptionCounter++;
                if (ex.Message == "403 (Forbidden)" && exceptionCounter <= 3)
                {
                    var credential = AuthenticationManager.Current.FindCredential(new Uri(Configuration.RouteUrl));
                    await CreateRouteTask();

                    return;
                }
#endif
                // This is returned when user hits the Cancel button in iOS or the back arrow in Android
                // It does not get caught in the SignInRenderer and needs to be handled here
                if (ex.Message.Contains("Token Required"))
                {
                    FromPlace = null;
                    ToPlace   = null;
                    IsBusy    = false;
                    return;
                }

                exceptionCounter = 0;
                throw ex;
            }
        }
Exemplo n.º 5
0
        private static void InititializeRoute(FrameworkElement fe, string route, DependencyProperty property)
        {
            PropertyRoute parentContext = GetPropertyRoute(fe.Parent ?? fe);

            if (parentContext == null)
            {
                throw new InvalidOperationException("Route attached property can not be set with null PropertyRoute: '{0}'".FormatWith(route));
            }

            var context = ContinueRouteExtension.Continue(parentContext, route);

            if (property == Common.RouteProperty)
            {
                SetPropertyRoute(fe, context);

                foreach (var task in RouteTask.GetInvocationListTyped())
                {
                    task(fe, route, context);
                }
            }
            else
            {
                foreach (var task in LabelOnlyRouteTask.GetInvocationListTyped())
                {
                    task(fe, route, context);
                }
            }
        }
Exemplo n.º 6
0
        private void MyDrawObject_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs e)
        {
            GraphicsLayer stopsGraphicsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
            Graphic       stop = new Graphic()
            {
                Geometry = e.Geometry, Symbol = LayoutRoot.Resources["StopSymbol"] as ESRI.ArcGIS.Client.Symbols.Symbol
            };

            stopsGraphicsLayer.Graphics.Add(stop);

            if (stopsGraphicsLayer.Graphics.Count > 1)
            {
                RouteTask routeTask = LayoutRoot.Resources["MyRouteTask"] as RouteTask;
                if (routeTask.IsBusy)
                {
                    routeTask.CancelAsync();
                    stopsGraphicsLayer.Graphics.RemoveAt(stopsGraphicsLayer.Graphics.Count - 1);
                }
                routeTask.SolveAsync(new RouteParameters()
                {
                    Stops = stopsGraphicsLayer, UseTimeWindows = false,
                    OutSpatialReference = MyMap.SpatialReference
                });
            }
        }
Exemplo n.º 7
0
        private async Task CreateRouteTask()
        {
            try
            {
                Router = await RouteTask.CreateAsync(new Uri(Configuration.RouteUrl));
            }
            catch (Exception)
            {
                // Try one more time, to work around a bug. dotnet-api/6024
                try
                {
                    var credential = await AuthenticationManager.Current.GenerateCredentialAsync(new Uri(Configuration.RouteUrl));

                    AuthenticationManager.Current.AddCredential(credential);
                    Router = await RouteTask.CreateAsync(new Uri(Configuration.RouteUrl));
                }
                catch (Exception exx)
                {
                    // This is returned when user hits the Cancel button in iOS or the back arrow in Android
                    // It does not get caught in the SignInRenderer and needs to be handled here
                    if (exx.Message.Contains("Token Required"))
                    {
                        FromPlace = null;
                        ToPlace   = null;
                        IsBusy    = false;
                        return;
                    }

                    throw;
                }
            }
        }
        void SolveRoute(MapPoint start, MapPoint end)
        {
            // The Esri World Network Analysis Services requires an ArcGIS Online Subscription.
            // In this sample use the North America only service on tasks.arcgisonline.com.
            var routeTask = new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");

            // Create a new list of graphics to send to the route task. Note don't use the graphcis returned from find
            // as the attributes cause issues with the route finding.
            var stops = new List <Graphic>()
            {
                new Graphic()
                {
                    Geometry = start
                },
                new Graphic()
                {
                    Geometry = end
                }
            };

            var routeParams = new RouteParameters()
            {
                Stops                  = stops,
                UseTimeWindows         = false,
                OutSpatialReference    = MyMap.SpatialReference,
                ReturnDirections       = false,
                IgnoreInvalidLocations = true
            };

            routeTask.Failed += (s, e) =>
            {
                MessageBox.Show("Route Task failed:" + e.Error);
            };

            // Register an inline handler for the SolveCompleted event.
            routeTask.SolveCompleted += (s, e) =>
            {
                // Add the returned route to the Map
                var myRoute = new Graphic()
                {
                    Geometry = e.RouteResults[0].Route.Geometry,
                    Symbol   = new SimpleLineSymbol()
                    {
                        Width = 10,
                        Color = new SolidColorBrush(Color.FromArgb(127, 0, 0, 255))
                    }
                };

                // Add a MapTip
                decimal totalTime = (decimal)e.RouteResults[0].Route.Attributes["Total_Time"];
                string  tip       = string.Format("{0} minutes", totalTime.ToString("#0.0"));
                myRoute.Attributes.Add("TIP", tip);

                MyRoutesGraphicsLayer.Graphics.Add(myRoute);
            };

            // Call the SolveAsync method
            routeTask.SolveAsync(routeParams);
        }
        private bool Init()
        {
            if (!InitUI())
            {
                return(false);
            }

            if (!CreateGraphicsLayer())
            {
                return(false);
            }

            // create the symbols
            _lineSymbol = new SimpleLineSymbol(System.Windows.Media.Colors.Red, 4) as LineSymbol;
            _fillSymbol = new SimpleFillSymbol()
            {
                //Fill = Brushes.Yellow,
                Fill            = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 255, 0)),
                BorderBrush     = System.Windows.Media.Brushes.Green,
                BorderThickness = 1
            } as FillSymbol;

            _saFillSymbol = new SimpleFillSymbol()
            {
                //Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 90, 90, 90)),  // gray
                Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 255, 0)),
                //BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Transparent),
                BorderBrush     = System.Windows.Media.Brushes.Green,
                BorderThickness = 1
            };

            _saLineSymbol = new SimpleLineSymbol()
            {
                Color = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, (byte)_random.Next(0, 255), (byte)_random.Next(0, 255), (byte)_random.Next(0, 255))),
                Width = 1,
            };


            // create the Geometry Service
            _geometryService = new GeometryService(_vm.GetPropValue("GeometryServiceUrl"));
            _geometryService.BufferCompleted += GeometryService_BufferCompleted;
            _geometryService.Failed          += GeometryService_Failed;


            // create the route task
            _facilitiesGraphicsLayer = new GraphicsLayer();
            _barriersGraphicsLayer   = new GraphicsLayer();
            _pointBarriers           = new List <Graphic>();
            _polylineBarriers        = new List <Graphic>();
            _polygonBarriers         = new List <Graphic>();
            string serviceAreaURL = _vm.GetPropValue("ServiceAreaServiceUrl");

            _routeTask = new RouteTask(serviceAreaURL);
            _routeTask.SolveServiceAreaCompleted += SolveServiceArea_Completed;
            _routeTask.Failed += SolveServiceArea_Failed;


            return(true);
        }
        public Routing()
        {
            InitializeComponent();

            stopsGraphicsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
            routeGraphicsLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
            routeTask = LayoutRoot.Resources["MyRouteTask"] as RouteTask;
        }
Exemplo n.º 11
0
        public Routing()
        {
            InitializeComponent();

            stopsGraphicsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
            routeGraphicsLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
            routeTask          = LayoutRoot.Resources["MyRouteTask"] as RouteTask;
        }
Exemplo n.º 12
0
 //Thread safe initialization of the route task
 private static Task <RouteTask> InitRouterAsync()
 {
     if (initializeTask == null)
     {
         string path = System.IO.Path.Combine(MapViewModel.GetDataFolder(), "Network/IndoorNavigation.geodatabase");
         initializeTask = RouteTask.CreateAsync(path, "Transportation_ND");
     }
     return(initializeTask);
 }
        public FindClosestResourceToolbar(MapWidget mapWidget, ObservableCollection <ESRI.ArcGIS.OperationsDashboard.DataSource> resourceDatasources, String resourceTypeField,
                                          ObservableCollection <ESRI.ArcGIS.OperationsDashboard.DataSource> barriersDataSources)
        {
            InitializeComponent();
            this.DataContext = this;

            // Store a reference to the MapWidget that the toolbar has been installed to.
            _mapWidget = mapWidget;

            //set up the route task with find closest facility option
            _routeTask = new RouteTask("http://route.arcgis.com/arcgis/rest/services/World/ClosestFacility/NAServer/ClosestFacility_World/solveClosestFacility");
            _routeTask.SolveClosestFacilityCompleted += SolveClosestFacility_Completed;
            _routeTask.Failed += SolveClosestFacility_Failed;

            //check if the graphicslayers need to be added to the map.
            setupGraphicsLayer();

            //set up the resources/facilities datasource in the combobox
            setupResourcesDataSource(resourceDatasources);

            ResourceTypes      = new ObservableCollection <ResourceType>();
            _resourceTypeField = resourceTypeField;

            //set up the barriers types combobox
            //this will have to be read from the config file...
            BarriersDataSouces = new ObservableCollection <ResourceLayer>();
            //set up facilities type dropdown
            ResourceLayer barrierLayer = new ResourceLayer();

            barrierLayer.Name       = "Select Barrier";
            barrierLayer.DataSource = null;
            BarriersDataSouces.Add(barrierLayer);

            //Barriers - passed from the configurar
            foreach (ESRI.ArcGIS.OperationsDashboard.DataSource datasource in barriersDataSources)
            {
                barrierLayer            = new ResourceLayer();
                barrierLayer.Name       = datasource.Name;
                barrierLayer.DataSource = datasource;
                BarriersDataSouces.Add(barrierLayer);
            }

            cmbBarriers.ItemsSource = BarriersDataSouces;

            _incidentMarkerSymbol = new SimpleMarkerSymbol
            {
                Size  = 20,
                Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle
            };

            //polyline barrier layer symbol
            _polylineBarrierSymbol = new client.Symbols.SimpleLineSymbol()
            {
                Color = new SolidColorBrush(Color.FromRgb(138, 43, 226)),
                Width = 5
            };
        }
        private async void Initialize()
        {
            try
            {
                // Update interface state.
                UpdateInterfaceState(SampleState.NotReady);

                // Create the map with a basemap.
                Map sampleMap = new Map(Basemap.CreateTopographicVector());
                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.
                _myMapView.GraphicsOverlays.Add(_routeOverlay);
                _myMapView.GraphicsOverlays.Add(_stopsOverlay);
                _myMapView.GraphicsOverlays.Add(_barriersOverlay);

                // 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);

                // Configure directions display.
                _directionsViewModel = new DirectionsViewModel(_directions);

                // Create the table view controller for displaying directions.
                _directionsController = new UITableViewController(UITableViewStyle.Plain);

                // The table view content is managed by the view model.
                _directionsController.TableView.Source = _directionsViewModel;

                // Create the view controller for configuring the route.
                _routeSettingsController = new RouteSettingsViewController();

                // Enable the UI.
                UpdateInterfaceState(SampleState.Ready);
            }
            catch (Exception e)
            {
                UpdateInterfaceState(SampleState.NotReady);
                System.Diagnostics.Debug.WriteLine(e);
                ShowMessage("Couldn't load sample", "Couldn't start the sample. See the debug output for detail.");
            }
        }
 private void SetupRouteTask()
 {
     if (!IsOnline)
     {
         _routeTask = new LocalRouteTask(_localRoutingDatabase, _networkName);
     }
     else
     {
         _routeTask = new OnlineRouteTask(new Uri(_onlineRoutingService));
     }
 }
Exemplo n.º 16
0
        private async Task FindRoute()
        {
            // Manage Buttons
            AcceptNavigation.Visibility = Visibility.Visible;
            AcceptNavigation.IsEnabled  = true;
            RefuseNavigation.Visibility = Visibility.Visible;
            RefuseNavigation.IsEnabled  = true;
            CancelNavigation.Visibility = Visibility.Hidden;
            CancelNavigation.IsEnabled  = false;
            TripRequestTB.Visibility    = Visibility.Visible;

            try
            {
                _solveRouteTask = await RouteTask.CreateAsync(_transportationNetwork);

                _routeParameters = await _solveRouteTask.CreateDefaultParametersAsync();

                var truckMode = from travelmode in _solveRouteTask.RouteTaskInfo.TravelModes
                                where travelmode.Type == "TRUCK"
                                select travelmode;
                _routeParameters.TravelMode             = truckMode.Last();
                _routeParameters.ReturnDirections       = true;
                _routeParameters.ReturnStops            = true;
                _routeParameters.ReturnRoutes           = true;
                _routeParameters.OutputSpatialReference = SpatialReferences.Wgs84;

                List <Stop> stops = new List <Stop> {
                    new Stop(_mapView.LocationDisplay.MapLocation),
                    new Stop(_startPoint)
                };
                _routeParameters.SetStops(stops);

                _routeResult = await _solveRouteTask.SolveRouteAsync(_routeParameters);

                _route = _routeResult.Routes.FirstOrDefault();

                // Display UI info
                TimeTB     = _route.TotalTime.ToString(@"hh\:mm\:ss");
                DistanceTB = Math.Round(_route.TotalLength / 1000, 2).ToString();

                // Diplay the route
                Polyline         routePolyline = _route.RouteGeometry;
                SimpleLineSymbol routeSymbol   = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.BlueViolet, 4.0f);
                Graphic          routeGraphic  = new Graphic(routePolyline, routeSymbol);
                _graphicsOverlay.Graphics.Add(routeGraphic);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            setExtent(_mapView.LocationDisplay.MapLocation, _startPoint);
            //StartNavigation();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets the requested route based on start and end location points.
        /// </summary>
        /// <returns>The requested route.</returns>
        /// <param name="fromLocation">From location.</param>
        /// <param name="toLocation">To location.</param>
        internal async Task <RouteResult> GetRequestedRouteAsync(MapPoint fromLocation, MapPoint toLocation)
        {
            if (this.Map.LoadStatus != Esri.ArcGISRuntime.LoadStatus.Loaded)
            {
                try
                {
                    await this.Map.LoadAsync();
                }
                catch
                {
                    return(null);
                }
            }

            try
            {
                var routeTask = await RouteTask.CreateAsync(this.Map.TransportationNetworks[0]);

                if (routeTask != null)
                {
                    // Get the default route parameters
                    var routeParams = await routeTask.CreateDefaultParametersAsync();

                    // Explicitly set values for some params
                    // Indoor networks do not support turn by turn navigation
                    routeParams.ReturnRoutes     = true;
                    routeParams.ReturnDirections = true;

                    // Create stops
                    var startPoint = new Stop(fromLocation);
                    var endPoint   = new Stop(toLocation);

                    // assign the stops to the route parameters
                    routeParams.SetStops(new List <Stop> {
                        startPoint, endPoint
                    });

                    // Execute routing
                    var routeResult = await routeTask.SolveRouteAsync(routeParams);

                    return(routeResult);
                }
                else
                {
                    return(null);
                }
            }
            catch
            {
                return(null);
            }
        }
        public Routing()
        {
            InitializeComponent();

			_extentGraphicsOverlay = MyMapView.GraphicsOverlays["ExtentGraphicsOverlay"];
			_routeGraphicsOverlay = MyMapView.GraphicsOverlays["RouteGraphicsOverlay"];
			_stopsGraphicsOverlay = MyMapView.GraphicsOverlays["StopsGraphicsOverlay"];

            var extent = new Envelope(-117.2595, 32.5345, -116.9004, 32.8005, SpatialReferences.Wgs84);
            _extentGraphicsOverlay.Graphics.Add(new Graphic(GeometryEngine.Project(extent, SpatialReferences.WebMercator)));

            _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));
        }
        public Routing()
        {
            InitializeComponent();

            _extentGraphicsOverlay = MyMapView.GraphicsOverlays["ExtentGraphicsOverlay"];
            _routeGraphicsOverlay  = MyMapView.GraphicsOverlays["RouteGraphicsOverlay"];
            _stopsGraphicsOverlay  = MyMapView.GraphicsOverlays["StopsGraphicsOverlay"];

            var extent = new Envelope(-117.2595, 32.5345, -116.9004, 32.8005, SpatialReferences.Wgs84);

            _extentGraphicsOverlay.Graphics.Add(new Graphic(GeometryEngine.Project(extent, SpatialReferences.WebMercator)));

            _routeTask = new OnlineRouteTask(new Uri(OnlineRoutingService));
        }
Exemplo n.º 20
0
        public async Task <RouteResult> GetRoute(IEnumerable <MapPoint> stops, CancellationToken cancellationToken)
        {
            if (stops == null)
            {
                throw new ArgumentNullException("stops");
            }

            List <Stop> stopList = new List <Stop>();

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

            string svc = routeService;

            try
            {
                //Calculate route
                RouteTask task = await RouteTask.CreateAsync(new Uri(svc), credential).ConfigureAwait(false);

                var parameters = await task.CreateDefaultParametersAsync().ConfigureAwait(false);

                parameters.SetStops(stopList);
                parameters.ReturnStops             = true;
                parameters.ReturnDirections        = true;
                parameters.RouteShapeType          = RouteShapeType.TrueShapeWithMeasures;
                parameters.OutputSpatialReference  = SpatialReferences.Wgs84;
                parameters.DirectionsDistanceUnits = Esri.ArcGISRuntime.UnitSystem.Metric;
                parameters.StartTime = DateTime.UtcNow;
                return(await task.SolveRouteAsync(parameters));
            }
            catch (System.Exception ex)
            {
                if (ex is Esri.ArcGISRuntime.Http.ArcGISWebException)
                {
                    var webex = (Esri.ArcGISRuntime.Http.ArcGISWebException)ex;
                    if (webex.Details.FirstOrDefault()?.Contains("Unlocated") == true)
                    {
                        //This occurs if the server couldn't find a route to the location
                        return(null);
                    }
                }
                throw;
            }
        }
        /// <summary>
        /// Initializes layers and tasks
        /// </summary>
        protected override async Task InitializeAsync()
        {
            // Create map with layers and set startup location
            var map = new Map()
            {
                InitialExtent = new Envelope(-13636132.3698584, 4546349.82732426, -13633579.1021618, 4547513.1599185, SpatialReferences.WebMercator)
            };

            Map = map;

            // Basemap layer from ArcGIS Online hosted service
            var basemap = new ArcGISTiledMapServiceLayer()
            {
                ID          = "Basemap",
                DisplayName = "Basemap",
                ServiceUri  = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer"
            };

            // Initialize layer in Try - Catch
            Exception exceptionToHandle = null;

            try
            {
                await basemap.InitializeAsync();

                map.Layers.Add(basemap);

                // Create graphics layer for start and endpoints
                CreateEndpointLayer();
                CreateRouteLayer();

                // Create geocoding and routing tasks
                _locatorTask  = new LocalLocatorTask(@"../../../../Data/Locators/SanFrancisco/SanFranciscoLocator.loc");
                _routeTask    = new LocalRouteTask(@"../../../../Data/Networks/RuntimeSanFrancisco.geodatabase", "Routing_ND");
                IsInitialized = true;
            }
            catch (Exception exception)
            {
                // Exception is thrown ie if layer url is not found - ie. {"Error code '400' : 'Invalid URL'"}
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                                                              "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                                                          "An error occured");
            }
        }
Exemplo n.º 22
0
        private async Task <RouteTask> GetRouter()
        {
            if (UseOnlineService)
            {
                return(await RouteTask.CreateAsync(new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route")));
            }
            try
            {
                BusyMessage = "Loading network...";
#if NETFX_CORE
                string path       = "Data\\Networks";
                var    foldername = Windows.ApplicationModel.Package.Current.InstalledLocation.Path + "\\" + path;
                var    datafolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(foldername);

                var folders = await datafolder.GetFoldersAsync();

                foreach (var folder in folders)
                {
                    var files = await folder.GetFilesAsync();

                    var file = files.Where(f => f.Name.EndsWith(".db")).FirstOrDefault();
                    if (file != null) //Locator found
                    {
                        return(await RouteTask.CreateAsync(file.Path, "Streets_ND"));
                    }
                }
#else
                string path = "..\\..\\..\\Data\\Networks";
                foreach (var folder in new System.IO.DirectoryInfo(path).GetDirectories())
                {
                    var file = folder.GetFiles("*.db").FirstOrDefault();
                    if (file != null) //Locator found
                    {
                        return(await RouteTask.CreateAsync(file.FullName, "Streets_ND"));
                    }
                }
#endif
            }
            catch
            {
                throw;
            }
            finally
            {
                BusyMessage = "";
            }
            return(null);
        }
Exemplo n.º 23
0
        private async void Initialize()
        {
            // Create and show a map.
            _mapView.Map = new Map(Basemap.CreateImagery());

            try
            {
                // Enable location display.
                _mapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
                await _mapView.LocationDisplay.DataSource.StartAsync();

                _mapView.LocationDisplay.IsEnabled = true;

                // Configure authentication.
                SetOAuthInfo();
                var credential = await AuthenticationManager.Current.GenerateCredentialAsync(_routingUri);

                AuthenticationManager.Current.AddCredential(credential);

                // Create the route task.
                _routeTask = await RouteTask.CreateAsync(_routingUri);

                // Create route display overlay and symbology.
                _routeOverlay = new GraphicsOverlay();
                SimpleLineSymbol routeSymbol =
                    new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Yellow, 1);
                _routeOverlay.Renderer = new SimpleRenderer(routeSymbol);

                // Create stop display overlay.
                _stopsOverlay = new GraphicsOverlay();

                // Add the overlays to the map.
                _mapView.GraphicsOverlays.Add(_routeOverlay);
                _mapView.GraphicsOverlays.Add(_stopsOverlay);

                // Enable tap-to-place stops.
                _mapView.GeoViewTapped += MapView_GeoViewTapped;

                // Update the UI.
                _helpLabel.Text = "Tap to set a start point";
            }
            catch (Exception ex)
            {
                new Android.Support.V7.App.AlertDialog.Builder(this).SetMessage("Failed to start sample")
                .SetTitle("Error").Show();
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        private async Task SetupRouteTask()
        {
            if (!IsOnline)
            {
                _routeTask = new LocalRouteTask(_localRoutingDatabase, _networkName);
            }
            else
            {
                _routeTask = new OnlineRouteTask(new Uri(_onlineRoutingService));
            }

            if (_routeTask != null)
            {
                _routeParams = await _routeTask.GetDefaultParametersAsync();
            }
        }
Exemplo n.º 25
0
        public static async Task InitializeAsync(Portal.ArcGISPortal portal)
        {
            string?url = portal.PortalInfo.HelperServices.RouteService?.Url;

            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentException("The provided portal does not have a routing service configured");
            }
            var c = portal.Credential;

            if (c == null)
            {
                throw new ArgumentException("User does not have a credential");
            }
            _routeTask = await RouteTask.CreateAsync(new Uri(url), c).ConfigureAwait(false);
        }
        public RoutingBarriers()
        {
            InitializeComponent();

            _routeTask =
                new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");
            _routeTask.SolveCompleted += routeTask_SolveCompleted;
            _routeTask.Failed += routeTask_Failed;

            _routeParams.Stops = _stops;
            _routeParams.Barriers = _barriers;
            _routeParams.UseTimeWindows = false;

            barriersLayer = MyMap.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;
            stopsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
        }
Exemplo n.º 27
0
        public RoutingBarriers()
        {
            InitializeComponent();

            _routeTask =
                new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");
            _routeTask.SolveCompleted += routeTask_SolveCompleted;
            _routeTask.Failed         += routeTask_Failed;

            _routeParams.Stops          = _stops;
            _routeParams.Barriers       = _barriers;
            _routeParams.UseTimeWindows = false;

            barriersLayer = MyMap.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;
            stopsLayer    = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
        }
Exemplo n.º 28
0
        private async void SolveRouteButton_Click(object sender, EventArgs e)
        {
            try
            {
                // Create a new route task using the San Diego route service URI.
                RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);

                // Get the default parameters from the route task (defined with the service).
                RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();

                // Make some changes to the default parameters.
                routeParams.ReturnStops      = true;
                routeParams.ReturnDirections = true;

                // Set the list of route stops that were defined at startup.
                routeParams.SetStops(_routeStops);

                // Solve for the best route between the stops and store the result.
                RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);

                // Get the first (should be only) route from the result.
                Route firstRoute = solveRouteResult.Routes.First();

                // Get the route geometry (polyline).
                Polyline routePolyline = firstRoute.RouteGeometry;

                // Create a thick purple line symbol for the route.
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 8.0);

                // Create a new graphic for the route geometry and add it to the graphics overlay.
                Graphic routeGraphic = new Graphic(routePolyline, routeSymbol)
                {
                    ZIndex = 0
                };
                _routeGraphicsOverlay.Graphics.Add(routeGraphic);

                // Get a list of directions for the route and display it in the list box.
                _directionsList = firstRoute.DirectionManeuvers;

                // Enable the directions button.
                _directionsButton.Enabled = true;
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
Exemplo n.º 29
0
        public ServiceAreas()
        {
            InitializeComponent();

            facilitiesGraphicsLayer = MyMap.Layers["MyFacilityGraphicsLayer"] as GraphicsLayer;
            barriersGraphicsLayer   = MyMap.Layers["MyBarrierGraphicsLayer"] as GraphicsLayer;

            myRouteTask = new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea");
            myRouteTask.SolveServiceAreaCompleted += SolveServiceArea_Completed;
            myRouteTask.Failed += SolveServiceArea_Failed;

            pointBarriers    = new List <Graphic>();
            polylineBarriers = new List <Graphic>();
            polygonBarriers  = new List <Graphic>();

            random = new Random();
        }
Exemplo n.º 30
0
        private async void AddTrafficLayer()
        {
            try
            {
                _routeService = new Uri("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve");

                var route = await RouteTask.CreateAsync(_routeService);


                ArcGISMapImageLayer traffic = new ArcGISMapImageLayer(new Uri(_trafficLayerURL));
                MyMapView.Map.OperationalLayers.Add(traffic);
            }
            catch (Exception ex)
            {
                await DisplayAlert("Error", ex.Message, "OK");
            }
        }
        public ServiceAreas()
        {
            InitializeComponent();

            facilitiesGraphicsLayer = MyMap.Layers["MyFacilityGraphicsLayer"] as GraphicsLayer;
            barriersGraphicsLayer = MyMap.Layers["MyBarrierGraphicsLayer"] as GraphicsLayer;

            myRouteTask = new RouteTask("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Service%20Area");
            myRouteTask.SolveServiceAreaCompleted += SolveServiceArea_Completed;
            myRouteTask.Failed += SolveServiceArea_Failed;

            pointBarriers = new List<Graphic>();
            polylineBarriers = new List<Graphic>();
            polygonBarriers = new List<Graphic>();

            random = new Random();
        }
Exemplo n.º 32
0
        private async void SolveRouteClick(object sender, EventArgs e)
        {
            try
            {
                // Create a new route task using the San Diego route service URI
                RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);

                // Get the default parameters from the route task (defined with the service)
                RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();

                // Make some changes to the default parameters
                routeParams.ReturnStops      = true;
                routeParams.ReturnDirections = true;

                // Set the list of route stops that were defined at startup
                routeParams.SetStops(_routeStops);

                // Solve for the best route between the stops and store the result
                RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);

                // Get the first (should be only) route from the result
                Route firstRoute = solveRouteResult.Routes.First();

                // Get the route geometry (polyline)
                Polyline routePolyline = firstRoute.RouteGeometry;

                // Create a thick purple line symbol for the route
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 8.0);

                // Create a new graphic for the route geometry and add it to the graphics overlay
                Graphic routeGraphic = new Graphic(routePolyline, routeSymbol)
                {
                    ZIndex = 0
                };
                _routeGraphicsOverlay.Graphics.Add(routeGraphic);

                // Get a list of directions for the route and display it in the list box
                CreateDirectionsDialog(firstRoute.DirectionManeuvers.Select(d => d.DirectionText));
                _showHideDirectionsButton.Enabled = true;
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }
 private async void MyMap_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
 {
     var mp = MyMap.ScreenToMap(e.GetPosition(MyMap));
     Graphic g = new Graphic() { Geometry = mp };
     var stopsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
     var barriersLayer = MyMap.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;
     if (StopsRadioButton.IsChecked.Value)
     {
         stopsLayer.Graphics.Add(g);
     }
     else if (BarriersRadioButton.IsChecked.Value)
     {
         barriersLayer.Graphics.Add(g);
     }
     if (stopsLayer.Graphics.Count > 1)
     {
         try
         {
             var routeTask = new RouteTask(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route"));
             var result = await routeTask.SolveAsync(new RouteParameter()
             {
                 Stops = new FeatureStops(stopsLayer.Graphics),
                 Barriers = new FeatureBarriers(barriersLayer.Graphics),
                 UseTimeWindows = false,
                 OutSpatialReference = MyMap.SpatialReference
             });
             if (result != null)
             {
                 if (result.Directions != null && result.Directions.Count > 0)
                 {
                     var direction = result.Directions.FirstOrDefault();
                     if (direction != null && direction.RouteSummary != null)
                         await new MessageDialog(string.Format("{0} minutes", direction.RouteSummary.TotalDriveTime.ToString("#0.000"))).ShowAsync();
                 }
                 GraphicsLayer routeLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
                 routeLayer.Graphics.Clear();
                 routeLayer.Graphics.AddRange(result.Routes);
             }
         }
         catch (Exception ex)
         {
             System.Diagnostics.Debug.WriteLine(ex.Message);
         }
     }
 }
Exemplo n.º 34
0
        private async void SolveRouteClick(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                // Create a new route task using the San Diego route service URI
                RouteTask solveRouteTask = await RouteTask.CreateAsync(_sanDiegoRouteServiceUri);

                // Get the default parameters from the route task (defined with the service)
                RouteParameters routeParams = await solveRouteTask.CreateDefaultParametersAsync();

                // Make some changes to the default parameters
                routeParams.ReturnStops      = true;
                routeParams.ReturnDirections = true;

                // Set the list of route stops that were defined at startup
                routeParams.SetStops(_routeStops);

                // Solve for the best route between the stops and store the result
                RouteResult solveRouteResult = await solveRouteTask.SolveRouteAsync(routeParams);

                // Get the first (should be only) route from the result
                Route firstRoute = solveRouteResult.Routes.First();

                // Get the route geometry (polyline)
                Polyline routePolyline = firstRoute.RouteGeometry;

                // Create a thick purple line symbol for the route
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Purple, 8.0);

                // Create a new graphic for the route geometry and add it to the graphics overlay
                Graphic routeGraphic = new Graphic(routePolyline, routeSymbol)
                {
                    ZIndex = 0
                };
                _routeGraphicsOverlay.Graphics.Add(routeGraphic);

                // Get a list of directions for the route and display it in the list box
                IReadOnlyList <DirectionManeuver> directionsList = firstRoute.DirectionManeuvers;
                DirectionsListBox.ItemsSource = directionsList;
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.ToString(), "Error").ShowAsync();
            }
        }
Exemplo n.º 35
0
        public CustomParameters()
        {
            InitializeComponent();

            _stopsGraphicsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
            _routeGraphicsLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;

            _routeTask = new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");

            _routeParams = new RouteParameters()
            {
                Stops               = _stopsGraphicsLayer,
                UseTimeWindows      = false,
                OutSpatialReference = MyMap.SpatialReference
            };

            _routeTask.CustomParameters.Add("myParameterName", "0");
        }
        private async void chkOnline_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _routeGraphicsOverlay.Graphics.Clear();
                _stopsGraphicsOverlay.Graphics.Clear();
                panelRouteInfo.Visibility = Visibility.Collapsed;

                if (((CheckBox)sender).IsChecked == true)
                    _routeTask = await Task.Run<RouteTask>(() => new OnlineRouteTask(new Uri(OnlineRoutingService)));
                else
                    _routeTask = await Task.Run<RouteTask>(() => new LocalRouteTask(LocalRoutingDatabase, LocalNetworkName));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Sample Error");
            }
        }
        public RoutingDirectionsTaskAsync()
        {
            InitializeComponent();

            _locator = new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");

            _routeTask = new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");

            _routeParams = new RouteParameters()
            {
                ReturnRoutes = false,
                ReturnDirections = true,
                DirectionsLengthUnits = esriUnits.esriMiles,
                Stops = _stops,
                UseTimeWindows = false,
            };

            _routeGraphicsLayer = (MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer);            
        }
Exemplo n.º 38
0
        private async void Initialize()
        {
            // Create and add the map.
            _mapView.Map = new Map(Basemap.CreateImagery());

            try
            {
                // Configure location display.
                _mapView.LocationDisplay.AutoPanMode = LocationDisplayAutoPanMode.Recenter;
                await _mapView.LocationDisplay.DataSource.StartAsync();

                _mapView.LocationDisplay.IsEnabled = true;

                // Enable authentication.
                SetOAuthInfo();

                // Create the route task.
                _routeTask = await RouteTask.CreateAsync(new System.Uri("https://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"));

                // Create route display overlay and symbology.
                _routeOverlay = new GraphicsOverlay();
                SimpleLineSymbol routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Yellow, 1);
                _routeOverlay.Renderer = new SimpleRenderer(routeSymbol);

                // Create stop display overlay.
                _stopsOverlay = new GraphicsOverlay();

                // Add the overlays to the map.
                _mapView.GraphicsOverlays.Add(_routeOverlay);
                _mapView.GraphicsOverlays.Add(_stopsOverlay);

                // Wait for the user to place stops.
                _mapView.GeoViewTapped += MapView_GeoViewTapped;

                // Updat the help text.
                _helpLabel.Text = "Tap to set a start point";
            }
            catch (Exception ex)
            {
                new UIAlertView("Error", "Failed to start sample", (IUIAlertViewDelegate)null, "OK", null).Show();
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        public ClosestFacility()
        {
            InitializeComponent();

            facilitiesGraphicsLayer = MyMap.Layers["MyFacilitiesGraphicsLayer"] as GraphicsLayer;
            IncidentsGraphicsLayer = MyMap.Layers["MyIncidentsGraphicsLayer"] as GraphicsLayer;
            barriersGraphicsLayer = MyMap.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;
            routeGraphicsLayer = MyMap.Layers["MyRoutesGraphicsLayer"] as GraphicsLayer;

            myRouteTask = new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility");
            myRouteTask.SolveClosestFacilityCompleted += SolveClosestFacility_Completed;
            myRouteTask.Failed += SolveClosestFacility_Failed;

            pointBarriers = new List<Graphic>();
            polylineBarriers = new List<Graphic>();
            polygonBarriers = new List<Graphic>();

            random = new Random();
        }
        public RoutingDirections()
        {
            InitializeComponent();

            _routeParams = new RouteParameters()
            {
                ReturnRoutes = false,
                ReturnDirections = true,
                DirectionsLengthUnits = esriUnits.esriMiles,
                Stops = _stops,
                UseTimeWindows = false
            };

            _routeTask =
                new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");
            _routeTask.SolveCompleted += routeTask_SolveCompleted;
            _routeTask.Failed += task_Failed;

            _locator =
                new Locator("http://tasks.arcgisonline.com/ArcGIS/rest/services/Locators/TA_Address_NA/GeocodeServer");
            _locator.AddressToLocationsCompleted += locator_AddressToLocationsCompleted;
            _locator.Failed += task_Failed;
        }
        public RoutingBarriers()
        {
            InitializeComponent();

            myDrawObject = new Draw(MyMap)
            {
                DrawMode = DrawMode.Point,
                IsEnabled = true
            };
            myDrawObject.DrawComplete += myDrawObject_DrawComplete;

            _routeTask =
                new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");
            _routeTask.SolveCompleted += routeTask_SolveCompleted;
            _routeTask.Failed += routeTask_Failed;

            _routeParams.Stops = _stops;
            _routeParams.Barriers = _barriers;
            _routeParams.UseTimeWindows = false;

            barriersLayer = MyMap.Layers["MyBarriersGraphicsLayer"] as GraphicsLayer;
            stopsLayer = MyMap.Layers["MyStopsGraphicsLayer"] as GraphicsLayer;
        }
        public RoutingDirections()
        {
            InitializeComponent();

            _routeParams = new RouteParameters()
            {
                ReturnRoutes = false,
                ReturnDirections = true,
                DirectionsLengthUnits = esriUnits.esriMiles,
                Stops = _stops,
                UseTimeWindows = false,
            };

            _routeTask =
                new RouteTask("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/Route");
            _routeTask.SolveCompleted += routeTask_SolveCompleted;
            _routeTask.Failed += task_Failed;

            _locator =
                new Locator("http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer");
            _locator.FindCompleted += locator_FindCompleted;
            _locator.Failed += task_Failed;
        }
 private void GetDirectionsFromAtoB(Graphic origin, Graphic destination)
 {
     if (origin == null || destination == null) return;
     var l = MyMap.Layers["RouteResultsLayer"] as GraphicsLayer;
     l.Graphics.Clear();
     var stops = new List<Graphic>();
     stops.Add(origin);
     stops.Add(destination);
     #region RouteTask - Gets directions from A (Origin) to B (Destination)
     var routeTask = new RouteTask(ROUTE_URL);
     routeTask.SolveCompleted += (s, e) =>
     {
         MyProgressBar.IsIndeterminate = false;
         var featureSet = e.RouteResults.FirstOrDefault().Directions;
         var g = new Graphic() { Geometry = featureSet.MergedGeometry };
         g.Geometry.SpatialReference = MyMap.SpatialReference;
         l.Graphics.Add(g);
         MyMap.ZoomTo(Expand(l.FullExtent));
         BufferPathGeometry(g); // widens the scope of path geometry.
     };
     routeTask.Failed += (s, e) =>
     {
         MyProgressBar.IsIndeterminate = false;
         MessageBox.Show(string.Format("Get directions to '{0}' failed with error '{1}'", pointB.Geometry as MapPoint, e.Error.Message));
     };
     MyProgressBar.IsIndeterminate = true;
     routeTask.SolveAsync(new RouteParameters()
     {
         DirectionsLengthUnits = esriUnits.esriMiles,
         OutSpatialReference = MyMap.SpatialReference,
         Stops = stops,
         ReturnDirections = true
     });
     #endregion
 }
		/// <summary>
		/// Initializes layers and tasks
		/// </summary>
        protected override async Task InitializeAsync()
        {
            // Create map with layers and set startup location
            var map = new Map()
                {
                    InitialExtent = new Envelope(-13636132.3698584, 4546349.82732426, -13633579.1021618, 4547513.1599185, SpatialReferences.WebMercator)
                };
            Map = map;

            // Basemap layer from ArcGIS Online hosted service
            var basemap = new ArcGISTiledMapServiceLayer()
            {
                ID = "Basemap",
                DisplayName = "Basemap",
				ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer"
			};

            // Initialize layer in Try - Catch 
            Exception exceptionToHandle = null;
            try
            {
                await basemap.InitializeAsync();
                map.Layers.Add(basemap);

                // Create graphics layer for start and endpoints
                CreateEndpointLayer();
                CreateRouteLayer();

                // Create geocoding and routing tasks
				_locatorTask = new LocalLocatorTask(@"../../../../Data/Locators/SanFrancisco/SanFranciscoLocator.loc");
				_routeTask = new LocalRouteTask(@"../../../../Data/Networks/RuntimeSanFrancisco.geodatabase", "Routing_ND");
				IsInitialized = true;
			}
            catch (Exception exception)
            {
                // Exception is thrown ie if layer url is not found - ie. {"Error code '400' : 'Invalid URL'"} 
                exceptionToHandle = exception;
            }

            if (exceptionToHandle != null)
            {
                // Initialization failed, show message and return
                await MessageService.Instance.ShowMessage(string.Format(
                    "Could not create basemap. Error = {0}", exceptionToHandle.ToString()),
                    "An error occured");
            }
        }
        private async void GetDirections_Click(object sender, RoutedEventArgs e)
        {
            //Reset
            DirectionsStackPanel.Children.Clear();
            var _stops = new List<Graphic>();
            var _locator = new ESRI.ArcGIS.Runtime.Tasks.Locator(new Uri("http://tasks.arcgisonline.com/ArcGIS/rest/services/Locators/TA_Address_NA/GeocodeServer"));
            var routeLayer = MyMap.Layers["MyRouteGraphicsLayer"] as GraphicsLayer;
            routeLayer.Graphics.Clear();
            try
            {
                //Geocode from address
                var fromLocation = await _locator.AddressToLocationsAsync(ParseAddress(FromTextBox.Text));
                if (fromLocation.AddressCandidates != null && fromLocation.AddressCandidates.Count > 0)
                {
                    AddressCandidate address = fromLocation.AddressCandidates.FirstOrDefault();
                    Graphic graphicLocation = new Graphic() { Geometry = address.Location, Symbol = LayoutRoot.Resources["FromSymbol"] as ISymbol };
                    graphicLocation.Attributes["address"] = address.Address;
                    graphicLocation.Attributes["score"] = address.Score;
                    _stops.Add(graphicLocation);
                    routeLayer.Graphics.Add(graphicLocation);
                }
                //Geocode to address
                var toLocation = await _locator.AddressToLocationsAsync(ParseAddress(ToTextBox.Text));
                if (toLocation.AddressCandidates != null && toLocation.AddressCandidates.Count > 0)
                {
                    AddressCandidate address = toLocation.AddressCandidates.FirstOrDefault();
                    Graphic graphicLocation = new Graphic() { Geometry = address.Location, Symbol = LayoutRoot.Resources["ToSymbol"] as ISymbol };
                    graphicLocation.Attributes["address"] = address.Address;
                    graphicLocation.Attributes["score"] = address.Score;
                    _stops.Add(graphicLocation);
                    routeLayer.Graphics.Add(graphicLocation);
                }
                //Get route between from and to
                var _routeParams = new RouteParameter()
                {
                    ReturnRoutes = false,
                    ReturnDirections = true,
                    DirectionsLengthUnits = MapUnit.Miles,
                    Stops = new FeatureStops(_stops),
                    UseTimeWindows = false
                };

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

                _routeParams.OutSpatialReference = MyMap.SpatialReference;
                var routeTaskResult = await _routeTask.SolveAsync(_routeParams);
                _directionsFeatureSet = routeTaskResult.Directions.FirstOrDefault();

                routeLayer.Graphics.Add(new Graphic() { Geometry = _directionsFeatureSet.MergedGeometry, Symbol = LayoutRoot.Resources["RouteSymbol"] as ISymbol });
                TotalDistanceTextBlock.Text = string.Format("Total Distance: {0}", FormatDistance(_directionsFeatureSet.RouteSummary.TotalLength, "miles"));
                TotalTimeTextBlock.Text = string.Format("Total Time: {0}", FormatTime(_directionsFeatureSet.RouteSummary.TotalTime));
                TitleTextBlock.Text = _directionsFeatureSet.RouteName;

                int i = 1;
                foreach (Graphic graphic in _directionsFeatureSet.Graphics)
                {
                    System.Text.StringBuilder text = new System.Text.StringBuilder();
                    text.AppendFormat("{0}. {1}", i, graphic.Attributes["text"]);
                    if (i > 1 && i < _directionsFeatureSet.Graphics.Count)
                    {
                        string distance = FormatDistance(Convert.ToDouble(graphic.Attributes["length"]), "miles");
                        string time = null;
                        if (graphic.Attributes.ContainsKey("time"))
                        {
                            time = FormatTime(Convert.ToDouble(graphic.Attributes["time"]));
                        }
                        if (!string.IsNullOrEmpty(distance) || !string.IsNullOrEmpty(time))
                            text.Append(" (");
                        text.Append(distance);
                        if (!string.IsNullOrEmpty(distance) && !string.IsNullOrEmpty(time))
                            text.Append(", ");
                        text.Append(time);
                        if (!string.IsNullOrEmpty(distance) || !string.IsNullOrEmpty(time))
                            text.Append(")");
                    }
                    TextBlock textBlock = new TextBlock() { Text = text.ToString(), Tag = graphic, Margin = new Thickness(4) };
                    textBlock.Tapped += TextBlock_Tapped;
                    DirectionsStackPanel.Children.Add(textBlock);
                    i++;
                }
                MyMap.ZoomTo(_directionsFeatureSet.RouteSummary.Extent.Expand(0.6));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        private bool Init()
        {
            if (!InitUI())
            return false;

              if (!CreateGraphicsLayer())
            return false;

              // create the symbols
              _lineSymbol = new SimpleLineSymbol(System.Windows.Media.Colors.Red, 4) as LineSymbol;
              _fillSymbol = new SimpleFillSymbol()
              {
            //Fill = Brushes.Yellow,
            Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 255, 0)),
            BorderBrush = System.Windows.Media.Brushes.Green,
            BorderThickness = 1
              } as FillSymbol;

              _saFillSymbol = new SimpleFillSymbol()
              {
            //Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 90, 90, 90)),  // gray
            Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 255, 0)),
            //BorderBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Transparent),
            BorderBrush = System.Windows.Media.Brushes.Green,
            BorderThickness = 1
              };

              _saLineSymbol = new SimpleLineSymbol()
              {
            Color = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, (byte)_random.Next(0, 255), (byte)_random.Next(0, 255), (byte)_random.Next(0, 255))),
            Width = 1,
              };

              // create the Geometry Service
              _geometryService = new GeometryService(_vm.GetPropValue("GeometryServiceUrl"));
              _geometryService.BufferCompleted += GeometryService_BufferCompleted;
              _geometryService.Failed += GeometryService_Failed;

              // create the route task
              _facilitiesGraphicsLayer = new GraphicsLayer();
              _barriersGraphicsLayer = new GraphicsLayer();
              _pointBarriers = new List<Graphic>();
              _polylineBarriers = new List<Graphic>();
              _polygonBarriers = new List<Graphic>();
              string serviceAreaURL = _vm.GetPropValue("ServiceAreaServiceUrl");
              _routeTask = new RouteTask(serviceAreaURL);
              _routeTask.SolveServiceAreaCompleted += SolveServiceArea_Completed;
              _routeTask.Failed += SolveServiceArea_Failed;

              return true;
        }
Exemplo n.º 47
0
        void SolveRoute(MapPoint start, MapPoint end)
        {
            // The Esri World Network Analysis Services requires an ArcGIS Online Subscription.
            // In this sample use the North America only service on tasks.arcgisonline.com.
            var routeTask = new RouteTask("http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route");

            // Create a new list of graphics to send to the route task. Note don't use the graphcis returned from find
            // as the attributes cause issues with the route finding.
            var stops = new List<Graphic>()
            {
                new Graphic() { Geometry = start},
                new Graphic() { Geometry = end}
            };

            var routeParams = new RouteParameters()
            {
                Stops = stops,
                UseTimeWindows = false,
                OutSpatialReference = MyMap.SpatialReference,
                ReturnDirections = false,
                IgnoreInvalidLocations = true
            };

            routeTask.Failed += (s, e) =>
            {
                MessageBox.Show("Route Task failed:" + e.Error);
            };

            // Register an inline handler for the SolveCompleted event.
            routeTask.SolveCompleted += (s, e) =>
            {
                // Add the returned route to the Map
                var myRoute = new Graphic()
                {
                    Geometry = e.RouteResults[0].Route.Geometry,
                    Symbol = new SimpleLineSymbol()
                    {
                        Width = 10,
                        Color = new SolidColorBrush(Color.FromArgb(127, 0, 0, 255))
                    }
                };

                // Add a MapTip
                decimal totalTime = (decimal)e.RouteResults[0].Route.Attributes["Total_Time"];
                string tip = string.Format("{0} minutes", totalTime.ToString("#0.0"));
                myRoute.Attributes.Add("TIP", tip);

                MyRoutesGraphicsLayer.Graphics.Add(myRoute);
            };

            // Call the SolveAsync method
            routeTask.SolveAsync(routeParams);
        }
 private async Task SetupRouteTask()
 {
     if (!IsOnline)
     {
         _routeTask = new LocalRouteTask(_localRoutingDatabase, _networkName);
     }
     else
     {
         _routeTask = new OnlineRouteTask(new Uri(_onlineRoutingService));
     }
 }
Exemplo n.º 49
0
        private void GetDirectionToDestination(Graphic destination)
        {
            if (myLocation == null || destination == null) return;

            EnableDirectionsButton(true);
            DirectionsStackPanel.Children.Clear();
            UpdateLayer("FindResultsLayer", false, false);
            var d = UpdateLayer("DestinationLayer", true, true);
            d.Graphics.Add(destination);
            var l = UpdateLayer("RouteResultsLayer", true, true);

            var stops = new List<Graphic>();
            stops.Add(myLocation);
            stops.Add(destination);
            #region RouteTask - Gets directions from A (Current Location) to B (Destination)
            var routeTask = new RouteTask(ROUTE_URL);
            routeTask.SolveCompleted += (s, e) =>
            {
                MyProgressBar.IsIndeterminate = false;              
                var featureSet = e.RouteResults.FirstOrDefault().Directions;
                l.Graphics.Add(new Graphic() { Geometry = featureSet.MergedGeometry });
                UpdateDirectionsPanel(featureSet);
                MyMap.ZoomTo(Expand(l.FullExtent));
            };
            routeTask.Failed += (s, e) =>
            {
                MyProgressBar.IsIndeterminate = false;
                MessageBox.Show(string.Format("Get directions to '{0}' failed with error '{1}'", destination.Geometry as MapPoint, e.Error.Message));
                ShowElement(MyMap);
            };
            MyProgressBar.IsIndeterminate = true;
            routeTask.SolveAsync(new RouteParameters()
            {
                DirectionsLengthUnits = esriUnits.esriMiles,
                OutSpatialReference = MyMap.SpatialReference,
                Stops = stops,
                ReturnDirections = true
            });
            #endregion
        }      
Exemplo n.º 50
0
        /// <summary>
        /// Creates a route from a service template and date. Uses a random route name.
        /// </summary>
        private void CreateRoute(DateTime date, ServiceTemplate serviceTemplate, BusinessAccount ownerBusinessAccount, int clientIndex)
        {
            var newRoute = new Route
            {
                Id = Guid.NewGuid(),
                Name = _routeNames.RandomItem(),
                Date = date.Date,
                RouteType = serviceTemplate.Name,
                OwnerBusinessAccount = ownerBusinessAccount,
                CreatedDate = DateTime.UtcNow,
                LastModified = DateTime.UtcNow
            };

            //Add employees to the Route
            newRoute.Employees.Add(_employeesDesignData.DesignEmployees.FirstOrDefault(e => e.FirstName == "Jon"));

            //Add vehicles to the Route
            newRoute.Vehicles.Add(_vehiclesDesignData.DesignVehicles.RandomItem());

            var orderInRoute = 1;

            var startingClientIndex = clientIndex * 6;

            //Create Services and RouteTasks, add them to the Route
            for (var i = startingClientIndex; i <= (startingClientIndex + 5); i++)
            {
                //Prevents you from trying to add a client that doesnt exist in Design Data
                if (i > _clientsDesignData.DesignClients.Count())
                    break;

                var currentClient = _clientsDesignData.DesignClients.ElementAt(i);

                //Take the first location from the client
                var currentLocation = currentClient.Locations.ElementAt(0);

                var newService = new Service
                {
                    ServiceDate = newRoute.Date,
                    ServiceTemplate = serviceTemplate.MakeChild(ServiceTemplateLevel.ServiceDefined),
                    Client = currentClient,
                    ServiceProvider = ownerBusinessAccount,
                    CreatedDate = DateTime.UtcNow,
                    LastModified = DateTime.UtcNow
                };

                newService.ServiceTemplate.SetDestination(currentLocation);

                var routeTask = new RouteTask
                {
                    OrderInRouteDestination = 1,
                    Date = newRoute.Date,
                    Location = currentClient.Locations.ElementAt(0),
                    Client = currentClient,
                    Name = newRoute.RouteType,
                    EstimatedDuration = new TimeSpan(0, _random.Next(25), 0),
                    OwnerBusinessAccount = ownerBusinessAccount,
                    Service = newService,
                    TaskStatus = ownerBusinessAccount.TaskStatuses.FirstOrDefault(ts => ts.DefaultTypeInt != null && ts.DefaultTypeInt == ((int)StatusDetail.RoutedDefault)),
                    CreatedDate = DateTime.UtcNow,
                    LastModified = DateTime.UtcNow
                };

                var routeDestination = new RouteDestination
                {
                    OrderInRoute = orderInRoute,
                    CreatedDate = DateTime.UtcNow,
                    LastModified = DateTime.UtcNow
                };
                routeDestination.RouteTasks.Add(routeTask);
                newRoute.RouteDestinations.Add(routeDestination);

                orderInRoute++;
            }

            DesignRoutes.Add(newRoute);
        }
        public FindClosestResourceToolbar(MapWidget mapWidget, ObservableCollection<ESRI.ArcGIS.OperationsDashboard.DataSource> resourceDatasources, String resourceTypeField, 
            ObservableCollection<ESRI.ArcGIS.OperationsDashboard.DataSource> barriersDataSources)
        {

            InitializeComponent();
            this.DataContext = this; 

            // Store a reference to the MapWidget that the toolbar has been installed to.
            _mapWidget = mapWidget;

            //set up the route task with find closest facility option 
            _routeTask = new RouteTask("http://route.arcgis.com/arcgis/rest/services/World/ClosestFacility/NAServer/ClosestFacility_World/solveClosestFacility");
            _routeTask.SolveClosestFacilityCompleted += SolveClosestFacility_Completed;
            _routeTask.Failed += SolveClosestFacility_Failed;

            //check if the graphicslayers need to be added to the map. 
            setupGraphicsLayer(); 

            //set up the resources/facilities datasource in the combobox 
            setupResourcesDataSource(resourceDatasources); 

            ResourceTypes = new ObservableCollection<ResourceType>();
            _resourceTypeField = resourceTypeField; 

            //set up the barriers types combobox 
            //this will have to be read from the config file...
            BarriersDataSouces = new ObservableCollection<ResourceLayer>();
            //set up facilities type dropdown 
            ResourceLayer barrierLayer = new ResourceLayer();
            barrierLayer.Name = "Select Barrier";
            barrierLayer.DataSource = null;
            BarriersDataSouces.Add(barrierLayer);

            //Barriers - passed from the configurar
            foreach (ESRI.ArcGIS.OperationsDashboard.DataSource datasource in barriersDataSources)
            {
                barrierLayer = new ResourceLayer();
                barrierLayer.Name = datasource.Name; 
                barrierLayer.DataSource = datasource; 
                BarriersDataSouces.Add(barrierLayer);
            }

            cmbBarriers.ItemsSource = BarriersDataSouces;

            _incidentMarkerSymbol = new SimpleMarkerSymbol
            {
                Size = 20,
                Style = SimpleMarkerSymbol.SimpleMarkerStyle.Circle
            };

            //polyline barrier layer symbol
            _polylineBarrierSymbol = new client.Symbols.SimpleLineSymbol()
            {
                Color = new SolidColorBrush(Color.FromRgb(138, 43, 226)),
                Width = 5
            };

        }
        private async Task SetupRouteTask()
        {
            if (!IsOnline)
            {
                _routeTask = new LocalRouteTask(_localRoutingDatabase, _networkName);
            }
            else
            {
                _routeTask = new OnlineRouteTask(new Uri(_onlineRoutingService));
            }

            if (_routeTask != null)
                _routeParams = await _routeTask.GetDefaultParametersAsync();
        }
Exemplo n.º 53
0
 public void Initialize(string URLRouting)
 {
     routeTask = new RouteTask(URLRouting);
 }