private async void Initialize()
        {
            // Create a map with a light gray canvas basemap.
            Map sampleMap = new Map(Basemap.CreateLightGrayCanvas());

            // Assign the map to the MapView.
            MyMapView.Map = sampleMap;

            // Define the Url string for the US highways feature layer.
            string highwaysUrlString = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/1";

            // Create a service feature table from the url to the US highways feature service.
            ServiceFeatureTable highwaysServiceFeatureTable = new ServiceFeatureTable(new System.Uri(highwaysUrlString));

            // Create a feature layer from the service feature table.
            FeatureLayer highwaysFeatureLayer = new FeatureLayer(highwaysServiceFeatureTable);

            // Add the US highways feature layer to the operations layers collection of the map.
            sampleMap.OperationalLayers.Add(highwaysFeatureLayer);

            // Load the US highways feature layer - this way we can obtain it's extent.
            await highwaysFeatureLayer.LoadAsync();

            // Zoom the map view to the extent of the US highways feature layer.
            await MyMapView.SetViewpointGeometryAsync(highwaysFeatureLayer.FullExtent);

            // Help regarding the Json syntax for defining the LabelDefinition.FromJson syntax can be found here:
            // https://developers.arcgis.com/web-map-specification/objects/labelingInfo/
            // This particular JSON string will have the following characteristics:
            // (1) The 'labelExpressionInfo' defines that the label text displayed comes from the field 'rte_num1' in the
            //     feature service and will be prefaced with an "I -". Example: "I - 10", "I - 15", "I - 95", etc.
            // (2) The 'labelPlacement' will be placed above and along the highway polyline segment.
            // (3) The 'where' clause restricts the labels to be displayed that has valid (non-empty) data. Empty data
            //     for this service has a single blank space in the 'rte_num1' field.
            // (4) The 'symbol' for the labeled text will be blue with a yellow halo.
            string theJSON_String =
                @"{
                    ""labelExpressionInfo"":{""expression"":""'I - ' + $feature.rte_num1""},
                    ""labelPlacement"":""esriServerLinePlacementAboveAlong"",
                    ""where"":""$feature.rte_num1 <> ' '"",
                    ""symbol"":
                        { 
                            ""angle"":0,
                            ""backgroundColor"":[0,0,0,0],
                            ""borderLineColor"":[0,0,0,0],
                            ""borderLineSize"":0,
                            ""color"":[0,0,255,255],
                            ""font"":
                                {
                                    ""decoration"":""none"",
                                    ""size"":15,
                                    ""style"":""normal"",
                                    ""weight"":""normal""
                                },
                            ""haloColor"":[255,255,0,255],
                            ""haloSize"":1.5,
                            ""horizontalAlignment"":""center"",
                            ""kerning"":false,
                            ""type"":""esriTS"",
                            ""verticalAlignment"":""middle"",
                            ""xoffset"":0,
                            ""yoffset"":0
                        }
               }";

            // Create a label definition from the JSON string.
            LabelDefinition highwaysLabelDefinition = LabelDefinition.FromJson(theJSON_String);

            // Add the label definition to the feature layer's label definition collection.
            highwaysFeatureLayer.LabelDefinitions.Add(highwaysLabelDefinition);

            // Enable the visibility of labels to be seen.
            highwaysFeatureLayer.LabelsEnabled = true;
        }
Ejemplo n.º 2
0
        private void MapView_ExtentChanged(object sender, System.EventArgs e)
        {
            Envelope newExtent = null;

            // Get current viewpoints extent from the MapView
            var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

            if (MyMapView.WrapAround)
            {
                Geometry normalizedExtent = GeometryEngine.NormalizeCentralMeridian(viewpointExtent);
                if (normalizedExtent is Polygon)
                {
                    var normalizedPolygon = (Polygon)normalizedExtent;

                    if (normalizedPolygon.Parts.Count == 1)
                    {
                        newExtent = normalizedPolygon.Extent;
                    }
                    else
                    {
                        var newExtentBuilder = new EnvelopeBuilder(MyMapView.SpatialReference);

                        foreach (var p in normalizedPolygon.Parts[0].GetPoints())
                        {
                            if (Geometry.IsNullOrEmpty(newExtent) || p.X < newExtent.XMin || double.IsNaN(newExtent.XMin))
                            {
                                newExtentBuilder.XMin = p.X;
                            }
                            if (Geometry.IsNullOrEmpty(newExtent) || p.Y < newExtent.YMin || double.IsNaN(newExtent.YMin))
                            {
                                newExtentBuilder.YMin = p.Y;
                            }
                        }

                        foreach (var p in normalizedPolygon.Parts[1].GetPoints())
                        {
                            if (Geometry.IsNullOrEmpty(newExtent) || p.X > newExtent.XMax || double.IsNaN(newExtent.XMax))
                            {
                                newExtentBuilder.XMax = p.X;
                            }
                            if (Geometry.IsNullOrEmpty(newExtent) || p.Y > newExtent.YMax || double.IsNaN(newExtent.YMax))
                            {
                                newExtentBuilder.YMax = p.Y;
                            }
                        }
                        newExtent = newExtentBuilder.ToGeometry();
                    }
                }
                else if (normalizedExtent is Envelope)
                {
                    newExtent = normalizedExtent as Envelope;
                }
            }
            else
            {
                newExtent = viewpointExtent;
            }

            MinXNormalized.Text = newExtent.XMin.ToString("0.000");
            MinYNormalized.Text = newExtent.YMin.ToString("0.000");
            MaxXNormalized.Text = newExtent.XMax.ToString("0.000");
            MaxYNormalized.Text = newExtent.YMax.ToString("0.000");

            MinXAbsolute.Text = viewpointExtent.XMin.ToString("0.000");
            MinYAbsolute.Text = viewpointExtent.YMin.ToString("0.000");
            MaxXAbsolute.Text = viewpointExtent.XMax.ToString("0.000");
            MaxYAbsolute.Text = viewpointExtent.YMax.ToString("0.000");
        }
Ejemplo n.º 3
0
        private async void LoadLayers_Clicked(object sender, RoutedEventArgs e)
        {
            // Skip if nothing to add.
            if (WfsLayerList.SelectedIndex == -1)
            {
                return;
            }

            // Show the progress bar and hide the button.
            LoadingProgressBar.Visibility = Visibility.Visible;
            LoadLayersButton.IsEnabled    = false;

            // Clear the existing layers.
            MyMapView.Map.OperationalLayers.Clear();

            try
            {
                // Get the selected WFS layer.
                WfsLayerInfo selectedLayerInfo = (WfsLayerInfo)WfsLayerList.SelectedItems[0];

                // Create the WFS feature table.
                WfsFeatureTable table = new WfsFeatureTable(selectedLayerInfo);

                // Set the feature request mode to manual - only manual is supported at v100.5.
                // In this mode, you must manually populate the table - panning and zooming won't request features automatically.
                table.FeatureRequestMode = FeatureRequestMode.ManualCache;

                // Set the axis order based on the UI.
                if (AxisOrderSwapCheckbox.IsChecked == true)
                {
                    table.AxisOrder = OgcAxisOrder.Swap;
                }
                else
                {
                    table.AxisOrder = OgcAxisOrder.NoSwap;
                }

                // Populate the WFS table.
                await table.PopulateFromServiceAsync(new QueryParameters(), false, null);

                // Create a feature layer from the WFS table.
                FeatureLayer wfsFeatureLayer = new FeatureLayer(table);

                // Choose a renderer for the layer based on the table.
                wfsFeatureLayer.Renderer = GetRandomRendererForTable(table) ?? wfsFeatureLayer.Renderer;

                // Add the layer to the map.
                MyMapView.Map.OperationalLayers.Add(wfsFeatureLayer);

                // Zoom to the extent of the selected layer.
                await MyMapView.SetViewpointGeometryAsync(selectedLayerInfo.Extent, 50);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString(), "Failed to load layer.");
                Debug.WriteLine(exception);
            }
            finally
            {
                // Hide the progress bar and enable button.
                LoadingProgressBar.Visibility = Visibility.Collapsed;
                LoadLayersButton.IsEnabled    = true;
            }
        }
Ejemplo n.º 4
0
        // Event handler to get information entered by the user and save the map
        private async void SaveMapAsync(object sender, SaveMapEventArgs e)
        {
            // Get the current map
            Map myMap = MyMapView.Map;

            try
            {
                // Show the progress bar so the user knows work is happening
                SaveMapProgressBar.IsVisible = true;

                // Make sure the user is logged in to ArcGIS Online
                Credential cred = await EnsureLoggedInAsync();

                AuthenticationManager.Current.AddCredential(cred);

                // Get information entered by the user for the new portal item properties
                string   title       = e.MapTitle;
                string   description = e.MapDescription;
                string[] tags        = e.Tags;

                // Apply the current extent as the map's initial extent
                myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // Export the current map view for the item's thumbnail
                RuntimeImage thumbnailImage = await MyMapView.ExportImageAsync();

                // See if the map has already been saved (has an associated portal item)
                if (myMap.Item == null)
                {
                    // Get the ArcGIS Online portal (will use credential from login above)
                    ArcGISPortal agsOnline = await ArcGISPortal.CreateAsync(new Uri(ArcGISOnlineUrl));

                    // Save the current state of the map as a portal item in the user's default folder
                    await myMap.SaveAsAsync(agsOnline, null, title, description, tags, thumbnailImage);

                    // Report a successful save
                    await((Page)Parent).DisplayAlert("Map Saved", "Saved '" + title + "' to ArcGIS Online!", "OK");
                }
                else
                {
                    // This is not the initial save, call SaveAsync to save changes to the existing portal item
                    await myMap.SaveAsync();

                    // Get the file stream from the new thumbnail image
                    Stream imageStream = await thumbnailImage.GetEncodedBufferAsync();

                    // Update the item thumbnail
                    ((PortalItem)myMap.Item).SetThumbnailWithImage(imageStream);
                    await myMap.SaveAsync();

                    // Report update was successful
                    await((Page)Parent).DisplayAlert("Updates Saved", "Saved changes to '" + myMap.Item.Title + "'", "OK");
                }
            }
            catch (Exception ex)
            {
                // Show the exception message
                await((Page)Parent).DisplayAlert("Unable to save map", ex.Message, "OK");
            }
            finally
            {
                // Hide the progress bar
                SaveMapProgressBar.IsVisible = false;
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Method to handle hiding the callout, should be called by all UI event handlers
 /// </summary>
 private void UserInteracted()
 {
     // Hide the callout
     MyMapView.DismissCallout();
 }
Ejemplo n.º 6
0
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Clean up any previous outputs in the temp directory.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the progress indicator while the job is running.
                busyIndicator.IsVisible = true;

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(MyMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    await Application.Current.MainPage.DisplayAlert("Alert", "Generate offline map package failed.", "OK");

                    busyIndicator.IsVisible = false;
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    string errorText = errorBuilder.ToString();
                    await Application.Current.MainPage.DisplayAlert("Alert", errorText, "OK");
                }

                // Display the offline map.
                MyMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                MyMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                MyMapView.InteractionOptions.IsEnabled = true;

                // Hide the "Take map offline" button.
                takeOfflineArea.IsVisible = false;

                // Show a message that the map is offline.
                messageArea.IsVisible = true;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                await Application.Current.MainPage.DisplayAlert("Alert", "Taking map offline was canceled", "OK");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                await Application.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                busyIndicator.IsVisible = false;
            }
        }
Ejemplo n.º 7
0
        private async void Initialize()
        {
            try
            {
                // Add event handler for when this sample is unloaded.
                Unloaded += SampleUnloaded;

                // Create the map view.
                MyMapView.Map = new Map(Basemap.CreateNavigationVector());

                // Create the route task, using the online routing service.
                RouteTask routeTask = await RouteTask.CreateAsync(_routingUri);

                // Get the default route parameters.
                RouteParameters routeParams = await routeTask.CreateDefaultParametersAsync();

                // Explicitly set values for parameters.
                routeParams.ReturnDirections       = true;
                routeParams.ReturnStops            = true;
                routeParams.ReturnRoutes           = true;
                routeParams.OutputSpatialReference = SpatialReferences.Wgs84;

                // Create stops for each location.
                Stop stop1 = new Stop(_conventionCenter)
                {
                    Name = "San Diego Convention Center"
                };
                Stop stop2 = new Stop(_memorial)
                {
                    Name = "USS San Diego Memorial"
                };
                Stop stop3 = new Stop(_aerospaceMuseum)
                {
                    Name = "RH Fleet Aerospace Museum"
                };

                // Assign the stops to the route parameters.
                List <Stop> stopPoints = new List <Stop> {
                    stop1, stop2, stop3
                };
                routeParams.SetStops(stopPoints);

                // Get the route results.
                _routeResult = await routeTask.SolveRouteAsync(routeParams);

                _route = _routeResult.Routes[0];

                // Add a graphics overlay for the route graphics.
                MyMapView.GraphicsOverlays.Add(new GraphicsOverlay());

                // Add graphics for the stops.
                SimpleMarkerSymbol stopSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.OrangeRed, 20);
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_conventionCenter, stopSymbol));
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_memorial, stopSymbol));
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_aerospaceMuseum, stopSymbol));

                // Create a graphic (with a dashed line symbol) to represent the route.
                _routeAheadGraphic = new Graphic(_route.RouteGeometry)
                {
                    Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.BlueViolet, 5)
                };

                // Create a graphic (solid) to represent the route that's been traveled (initially empty).
                _routeTraveledGraphic = new Graphic {
                    Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.LightBlue, 3)
                };

                // Add the route graphics to the map view.
                MyMapView.GraphicsOverlays[0].Graphics.Add(_routeAheadGraphic);
                MyMapView.GraphicsOverlays[0].Graphics.Add(_routeTraveledGraphic);

                // Set the map viewpoint to show the entire route.
                await MyMapView.SetViewpointGeometryAsync(_route.RouteGeometry, 100);

                // Enable the navigation button.
                StartNavigationButton.IsEnabled = true;
            }
            catch (Exception e)
            {
                await new MessageDialog2(e.Message, "Error").ShowAsync();
            }
        }
Ejemplo n.º 8
0
        // Draw and densify a user defined polygon
        private async void DensifyButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DensifyButton.IsEnabled = false;
                resultsPanel.Visibility = Visibility.Collapsed;
                _inputOverlay.Graphics.Clear();
                _resultsOverlay.Graphics.Clear();

                DrawShape drawShape;

                drawShape = (RadioPolyline.IsChecked.Value) ? drawShape = DrawShape.Polyline : drawShape = DrawShape.Polygon;

                // Use polyline as default
                Symbol symbolToUse = _lineSymbol;
                if (drawShape == DrawShape.Polygon)
                {
                    symbolToUse = _fillSymbol;
                }

                var original = await MyMapView.Editor.RequestShapeAsync(drawShape, symbolToUse);

                // Account for WrapAround
                var normalized = GeometryEngine.NormalizeCentralMeridian(original);

                // Add original shape vertices to input graphics layer
                var coordsOriginal = (normalized as Multipart).Parts.First().GetPoints();
                foreach (var coord in coordsOriginal)
                {
                    _inputOverlay.Graphics.Add(new Graphic(coord, _origVertexSymbol));
                }

                // Get current viewpoints extent from the MapView
                var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

                // Densify the shape
                var densify = GeometryEngine.GeodesicDensify(normalized, viewpointExtent.Width / 100, LinearUnits.Meters);

                if (densify.GeometryType == GeometryType.Polygon)
                {
                    _inputOverlay.Graphics.Add(new Graphic(densify, _fillSymbol));
                }
                else
                {
                    _inputOverlay.Graphics.Add(new Graphic(densify, _lineSymbol));
                }

                // Add new vertices to result graphics layer
                var coordsDensify = (densify as Multipart).Parts.First().GetPoints();
                foreach (var coord in coordsDensify)
                {
                    _resultsOverlay.Graphics.Add(new Graphic(coord, _newVertexSymbol));
                }

                // Results
                var results = new List <Tuple <string, object> >()
                {
                    new Tuple <string, object>("Length", GeometryEngine.GeodesicLength(densify) * METERS_TO_MILES),
                    new Tuple <string, object>("Area",
                                               (normalized is Polygon) ? (GeometryEngine.GeodesicArea(densify) * SQUARE_METERS_TO_MILES).ToString("0.000") : "N/A"),
                    new Tuple <string, object>("Vertices Before", coordsOriginal.Count()),
                    new Tuple <string, object>("Vertices After", coordsDensify.Count())
                };

                resultsListView.ItemsSource = results;
                resultsPanel.Visibility     = Visibility.Visible;
            }
            catch (TaskCanceledException) { }
            catch (Exception ex)
            {
                var _x = new MessageDialog("Densify Error: " + ex.Message, "Sample Error").ShowAsync();
            }
            finally
            {
                DensifyButton.IsEnabled = true;
            }
        }
        private async void Initialize()
        {
            try
            {
                // Construct the map and set the MapView.Map property.
                MyMapView.Map = new Map(Basemap.CreateLightGrayCanvasVector());

                // Add a graphics overlay to MyMapView. (Will be used later to display routes)
                MyMapView.GraphicsOverlays.Add(new GraphicsOverlay());

                // Create a ClosestFacilityTask using the San Diego Uri.
                _task = await ClosestFacilityTask.CreateAsync(_closestFacilityUri);

                // Create a symbol for displaying facilities.
                PictureMarkerSymbol facilitySymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png"))
                {
                    Height = 30,
                    Width  = 30
                };

                // Incident symbol.
                PictureMarkerSymbol incidentSymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png"))
                {
                    Height = 30,
                    Width  = 30
                };

                // Create a list of line symbols to show unique routes. Different colors help make different routes visually distinguishable.
                _routeSymbols = new List <SimpleLineSymbol>()
                {
                    new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 25, 45, 85), 5.0f),
                    new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 35, 65, 120), 5.0f),
                    new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 55, 100, 190), 5.0f),
                    new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.FromArgb(125, 75, 140, 255), 5.0f)
                };

                // Create a table for facilities using the FeatureServer.
                _facilityTable = new ServiceFeatureTable(_facilityUri);

                // Create a feature layer from the table.
                _facilityLayer = new FeatureLayer(_facilityTable)
                {
                    Renderer = new SimpleRenderer(facilitySymbol)
                };

                // Create a table for facilities using the FeatureServer.
                _incidentTable = new ServiceFeatureTable(_incidentUri);

                // Create a feature layer from the table.
                _incidentLayer = new FeatureLayer(_incidentTable)
                {
                    Renderer = new SimpleRenderer(incidentSymbol)
                };

                // Add the layers to the map.
                MyMapView.Map.OperationalLayers.Add(_facilityLayer);
                MyMapView.Map.OperationalLayers.Add(_incidentLayer);

                // Wait for both layers to load.
                await _facilityLayer.LoadAsync();

                await _incidentLayer.LoadAsync();

                // Zoom to the combined extent of both layers.
                Envelope fullExtent = GeometryEngine.CombineExtents(_facilityLayer.FullExtent, _incidentLayer.FullExtent);
                await MyMapView.SetViewpointGeometryAsync(fullExtent, 50);

                // Enable the solve button.
                SolveRoutesButton.IsEnabled = true;
            }
            catch (Exception exception)
            {
                await Application.Current.MainPage.DisplayAlert("Error", "An exception has occurred.\n" + exception.Message, "OK");
            }
        }
Ejemplo n.º 10
0
        private async void OnGeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                IsBusy.Visibility = Visibility.Visible;
                Status.Text       = "Identifying trace locations...";

                // Identify the feature to be used.
                IEnumerable <IdentifyLayerResult> identifyResult = await MyMapView.IdentifyLayersAsync(e.Position, 10.0, false);

                ArcGISFeature feature = identifyResult?.FirstOrDefault()?.GeoElements?.FirstOrDefault() as ArcGISFeature;
                if (feature == null)
                {
                    return;
                }

                // Create element from the identified feature.
                UtilityElement element = _utilityNetwork.CreateElement(feature);

                if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Junction)
                {
                    // Select terminal for junction feature.
                    IEnumerable <UtilityTerminal> terminals = element.AssetType.TerminalConfiguration?.Terminals;
                    if (terminals?.Count() > 1)
                    {
                        element.Terminal = await GetTerminalAsync(terminals);
                    }
                    Status.Text = $"Terminal: {element.Terminal?.Name ?? "default"}";
                }
                else if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Edge)
                {
                    // Compute how far tapped location is along the edge feature.
                    if (feature.Geometry is Polyline line)
                    {
                        line = GeometryEngine.RemoveZ(line) as Polyline;
                        double fraction = GeometryEngine.FractionAlong(line, e.Location, -1);
                        if (double.IsNaN(fraction))
                        {
                            return;
                        }
                        element.FractionAlongEdge = fraction;
                        Status.Text = $"Fraction along edge: {element.FractionAlongEdge}";
                    }
                }

                // Check whether starting location or barrier is added to update the right collection and symbology.
                Symbol symbol = null;
                if (IsAddingStartingLocations.IsChecked.Value == true)
                {
                    _startingLocations.Add(element);
                    symbol = _startingPointSymbol;
                }
                else
                {
                    _barriers.Add(element);
                    symbol = _barrierPointSymbol;
                }

                // Add a graphic for the new utility element.
                Graphic traceLocationGraphic = new Graphic(feature.Geometry as MapPoint ?? e.Location, symbol);
                MyMapView.GraphicsOverlays.FirstOrDefault()?.Graphics.Add(traceLocationGraphic);
            }
            catch (Exception ex)
            {
                Status.Text = "Identifying locations failed.";
                await new MessageDialog2(ex.Message, ex.GetType().Name).ShowAsync();
            }
            finally
            {
                if (Status.Text.Equals("Identifying trace locations..."))
                {
                    Status.Text = "Could not identify location.";
                }
                IsBusy.Visibility = Visibility.Collapsed;
            }
        }
Ejemplo n.º 11
0
        private void Initialize()
        {
            // Configure the basemap
            MyMapView.Map = new Map(Basemap.CreateTopographic());

            // Create the graphics overlay
            _graphicsOverlay = new GraphicsOverlay();

            // Add the overlay to the MapView
            MyMapView.GraphicsOverlays.Add(_graphicsOverlay);

            // Set the selection color
            MyMapView.SelectionProperties.Color = Color.Yellow;

            // Create the point collection that defines the polygon
            PointCollection polygonPoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-5991501.677830, 5599295.131468),
                new MapPoint(-6928550.398185, 2087936.739807),
                new MapPoint(-3149463.800709, 1840803.011362),
                new MapPoint(-1563689.043184, 3714900.452072),
                new MapPoint(-3180355.516764, 5619889.608838)
            };

            // Create the polygon
            Polygon polygonGeometry = new Polygon(polygonPoints);

            // Define the symbology of the polygon
            SimpleLineSymbol polygonOutlineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.Green, 2);
            SimpleFillSymbol polygonFillSymbol    = new SimpleFillSymbol(SimpleFillSymbolStyle.ForwardDiagonal, System.Drawing.Color.Green, polygonOutlineSymbol);

            // Create the polygon graphic and add it to the graphics overlay
            _polygonGraphic = new Graphic(polygonGeometry, polygonFillSymbol);
            _graphicsOverlay.Graphics.Add(_polygonGraphic);

            // Create the point collection that defines the polyline
            PointCollection polylinePoints = new PointCollection(SpatialReferences.WebMercator)
            {
                new MapPoint(-4354240.726880, -609939.795721),
                new MapPoint(-3427489.245210, 2139422.933233),
                new MapPoint(-2109442.693501, 4301843.057130),
                new MapPoint(-1810822.771630, 7205664.366363)
            };

            // Create the polyline
            Polyline polylineGeometry = new Polyline(polylinePoints);

            // Create the polyline graphic and add it to the graphics overlay
            _polylineGraphic = new Graphic(polylineGeometry, new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Red, 4));
            _graphicsOverlay.Graphics.Add(_polylineGraphic);

            // Create the point geometry that defines the point graphic
            MapPoint pointGeometry = new MapPoint(-4487263.495911, 3699176.480377, SpatialReferences.WebMercator);

            // Define the symbology for the point
            SimpleMarkerSymbol locationMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Blue, 10);

            // Create the point graphic and add it to the graphics overlay
            _pointGraphic = new Graphic(pointGeometry, locationMarker);
            _graphicsOverlay.Graphics.Add(_pointGraphic);

            // Listen for taps; the spatial relationships will be updated in the handler
            MyMapView.GeoViewTapped += MapViewTapped;

            // Set the viewpoint to center on the point
            MyMapView.SetViewpointCenterAsync(pointGeometry, 200000000);
        }
Ejemplo n.º 12
0
        private async void Initialize()
        {
            // Create a map with a light gray canvas basemap.
            Map sampleMap = new Map(Basemap.CreateLightGrayCanvas());

            // Assign the map to the MapView.
            MyMapView.Map = sampleMap;

            // Define the URL string for the feature layer.
            string layerUrl = "https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_Congressional_Districts_analysis/FeatureServer/0";

            // Create a service feature table from the URL.
            ServiceFeatureTable featureTable = new ServiceFeatureTable(new System.Uri(layerUrl));

            // Create a feature layer from the service feature table.
            FeatureLayer districtFeatureLabel = new FeatureLayer(featureTable);

            // Add the feature layer to the operations layers collection of the map.
            sampleMap.OperationalLayers.Add(districtFeatureLabel);

            // Load the feature layer - this way we can obtain it's extent.
            await districtFeatureLabel.LoadAsync();

            // Zoom the map view to the extent of the feature layer.
            await MyMapView.SetViewpointCenterAsync(new MapPoint(-10846309.950860, 4683272.219411, SpatialReferences.WebMercator), 20000000);

            // Help regarding the Json syntax for defining the LabelDefinition.FromJson syntax can be found here:
            // https://developers.arcgis.com/web-map-specification/objects/labelingInfo/
            // This particular JSON string will have the following characteristics:
            string redLabelJson =
                @"{
                    ""labelExpressionInfo"":{""expression"":""$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict' + $feature.CDFIPS""},
                    ""labelPlacement"":""esriServerPolygonPlacementAlwaysHorizontal"",
                    ""where"":""PARTY = 'Republican'"",
                    ""symbol"":
                        { 
                            ""angle"":0,
                            ""backgroundColor"":[0,0,0,0],
                            ""borderLineColor"":[0,0,0,0],
                            ""borderLineSize"":0,
                            ""color"":[255,0,0,255],
                            ""font"":
                                {
                                    ""decoration"":""none"",
                                    ""size"":10,
                                    ""style"":""normal"",
                                    ""weight"":""normal""
                                },
                            ""haloColor"":[255,255,255,255],
                            ""haloSize"":2,
                            ""horizontalAlignment"":""center"",
                            ""kerning"":false,
                            ""type"":""esriTS"",
                            ""verticalAlignment"":""middle"",
                            ""xoffset"":0,
                            ""yoffset"":0
                        }
               }";

            string blueLabelJson =
                @"{
                    ""labelExpressionInfo"":{""expression"":""$feature.NAME + ' (' + left($feature.PARTY,1) + ')\\nDistrict' + $feature.CDFIPS""},
                    ""labelPlacement"":""esriServerPolygonPlacementAlwaysHorizontal"",
                    ""where"":""PARTY = 'Democrat'"",
                    ""symbol"":
                        { 
                            ""angle"":0,
                            ""backgroundColor"":[0,0,0,0],
                            ""borderLineColor"":[0,0,0,0],
                            ""borderLineSize"":0,
                            ""color"":[0,0,255,255],
                            ""font"":
                                {
                                    ""decoration"":""none"",
                                    ""size"":10,
                                    ""style"":""normal"",
                                    ""weight"":""normal""
                                },
                            ""haloColor"":[255,255,255,255],
                            ""haloSize"":2,
                            ""horizontalAlignment"":""center"",
                            ""kerning"":false,
                            ""type"":""esriTS"",
                            ""verticalAlignment"":""middle"",
                            ""xoffset"":0,
                            ""yoffset"":0
                        }
               }";

            // Create a label definition from the JSON string.
            LabelDefinition redLabelDefinition  = LabelDefinition.FromJson(redLabelJson);
            LabelDefinition blueLabelDefinition = LabelDefinition.FromJson(blueLabelJson);

            // Add the label definition to the feature layer's label definition collection.
            districtFeatureLabel.LabelDefinitions.Add(redLabelDefinition);
            districtFeatureLabel.LabelDefinitions.Add(blueLabelDefinition);

            // Enable the visibility of labels to be seen.
            districtFeatureLabel.LabelsEnabled = true;
        }
        private async void MyMapViewOnGeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Clear any existing feature selection and results list
                _myFeatureLayer.ClearSelection();
                MyResultsView.ItemsSource = null;

                // Identify the tapped feature
                IdentifyLayerResult results = await MyMapView.IdentifyLayerAsync(_myFeatureLayer, e.Position, 10, false);

                // Return if there are no results
                if (results.GeoElements.Count < 1)
                {
                    return;
                }

                Status.Text = "Loading...";

                // Get the first result
                ArcGISFeature myFeature = (ArcGISFeature)results.GeoElements.First();

                // Select the feature
                _myFeatureLayer.SelectFeature(myFeature);

                // Get the feature table for the feature
                ArcGISFeatureTable myFeatureTable = (ArcGISFeatureTable)myFeature.FeatureTable;

                // Query related features
                IReadOnlyList <RelatedFeatureQueryResult> relatedFeaturesResult = await myFeatureTable.QueryRelatedFeaturesAsync(myFeature);

                // Create a list to hold the formatted results of the query
                List <String> queryResultsForUi = new List <string>();

                // For each query result
                foreach (RelatedFeatureQueryResult result in relatedFeaturesResult)
                {
                    // And then for each feature in the result
                    foreach (Feature resultFeature in result)
                    {
                        // Get a reference to the feature's table
                        ArcGISFeatureTable relatedTable = (ArcGISFeatureTable)resultFeature.FeatureTable;

                        // Get the display field name - this is the name of the field that is intended for display
                        string displayFieldName = relatedTable.LayerInfo.DisplayFieldName;

                        // Get the name of the feature's table
                        string tableName = relatedTable.TableName;

                        // Get the display name for the feature
                        string featureDisplayname = resultFeature.Attributes[displayFieldName].ToString();

                        // Create a formatted result string
                        string formattedResult = $"{tableName} - {featureDisplayname}";

                        // Add the result to the list
                        queryResultsForUi.Add(formattedResult);
                    }
                }

                // Update the UI with the result list
                MyResultsView.ItemsSource = queryResultsForUi;
                Status.Text = "Tap a park (green) to see related features.";
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
Ejemplo n.º 14
0
        public ItemDetailPage(Item poiItem)
        {
            InitializeComponent();

            // Create a view model with the current item (place category)
            this._viewModel = new ItemDetailViewModel(poiItem);
            BindingContext  = _viewModel;

            // Create a symbol for the places (red circle), use it to create a renderer
            SimpleMarkerSymbol sym   = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 10);
            SimpleRenderer     rndrr = new SimpleRenderer(sym);

            // Create a graphics overlay to show the places, add it to the map view
            _placesGraphicsOverlay = new GraphicsOverlay
            {
                Renderer = rndrr
            };
            MyMapView.GraphicsOverlays.Add(_placesGraphicsOverlay);

            // Add the route graphics overlay
            _routeGraphicsOverlay = new GraphicsOverlay();
            MyMapView.GraphicsOverlays.Add(_routeGraphicsOverlay);

            // Zoom to the device location (Xamarin.Essentials)
            MyMapView.SpatialReferenceChanged += async(a, b) =>
            {
                GeolocationRequest locationRequest = new GeolocationRequest(GeolocationAccuracy.Default);
                Location           myLocation      = await Geolocation.GetLocationAsync(locationRequest);

                MapPoint deviceLocation = new MapPoint(myLocation.Longitude, myLocation.Latitude, SpatialReferences.Wgs84);
                await MyMapView.SetViewpointCenterAsync(deviceLocation, 24000);
            };

            // Use MapView.LocationDisplay to listen for location updates and for automatic display
            // When the location updates, store the last known location
            //MyMapView.LocationDisplay.IsEnabled = true;
            //MyMapView.LocationDisplay.LocationChanged += async(s, locArgs) =>
            //{
            //    _deviceLocation = locArgs.Position;
            //    await ShowPlaces();
            //};
            #region
            // Why is LocationDisplay null?
            //  Search GeoNet: https://community.esri.com/search.jspa?place=%2Fplaces%2F191827&q=locationdisplay
            //     -Answer from Zack (https://community.esri.com/message/875283-1006-locationdisplay-always-null)
            MyMapView.PropertyChanged += (o, e) =>
            {
                if (e.PropertyName == nameof(MyMapView.LocationDisplay) && MyMapView.LocationDisplay != null)
                {
                    // Enable your location display.
                    MyMapView.LocationDisplay.IsEnabled        = true;
                    MyMapView.LocationDisplay.LocationChanged += async(s, locArgs) =>
                    {
                        _deviceLocation = locArgs.Position;
                        await ShowPlaces();
                    };
                }
            };
            #endregion

            // TODO: Uncomment to test compass control by setting map rotation
            //await MyMapView.SetViewpointRotationAsync(90);
        }
        private async void QuerySublayers_Click(object sender, RoutedEventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

            // If the population value entered is not numeric, warn the user and exit.
            double populationNumber = 0.0;

            if (!double.TryParse(PopulationTextBox.Text.Trim(), out populationNumber))
            {
                MessageDialog dialog = new MessageDialog("The population value must be numeric.", "Query error");
                await dialog.ShowAsync();

                return;
            }

            // Get the USA map image layer (the first and only operational layer in the map).
            ArcGISMapImageLayer usaMapImageLayer = MyMapView.Map.OperationalLayers[0] as ArcGISMapImageLayer;

            // Use a utility method on the map image layer to load all the sublayers and tables.
            await usaMapImageLayer.LoadTablesAndLayersAsync();

            // Get the sublayers of interest (skip 'Highways' since it doesn't have the POP2000 field).
            ArcGISMapImageSublayer citiesSublayer   = usaMapImageLayer.Sublayers[0] as ArcGISMapImageSublayer;
            ArcGISMapImageSublayer statesSublayer   = usaMapImageLayer.Sublayers[2] as ArcGISMapImageSublayer;
            ArcGISMapImageSublayer countiesSublayer = usaMapImageLayer.Sublayers[3] as ArcGISMapImageSublayer;

            // Get the service feature table for each of the sublayers.
            ServiceFeatureTable citiesTable   = citiesSublayer.Table;
            ServiceFeatureTable statesTable   = statesSublayer.Table;
            ServiceFeatureTable countiesTable = countiesSublayer.Table;

            // Create the query parameters that will find features in the current extent with a population greater than the value entered.
            QueryParameters populationQuery = new QueryParameters
            {
                WhereClause = "POP2000 > " + PopulationTextBox.Text,
                Geometry    = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry
            };

            // Query each of the sublayers with the query parameters.
            FeatureQueryResult citiesQueryResult = await citiesTable.QueryFeaturesAsync(populationQuery);

            FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery);

            FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery);

            // Display the selected cities in the graphics overlay.
            SimpleMarkerSymbol citySymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 16);

            foreach (Feature city in citiesQueryResult)
            {
                Graphic cityGraphic = new Graphic(city.Geometry, citySymbol);

                _selectedFeaturesOverlay.Graphics.Add(cityGraphic);
            }

            // Display the selected counties in the graphics overlay.
            SimpleLineSymbol countyLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.Cyan, 2);
            SimpleFillSymbol countySymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, System.Drawing.Color.Cyan, countyLineSymbol);

            foreach (Feature county in countiesQueryResult)
            {
                Graphic countyGraphic = new Graphic(county.Geometry, countySymbol);

                _selectedFeaturesOverlay.Graphics.Add(countyGraphic);
            }

            // Display the selected states in the graphics overlay.
            SimpleLineSymbol stateLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.DarkCyan, 6);
            SimpleFillSymbol stateSymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, System.Drawing.Color.Cyan, stateLineSymbol);

            foreach (Feature state in statesQueryResult)
            {
                Graphic stateGraphic = new Graphic(state.Geometry, stateSymbol);

                _selectedFeaturesOverlay.Graphics.Add(stateGraphic);
            }
        }
Ejemplo n.º 16
0
        private async void OnAnalyzeHotspotsClicked(object sender, RoutedEventArgs e)
        {
            // Clear any existing results
            MyMapView.Map.OperationalLayers.Clear();

            // Show the busyOverlay indication
            ShowBusyOverlay();

            // Get the 'from' and 'to' dates from the date pickers for the geoprocessing analysis
            var myFromDate = FromDate.Date;
            var myToDate   = ToDate.Date;

            // The end date must be at least one day after the start date
            if (myToDate <= myFromDate.AddDays(1))
            {
                // Show error message
                var message = new MessageDialog("Please select valid time range. There has to be at least one day in between To and From dates.",
                                                "Invalid date range");
                await message.ShowAsync();

                // Remove the busyOverlay
                ShowBusyOverlay(false);
                return;
            }

            // Create the parameters that are passed to the used geoprocessing task
            GeoprocessingParameters myHotspotParameters = new GeoprocessingParameters(GeoprocessingExecutionType.AsynchronousSubmit);

            // Construct the date query
            var myQueryString = string.Format("(\"DATE\" > date '{0} 00:00:00' AND \"DATE\" < date '{1} 00:00:00')",
                                              myFromDate.ToString("yyyy-MM-dd"),
                                              myToDate.ToString("yyyy-MM-dd"));

            // Add the query that contains the date range used in the analysis
            myHotspotParameters.Inputs.Add("Query", new GeoprocessingString(myQueryString));

            // Create job that handles the communication between the application and the geoprocessing task
            _hotspotJob = _hotspotTask.CreateJob(myHotspotParameters);
            try
            {
                // Execute the geoprocessing analysis and wait for the results
                GeoprocessingResult myAnalysisResult = await _hotspotJob.GetResultAsync();

                // Add results to a map using map server from a geoprocessing task
                // Load to get access to full extent
                await myAnalysisResult.MapImageLayer.LoadAsync();

                // Add the analysis layer to the map view
                MyMapView.Map.OperationalLayers.Add(myAnalysisResult.MapImageLayer);

                // Zoom to the results
                await MyMapView.SetViewpointAsync(new Viewpoint(myAnalysisResult.MapImageLayer.FullExtent));
            }
            catch (TaskCanceledException)
            {
                // This is thrown if the task is canceled. Ignore.
            }
            catch (Exception ex)
            {
                // Display error messages if the geoprocessing task fails
                if (_hotspotJob.Status == JobStatus.Failed && _hotspotJob.Error != null)
                {
                    var message = new MessageDialog("Executing geoprocessing failed. " + _hotspotJob.Error.Message, "Geoprocessing error");
                    await message.ShowAsync();
                }
                else
                {
                    var message = new MessageDialog("An error occurred. " + ex.ToString(), "Sample error");
                    await message.ShowAsync();
                }
            }
            finally
            {
                // Remove the busyOverlay
                ShowBusyOverlay(false);
            }
        }
Ejemplo n.º 17
0
        private async void Initialize()
        {
            try
            {
                // Create the map view.
                MyMapView.Map = new Map(BasemapStyle.ArcGISStreets);

                // Create the route task, using the routing service.
                _routeTask = await RouteTask.CreateAsync(_networkGeodatabasePath, "Streets_ND");

                // Get the default route parameters.
                _routeParams = await _routeTask.CreateDefaultParametersAsync();

                // Explicitly set values for parameters.
                _routeParams.ReturnDirections       = true;
                _routeParams.ReturnStops            = true;
                _routeParams.ReturnRoutes           = true;
                _routeParams.OutputSpatialReference = SpatialReferences.Wgs84;

                // Create stops for each location.
                Stop stop1 = new Stop(_conventionCenter)
                {
                    Name = "San Diego Convention Center"
                };
                Stop stop2 = new Stop(_aerospaceMuseum)
                {
                    Name = "RH Fleet Aerospace Museum"
                };

                // Assign the stops to the route parameters.
                List <Stop> stopPoints = new List <Stop> {
                    stop1, stop2
                };
                _routeParams.SetStops(stopPoints);

                // Get the route results.
                _routeResult = await _routeTask.SolveRouteAsync(_routeParams);

                _route = _routeResult.Routes[0];

                // Add a graphics overlay for the route graphics.
                MyMapView.GraphicsOverlays.Add(new GraphicsOverlay());

                // Add graphics for the stops.
                SimpleMarkerSymbol stopSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Diamond, Color.OrangeRed, 20);
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_conventionCenter, stopSymbol));
                MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(_aerospaceMuseum, stopSymbol));

                // Create a graphic (with a dashed line symbol) to represent the route.
                _routeAheadGraphic = new Graphic(_route.RouteGeometry)
                {
                    Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.BlueViolet, 5)
                };

                // Create a graphic (solid) to represent the route that's been traveled (initially empty).
                _routeTraveledGraphic = new Graphic {
                    Symbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.LightBlue, 3)
                };

                // Add the route graphics to the map view.
                MyMapView.GraphicsOverlays[0].Graphics.Add(_routeAheadGraphic);
                MyMapView.GraphicsOverlays[0].Graphics.Add(_routeTraveledGraphic);

                // Set the map viewpoint to show the entire route.
                await MyMapView.SetViewpointGeometryAsync(_route.RouteGeometry, 100);

                // Enable the navigation button.
                StartNavigationButton.IsEnabled = true;
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.Message, "OK");
            }
        }
        // Calculate the route
        private async void MyMapView_MapViewDoubleTapped(object sender, Esri.ArcGISRuntime.Controls.MapViewInputEventArgs e)
        {
            if (_stopsOverlay.Graphics.Count() < 2)
            {
                return;
            }

            try
            {
                e.Handled = true;

                panelResults.Visibility = Visibility.Collapsed;
                progress.Visibility     = Visibility.Visible;

                RouteParameters routeParams = await _routeTask.GetDefaultParametersAsync();

                routeParams.OutSpatialReference  = MyMapView.SpatialReference;
                routeParams.ReturnDirections     = true;
                routeParams.DirectionsLengthUnit = LinearUnits.Miles;
                routeParams.DirectionsLanguage   = new CultureInfo("en-Us");               // CultureInfo.CurrentCulture;
                routeParams.SetStops(_stopsOverlay.Graphics);

                var routeResult = await _routeTask.SolveAsync(routeParams);

                if (routeResult == null || routeResult.Routes == null || routeResult.Routes.Count() == 0)
                {
                    throw new Exception("No route could be calculated");
                }

                var route = routeResult.Routes.First();
                _routesOverlay.Graphics.Add(new Graphic(route.RouteFeature.Geometry));

                _directionsOverlay.GraphicsSource = route.RouteDirections.Select(rd => GraphicFromRouteDirection(rd));

                var totalTime   = route.RouteDirections.Select(rd => rd.Time).Aggregate(TimeSpan.Zero, (p, v) => p.Add(v));
                var totalLength = route.RouteDirections.Select(rd => rd.GetLength(LinearUnits.Miles)).Sum();
                txtRouteTotals.Text = string.Format("Time: {0:h':'mm':'ss} / Length: {1:0.00} mi", totalTime, totalLength);

                await MyMapView.SetViewAsync(route.RouteFeature.Geometry.Extent.Expand(1.25));
            }
            catch (AggregateException ex)
            {
                var message             = ex.Message;
                var innermostExceptions = ex.Flatten().InnerExceptions;
                if (innermostExceptions != null && innermostExceptions.Count > 0)
                {
                    message = innermostExceptions[0].Message;
                }

                var _x = new MessageDialog(message, "Sample Error").ShowAsync();
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
            finally
            {
                progress.Visibility = Visibility.Collapsed;
                if (_directionsOverlay.Graphics.Count() > 0)
                {
                    panelResults.Visibility = Visibility.Visible;
                }
            }
        }
        private async void TakeMapOfflineButton_Click(object sender, RoutedEventArgs e)
        {
            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), @"NapervilleWaterNetwork" + num.ToString());
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the progress indicator while the job is running.
                BusyIndicator.Visibility = Visibility.Visible;

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(MyMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                #region overrides

                // Generate parameter overrides for more in-depth control of the job.
                GenerateOfflineMapParameterOverrides overrides = await takeMapOfflineTask.CreateGenerateOfflineMapParameterOverridesAsync(parameters);

                // Configure the overrides using helper methods.
                ConfigureTileLayerOverrides(overrides);
                ConfigureLayerExclusion(overrides);
                CropWaterPipes(overrides);
                ApplyFeatureFilter(overrides);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath, overrides);

                #endregion overrides

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    MessageBox.Show("Generate offline map package failed.", "Job status");
                    BusyIndicator.Visibility = Visibility.Collapsed;
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    string errorText = errorBuilder.ToString();
                    MessageBox.Show(errorText, "Layer errors");
                }

                // Display the offline map.
                MyMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                MyMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                MyMapView.InteractionOptions.IsEnabled = true;

                // Hide the "Take map offline" button.
                takeOfflineArea.Visibility = Visibility.Collapsed;

                // Show a message that the map is offline.
                MessageArea.Visibility = Visibility.Visible;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                MessageBox.Show("Taking map offline was canceled");
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                MessageBox.Show(ex.Message, "Offline map error");
            }
            finally
            {
                // Hide the activity indicator when the job is done.
                BusyIndicator.Visibility = Visibility.Collapsed;
            }
        }
        // Draw and densify a user defined polygon
        private async void DensifyButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                resultsPanel.Visibility = Visibility.Collapsed;
                _inputOverlay.Graphics.Clear();
                _resultsOverlay.Graphics.Clear();

                // Request polygon or polyline from the user
                DrawShape drawShape = (DrawShape)comboShapeType.SelectedValue;

                // Use polyline as default
                Symbol symbolToUse = _lineSymbol;
                if (drawShape == DrawShape.Polygon)
                {
                    symbolToUse = _fillSymbol;
                }

                var original = await MyMapView.Editor.RequestShapeAsync(drawShape, symbolToUse);

                // Account for WrapAround
                var normalized = GeometryEngine.NormalizeCentralMeridian(original);

                // Add original shape vertices to input graphics layer
                var coordsOriginal = (normalized as Multipart).Parts.First().GetPoints();
                foreach (var mapPoint in coordsOriginal)
                {
                    _inputOverlay.Graphics.Add(new Graphic(mapPoint, _origVertexSymbol));
                }

                // Get current viewpoints extent from the MapView
                var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

                // Densify the shape
                var densify = GeometryEngine.GeodesicDensify(normalized, viewpointExtent.Width / 100, LinearUnits.Meters);

                if (densify.GeometryType == GeometryType.Polygon)
                {
                    _inputOverlay.Graphics.Add(new Graphic(densify, _fillSymbol));
                }
                else
                {
                    _inputOverlay.Graphics.Add(new Graphic(densify, _lineSymbol));
                }

                // Add new vertices to result graphics layer
                var coordsDensify = (densify as Multipart).Parts.First().GetPoints();
                foreach (var mapPoint in coordsDensify)
                {
                    _resultsOverlay.Graphics.Add(new Graphic(mapPoint, _newVertexSymbol));
                }

                // Results
                Dictionary <string, object> results = new Dictionary <string, object>();
                results["Length"] = GeometryEngine.GeodesicLength(densify) * METERS_TO_MILES;
                if (normalized is Polygon)
                {
                    results["Area"] = GeometryEngine.GeodesicArea(densify) * SQUARE_METERS_TO_MILES;
                }
                else
                {
                    results["Area"] = "N/A";
                }
                results["Vertices Before"] = coordsOriginal.Count();
                results["Vertices After"]  = coordsDensify.Count();

                resultsListView.ItemsSource = results;
                resultsPanel.Visibility     = Visibility.Visible;
            }
            catch (TaskCanceledException) { }
            catch (Exception ex)
            {
                MessageBox.Show("Densify Error: " + ex.Message, "Geodesic Densify Sample");
            }
        }
        private async void SaveMapClicked(object sender, RoutedEventArgs e)
        {
            try
            {
                // Show the progress bar so the user knows work is happening
                SaveProgressBar.Visibility = Visibility.Visible;

                // Get the current map
                var myMap = MyMapView.Map;

                // Apply the current extent as the map's initial extent
                myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // Get the current map view for the item thumbnail
                RuntimeImage thumbnailImg = await MyMapView.ExportImageAsync();

                // See if the map has already been saved (has an associated portal item)
                if (myMap.Item == null)
                {
                    // Get information for the new portal item
                    var title       = TitleTextBox.Text;
                    var description = DescriptionTextBox.Text;
                    var tags        = TagsTextBox.Text.Split(',');

                    // Make sure all required info was entered
                    if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description) || tags.Length == 0)
                    {
                        throw new Exception("Please enter a title, description, and some tags to describe the map.");
                    }

                    // Call a function to save the map as a new portal item
                    await SaveNewMapAsync(MyMapView.Map, title, description, tags, thumbnailImg);

                    // Report a successful save
                    MessageBox.Show("Saved '" + title + "' to ArcGIS Online!", "Map Saved");
                }
                else
                {
                    // This is not the initial save, call SaveAsync to save changes to the existing portal item
                    await myMap.SaveAsync();

                    // Get the file stream from the new thumbnail image
                    Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();

                    // Update the item thumbnail
                    (myMap.Item as PortalItem).SetThumbnailWithImage(imageStream);
                    await myMap.SaveAsync();

                    // Report update was successful
                    MessageBox.Show("Saved changes to '" + myMap.Item.Title + "'", "Updates Saved");
                }
            }
            catch (Exception ex)
            {
                // Report error message
                MessageBox.Show("Error saving map to ArcGIS Online: " + ex.Message);
            }
            finally
            {
                // Hide the progress bar
                SaveProgressBar.Visibility = Visibility.Hidden;
            }
        }
Ejemplo n.º 22
0
        private async void MyMapView_GeoViewTapped(object sender, Esri.ArcGISRuntime.UI.Controls.GeoViewInputEventArgs e)
        {
            try
            {
                // Perform an identify across all layers, taking up to 10 results per layer.
                IReadOnlyList <IdentifyLayerResult> myIdentifyLayerResults = await MyMapView.IdentifyLayersAsync(e.Position, 15, false, 10);

                // Loop through each layer result in the collection of identify layer results.
                foreach (IdentifyLayerResult layerResult in myIdentifyLayerResults)
                {
                    // Get the layer content from the layer result.
                    ILayerContent myLayerContent = layerResult.LayerContent;

                    // Get the name of the layer content (i.e. the name of the layer).
                    string lc_Name = myLayerContent.Name;

                    // We are only interested in the identify layer results for the created feature collection layer that
                    // was generated from the NY Times articles.
                    if (lc_Name == "JoinedFCL")
                    {
                        // Get the sub layer results for the NY Times generated feature collection layer.
                        IReadOnlyList <IdentifyLayerResult> myIdentifyLayerResultsSubLayer = layerResult.SublayerResults;

                        // Get the first result found from identify operation on the NY Times generated feature collection layer.
                        IdentifyLayerResult myIdentifyLayerResultNYTimesFeatureCollectionTable = myIdentifyLayerResultsSubLayer.First();

                        // Get the geo-element collection from the first result.
                        IReadOnlyList <GeoElement> myGeoElements = myIdentifyLayerResultNYTimesFeatureCollectionTable.GeoElements;

                        // Get the first geo-element in the geo-element collection. This is the identified country (via the mouse click/tap)
                        // in the NY Times feature collection layer.
                        GeoElement myGeoElement = myGeoElements.First();

                        // Loop through key/value pair of the features attributes in the NY Times feature collection layer.
                        foreach (KeyValuePair <string, object> myKeyValuePair in myGeoElement.Attributes)
                        {
                            // Get the key (aka. field name).
                            var myKey = myKeyValuePair.Key;

                            // Get the value (aka. the text for the record of a specific field).
                            var myValue = myKeyValuePair.Value;

                            // Check is the name of the field in the NY Times feature collection layer 'AreaName'. This represents the country name.
                            if (myKey == "AreaName")
                            {
                                // Read the NY Times data from the text file and get back a list of each article.
                                // The format of each record/article will look like:
                                // [Article summary]~[Article abstract]~[Country name]~[Url to the NY times article]~[Url to an image about the NY times article]~[Date of NY Times news article]
                                // Ex:
                                // Netanyahu not happy with Cohen~A spokesman for Prime Minister Benjamin Netanyahu disagrees with Roger Cohen’s “pessimism.”~Israel~https://www.nytimes.com/2018/01/02/opinion/israel-future.html~https://www.nytimes.com/images/2017/12/29/opinion/29cohenWeb/29cohenWeb-thumbLarge.jpg~20180102
                                List <string> myNYTimesArticles = ReadTextFile3(_NEWSFILE);

                                // Create a FlowDocument to contain content for the RichTextBox.
                                FlowDocument myFlowDoc = new FlowDocument();

                                // Loop through each NY Times article.
                                foreach (var oneNYTimesArticle in myNYTimesArticles)
                                {
                                    // Char array to remove embedded double quotes from various NT Times strings.
                                    char[] charsToTrim = { '"' };

                                    // Get various sub-parts of the records for each NY Times article.
                                    string title    = oneNYTimesArticle.Split('~')[0].Trim(charsToTrim);
                                    string absrtact = oneNYTimesArticle.Split('~')[1].Trim(charsToTrim);
                                    string country  = oneNYTimesArticle.Split('~')[2].Trim(charsToTrim);
                                    string newsurl  = oneNYTimesArticle.Split('~')[3].Trim(charsToTrim);
                                    string imageurl = oneNYTimesArticle.Split('~')[4].Trim(charsToTrim);
                                    string date     = oneNYTimesArticle.Split('~')[5].Trim(charsToTrim);

                                    // Find a match from the NY Times feature collection layer feature country name and the NY
                                    // Times country name in the article.
                                    if (myValue.ToString() == country)
                                    {
                                        // Create a paragraph.
                                        Paragraph myParagraph = new Paragraph();

                                        myParagraph.FontSize = 18;

                                        // Create a run that contains the country and a new line.
                                        Run myRun = new Run(myValue.ToString() + System.Environment.NewLine);

                                        // Create a bold that contains short title (aka news headline) of the NY Times article.
                                        Bold myBold = new Bold(new Run(title));

                                        // Create a run that contains a new line.
                                        Run myRun2 = new Run(System.Environment.NewLine);

                                        // Create a new run that contains the hyperlink to the NY Times article.
                                        Run myRun7 = new Run(newsurl);

                                        // Create a new hyperlink based on the run.
                                        Hyperlink myHP = new Hyperlink(myRun7);

                                        // Set the hyperlink to the uri of the NY Times news article.
                                        myHP.NavigateUri = new Uri(newsurl);

                                        // Wire up the event handler when the user holds down the CTRL key and presses on the hyperlink for
                                        // the NY Times article shown in the rich text box.
                                        myHP.Click += MyHP_Click;

                                        // Add all of the sub components of the paragraph that make up what will be displayed for each NY
                                        // Times article in the rich text box.
                                        myParagraph.Inlines.Add(myRun);
                                        myParagraph.Inlines.Add(myBold);
                                        myParagraph.Inlines.Add(myRun2);
                                        myParagraph.Inlines.Add(myHP);

                                        // Add the paragraph to the flow document's block collection.
                                        myFlowDoc.Blocks.Add(myParagraph);
                                    }
                                }

                                // Make sure that the user is able to click on hyper links in the rick text box. Requires that the .IsDocumentEnabled be true.
                                MyRichTextBox.IsDocumentEnabled = true;

                                // Add initial content to the RichTextBox.
                                MyRichTextBox.Document = myFlowDoc;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Runs a search and populates the map with results based on the provided information
        /// </summary>
        /// <param name="enteredText">Results to search for</param>
        /// <param name="locationText">Location around which to find results</param>
        /// <param name="restrictToExtent">If true, limits results to only those that are within the current extent</param>
        private async void UpdateSearch(string enteredText, string locationText, bool restrictToExtent = false)
        {
            // Clear any existing markers
            MyMapView.GraphicsOverlays.Clear();

            // Return gracefully if the textbox is empty or the geocoder isn't ready
            if (string.IsNullOrWhiteSpace(enteredText) || _geocoder == null)
            {
                return;
            }

            // Create the geocode parameters
            GeocodeParameters parameters = new GeocodeParameters();

            // Get the MapPoint for the current search location
            MapPoint searchLocation = await GetSearchMapPoint(locationText);

            // Update the geocode parameters if the map point is not null
            if (searchLocation != null)
            {
                parameters.PreferredSearchLocation = searchLocation;
            }

            // Update the search area if desired
            if (restrictToExtent)
            {
                // Get the current map extent
                Geometry extent = MyMapView.VisibleArea;

                // Update the search parameters
                parameters.SearchArea = extent;
            }

            // Show the progress bar
            MyProgressBar.Visibility = Visibility.Visible;

            // Get the location information
            IReadOnlyList <GeocodeResult> locations = await _geocoder.GeocodeAsync(enteredText, parameters);

            // Stop gracefully and show a message if the geocoder does not return a result
            if (locations.Count < 1)
            {
                MyProgressBar.Visibility = Visibility.Collapsed; // 1. Hide the progress bar
                ShowStatusMessage("No results found");           // 2. Show a message
                return;                                          // 3. Stop
            }

            // Create the GraphicsOverlay so that results can be drawn on the map
            GraphicsOverlay resultOverlay = new GraphicsOverlay();

            // Add each address to the map
            foreach (GeocodeResult location in locations)
            {
                // Get the Graphic to display
                Graphic point = await GraphicForPoint(location.DisplayLocation);

                // Add the specific result data to the point
                point.Attributes["Match_Title"] = location.Label;

                // Get the address for the point
                IReadOnlyList <GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(location.DisplayLocation);

                // Add the first suitable address if possible
                if (addresses.Count() > 0)
                {
                    point.Attributes["Match_Address"] = addresses.First().Label;
                }

                // Add the Graphic to the GraphicsOverlay
                resultOverlay.Graphics.Add(point);
            }

            // Hide the progress bar
            MyProgressBar.Visibility = Visibility.Collapsed;

            // Add the GraphicsOverlay to the MapView
            MyMapView.GraphicsOverlays.Add(resultOverlay);

            // Create a viewpoint for the extent containing all graphics
            Viewpoint viewExtent = new Viewpoint(resultOverlay.Extent);

            // Update the map viewpoint
            MyMapView.SetViewpoint(viewExtent);
        }
Ejemplo n.º 24
0
        private async void Initialize()
        {
            // Hook up the DrawStatusChanged event.
            MyMapView.DrawStatusChanged += OnDrawStatusChanged;

            // Construct the map and set the MapView.Map property.
            Map map = new Map(Basemap.CreateLightGrayCanvasVector());

            MyMapView.Map = map;

            try
            {
                // Create a ClosestFacilityTask using the San Diego Uri.
                _task = await ClosestFacilityTask.CreateAsync(new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility"));

                // List of facilities to be placed around San Diego area.
                _facilities = new List <Facility> {
                    new Facility(new MapPoint(-1.3042129900625112E7, 3860127.9479775648, SpatialReferences.WebMercator)),
                    new Facility(new MapPoint(-1.3042193400557665E7, 3862448.873041752, SpatialReferences.WebMercator)),
                    new Facility(new MapPoint(-1.3046882875518233E7, 3862704.9896770366, SpatialReferences.WebMercator)),
                    new Facility(new MapPoint(-1.3040539754780494E7, 3862924.5938606677, SpatialReferences.WebMercator)),
                    new Facility(new MapPoint(-1.3042571225655518E7, 3858981.773018156, SpatialReferences.WebMercator)),
                    new Facility(new MapPoint(-1.3039784633928463E7, 3856692.5980474586, SpatialReferences.WebMercator)),
                    new Facility(new MapPoint(-1.3049023883956768E7, 3861993.789732541, SpatialReferences.WebMercator))
                };

                // Center the map on the San Diego facilities.
                Envelope fullExtent = GeometryEngine.CombineExtents(_facilities.Select(facility => facility.Geometry));
                await MyMapView.SetViewpointGeometryAsync(fullExtent, 50);

                // Create a symbol for displaying facilities.
                _facilitySymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png"))
                {
                    Height = 30,
                    Width  = 30
                };

                // Incident symbol.
                _incidentSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, Color.FromArgb(255, 0, 0, 0), 30);

                // Route to hospital symbol.
                _routeSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(255, 0, 0, 255), 5.0f);

                // Create Graphics Overlays for incidents and facilities.
                _incidentGraphicsOverlay = new GraphicsOverlay();
                _facilityGraphicsOverlay = new GraphicsOverlay();

                // Create a graphic and add to graphics overlay for each facility.
                foreach (Facility facility in _facilities)
                {
                    _facilityGraphicsOverlay.Graphics.Add(new Graphic(facility.Geometry, _facilitySymbol));
                }

                // Add each graphics overlay to MyMapView.
                MyMapView.GraphicsOverlays.Add(_incidentGraphicsOverlay);
                MyMapView.GraphicsOverlays.Add(_facilityGraphicsOverlay);
            }
            catch (Exception e)
            {
                await new MessageDialog(e.ToString(), "Error").ShowAsync();
            }
        }
Ejemplo n.º 25
0
        private async void Initialize()
        {
            try
            {
                // Disable the UI.
                FilterOptions.IsEnabled = false;

                // Create and load the utility network.
                _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl));

                // Create a map with layers in this utility network.
                MyMapView.Map = new Map(Basemap.CreateStreetsNightVector());
                MyMapView.Map.OperationalLayers.Add(new FeatureLayer(new Uri($"{FeatureServiceUrl}/{LineLayerId}")));
                MyMapView.Map.OperationalLayers.Add(new FeatureLayer(new Uri($"{FeatureServiceUrl}/{DeviceLayerId}")));

                // Get a trace configuration from a tier.
                UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork(DomainNetworkName) ?? throw new ArgumentException(DomainNetworkName);
                UtilityTier          tier          = domainNetwork.GetTier(TierName) ?? throw new ArgumentException(TierName);
                _configuration = tier.TraceConfiguration;

                // Create a trace filter.
                _configuration.Filter = new UtilityTraceFilter();

                // Get a default starting location.
                UtilityNetworkSource networkSource = _utilityNetwork.Definition.GetNetworkSource(NetworkSourceName) ?? throw new ArgumentException(NetworkSourceName);
                UtilityAssetGroup    assetGroup    = networkSource.GetAssetGroup(AssetGroupName) ?? throw new ArgumentException(AssetGroupName);
                UtilityAssetType     assetType     = assetGroup.GetAssetType(AssetTypeName) ?? throw new ArgumentException(AssetTypeName);
                Guid globalId = Guid.Parse(GlobalId);
                _startingLocation = _utilityNetwork.CreateElement(assetType, globalId);

                // Create a graphics overlay.
                GraphicsOverlay overlay = new GraphicsOverlay();
                MyMapView.GraphicsOverlays.Add(overlay);

                // Display starting location.
                IEnumerable <ArcGISFeature> elementFeatures = await _utilityNetwork.GetFeaturesForElementsAsync(new List <UtilityElement> {
                    _startingLocation
                });

                MapPoint startingLocationGeometry = elementFeatures.FirstOrDefault().Geometry as MapPoint;
                Symbol   symbol  = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.LimeGreen, 25d);
                Graphic  graphic = new Graphic(startingLocationGeometry, symbol);
                overlay.Graphics.Add(graphic);

                // Set the starting viewpoint.
                await MyMapView.SetViewpointAsync(new Viewpoint(startingLocationGeometry, 3000));

                // Build the choice list for categories populated with the `Name` property of each `UtilityCategory` in the `UtilityNetworkDefinition`.
                Categories.ItemsSource  = _utilityNetwork.Definition.Categories;
                Categories.SelectedItem = _utilityNetwork.Definition.Categories.First();

                // Enable the UI.
                FilterOptions.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                LoadingBar.Visibility = Visibility.Collapsed;
            }
        }
Ejemplo n.º 26
0
        private async void SaveMapClicked(object sender, RoutedEventArgs e)
        {
            try
            {
                // Don't attempt to save if the OAuth settings weren't provided
                if (String.IsNullOrEmpty(_appClientId) || String.IsNullOrEmpty(_oAuthRedirectUrl))
                {
                    MessageDialog dialog = new MessageDialog("OAuth settings were not provided.", "Cannot Save");
                    await dialog.ShowAsync();

                    return;
                }

                // Show the progress bar so the user knows work is happening
                SaveProgressBar.Visibility = Visibility.Visible;

                // Get the current map
                Map myMap = MyMapView.Map;

                // Apply the current extent as the map's initial extent
                myMap.InitialViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // Export the current map view to use as the item's thumbnail
                RuntimeImage thumbnailImg = await MyMapView.ExportImageAsync();

                // See if the map has already been saved (has an associated portal item)
                if (myMap.Item == null)
                {
                    // Get information for the new portal item
                    string title       = TitleTextBox.Text;
                    string description = DescriptionTextBox.Text;
                    string tagText     = TagsTextBox.Text;

                    // Make sure all required info was entered
                    if (String.IsNullOrEmpty(title) || String.IsNullOrEmpty(description) || String.IsNullOrEmpty(tagText))
                    {
                        throw new Exception("Please enter a title, description, and some tags to describe the map.");
                    }

                    // Call a function to save the map as a new portal item
                    await SaveNewMapAsync(MyMapView.Map, title, description, tagText.Split(','), thumbnailImg);

                    // Report a successful save
                    MessageDialog messageDialog = new MessageDialog("Saved '" + title + "' to ArcGIS Online!", "Map Saved");
                    await messageDialog.ShowAsync();
                }
                else
                {
                    // This is not the initial save, call SaveAsync to save changes to the existing portal item
                    await myMap.SaveAsync();

                    // Get the file stream from the new thumbnail image
                    Stream imageStream = await thumbnailImg.GetEncodedBufferAsync();

                    // Update the item thumbnail
                    ((PortalItem)myMap.Item).SetThumbnailWithImage(imageStream);
                    await myMap.SaveAsync();

                    // Report update was successful
                    MessageDialog messageDialog = new MessageDialog("Saved changes to '" + myMap.Item.Title + "'", "Updates Saved");
                    await messageDialog.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                // Report error message
                MessageDialog messageDialog = new MessageDialog("Error saving map to ArcGIS Online: " + ex.Message);
                await messageDialog.ShowAsync();
            }
            finally
            {
                // Hide the progress bar
                SaveProgressBar.Visibility = Visibility.Collapsed;
            }
        }
Ejemplo n.º 27
0
        private async void CreateNewFeatureCollection()
        {
            // Create the schema for a points table (one text field to contain a name attribute)
            List <Field> pointFields = new List <Field>();
            Field        placeField  = new Field(FieldType.Text, "Place", "Place Name", 50);

            pointFields.Add(placeField);

            // Create the schema for a lines table (one text field to contain a name attribute)
            List <Field> lineFields    = new List <Field>();
            Field        boundaryField = new Field(FieldType.Text, "Boundary", "Boundary Name", 50);

            lineFields.Add(boundaryField);

            // Create the schema for a polygon table (one text field to contain a name attribute)
            List <Field> polyFields = new List <Field>();
            Field        areaField  = new Field(FieldType.Text, "AreaName", "Area Name", 50);

            polyFields.Add(areaField);

            // Instantiate FeatureCollectionTables with schema and geometry type
            FeatureCollectionTable pointsTable = new FeatureCollectionTable(pointFields, GeometryType.Point, SpatialReferences.Wgs84);
            FeatureCollectionTable linesTable  = new FeatureCollectionTable(lineFields, GeometryType.Polyline, SpatialReferences.Wgs84);
            FeatureCollectionTable polysTable  = new FeatureCollectionTable(polyFields, GeometryType.Polygon, SpatialReferences.Wgs84);

            // Set rendering for each table
            pointsTable.Renderer = CreateRenderer(GeometryType.Point);
            linesTable.Renderer  = CreateRenderer(GeometryType.Polyline);
            polysTable.Renderer  = CreateRenderer(GeometryType.Polygon);

            // Create a new point feature, provide geometry and attribute values
            Feature pointFeature = pointsTable.CreateFeature();

            pointFeature.SetAttributeValue(placeField, "Current location");
            MapPoint point1 = new MapPoint(-79.497238, 8.849289, SpatialReferences.Wgs84);

            pointFeature.Geometry = point1;

            // Create a new line feature, provide geometry and attribute values
            Feature lineFeature = linesTable.CreateFeature();

            lineFeature.SetAttributeValue(boundaryField, "AManAPlanACanalPanama");
            MapPoint point2 = new MapPoint(-80.035568, 9.432302, SpatialReferences.Wgs84);
            Polyline line   = new Polyline(new MapPoint[] { point1, point2 });

            lineFeature.Geometry = line;

            // Create a new polygon feature, provide geometry and attribute values
            Feature polyFeature = polysTable.CreateFeature();

            polyFeature.SetAttributeValue(areaField, "Restricted area");
            MapPoint point3 = new MapPoint(-79.337936, 8.638903, SpatialReferences.Wgs84);
            MapPoint point4 = new MapPoint(-79.11409, 8.895422, SpatialReferences.Wgs84);
            Polygon  poly   = new Polygon(new MapPoint[] { point1, point3, point4 });

            polyFeature.Geometry = poly;

            try
            {
                // Add the new features to the appropriate feature collection table
                await pointsTable.AddFeatureAsync(pointFeature);

                await linesTable.AddFeatureAsync(lineFeature);

                await polysTable.AddFeatureAsync(polyFeature);

                // Create a feature collection and add the feature collection tables
                FeatureCollection featuresCollection = new FeatureCollection();
                featuresCollection.Tables.Add(pointsTable);
                featuresCollection.Tables.Add(linesTable);
                featuresCollection.Tables.Add(polysTable);

                // Create a FeatureCollectionLayer
                FeatureCollectionLayer collectionLayer = new FeatureCollectionLayer(featuresCollection);

                // When the layer loads, zoom the map centered on the feature collection
                await collectionLayer.LoadAsync();

                await MyMapView.SetViewpointCenterAsync(collectionLayer.FullExtent.GetCenter(), 1000000);

                // Add the layer to the Map's Operational Layers collection
                MyMapView.Map.OperationalLayers.Add(collectionLayer);
            }
            catch (Exception e)
            {
                await new MessageDialog(e.ToString(), "Error").ShowAsync();
            }
        }
Ejemplo n.º 28
0
        private async void Initialize()
        {
            // Create new map with the streets basemap
            Map myMap = new Map(Basemap.CreateStreets());

            // Create a Uri to the image service raster
            var myUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/NLCDLandCover2001/ImageServer");

            // Create new image service raster from the Uri
            ImageServiceRaster myImageServiceRaster = new ImageServiceRaster(myUri);

            // Load the image service raster
            await myImageServiceRaster.LoadAsync();

            // NOTE: This is the ASCII text for actual raw JSON string:
            // ========================================================
            //{
            //  "raster_function_arguments":
            //  {
            //    "z_factor":{"double":25.0,"type":"Raster_function_variable"},
            //    "slope_type":{"raster_slope_type":"none","type":"Raster_function_variable"},
            //    "azimuth":{"double":315,"type":"Raster_function_variable"},
            //    "altitude":{"double":45,"type":"Raster_function_variable"},
            //    "type":"Raster_function_arguments",
            //    "raster":{"name":"raster","is_raster":true,"type":"Raster_function_variable"},
            //    "nbits":{"int":8,"type":"Raster_function_variable"}
            //  },
            //  "raster_function":{"type":"Hillshade_function"},
            //  "type":"Raster_function_template"
            //}

            // Define the JSON string needed for the raster function
            String theJSON_String =
                @"{
                ""raster_function_arguments"":
                {
                  ""z_factor"":{ ""double"":25.0,""type"":""Raster_function_variable""},
                  ""slope_type"":{ ""raster_slope_type"":""none"",""type"":""Raster_function_variable""},
                  ""azimuth"":{ ""double"":315,""type"":""Raster_function_variable""},
                  ""altitude"":{ ""double"":45,""type"":""Raster_function_variable""},
                  ""type"":""Raster_function_arguments"",
                  ""raster"":{ ""name"":""raster"",""is_raster"":true,""type"":""Raster_function_variable""},
                  ""nbits"":{ ""int"":8,""type"":""Raster_function_variable""}
                },
              ""raster_function"":{ ""type"":""Hillshade_function""},
              ""type"":""Raster_function_template""
            }";

            // Create a raster function from the JSON string using the static/Shared method called: RasterFunction.FromJson(json as String)
            RasterFunction myRasterFunction = RasterFunction.FromJson(theJSON_String);

            // NOTE: Depending on your platform/device, you could have alternatively created the raster function via a JSON string that is contained in a
            // file on disk (ex: hillshade_simplified.json) via the constructor: Esri.ArcGISRuntime.Rasters.RasterFuntion(path as String)

            // Get the raster function arguments
            RasterFunctionArguments myRasterFunctionArguments = myRasterFunction.Arguments;

            // Get the list of names from the raster function arguments
            IReadOnlyList <string> myRasterNames = myRasterFunctionArguments.GetRasterNames();

            // Apply the first raster name and image service raster in the raster function arguments
            myRasterFunctionArguments.SetRaster(myRasterNames[0], myImageServiceRaster);

            // Create a new raster based on the raster function
            Raster myRaster = new Raster(myRasterFunction);

            // Create a new raster layer from the raster
            RasterLayer myRasterLayer = new RasterLayer(myRaster);

            // Add the raster layer to the maps layer collection
            myMap.Basemap.BaseLayers.Add(myRasterLayer);

            // Assign the map to the map view
            MyMapView.Map = myMap;

            // Get the service information (aka. metadata) about the image service raster
            ArcGISImageServiceInfo myArcGISImageServiceInfo = myImageServiceRaster.ServiceInfo;

            // Zoom the map to the extent of the image service raster (which also the extent of the raster layer)
            await MyMapView.SetViewpointGeometryAsync(myArcGISImageServiceInfo.FullExtent);

            // NOTE: The sample zooms to the extent of the ImageServiceRaster. Currently the ArcGIS Runtime does not
            // support zooming a RasterLayer out beyond 4 times it's published level of detail. The sample uses
            // MapView.SetViewpointCenterAsync() method to ensure the image shows when the app starts. You can see
            // the effect of the image service not showing when you zoom out to the full extent of the image and beyond.
        }
Ejemplo n.º 29
0
        // Handle a new selected comment record in the table view.
        private async void CommentsListBox_SelectionChanged(object sender, SelectedItemChangedEventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

            // Get the selected comment feature. If there is no selection, return.
            ArcGISFeature selectedComment = e.SelectedItem as ArcGISFeature;

            if (selectedComment == null)
            {
                return;
            }

            // Get the map image layer that contains the service request sublayer and the service request comments table.
            ArcGISMapImageLayer serviceRequestsMapImageLayer = (ArcGISMapImageLayer)MyMapView.Map.OperationalLayers[0];

            // Get the (non-spatial) table that contains the service request comments.
            ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];

            // Get the relationship that defines related service request features for features in the comments table (this is the first and only relationship).
            RelationshipInfo commentsRelationshipInfo = commentsTable.LayerInfo.RelationshipInfos.FirstOrDefault();

            // Create query parameters to get the related service request for features in the comments table.
            RelatedQueryParameters relatedQueryParams = new RelatedQueryParameters(commentsRelationshipInfo)
            {
                ReturnGeometry = true
            };

            try
            {
                // Query the comments table to get the related service request feature for the selected comment.
                IReadOnlyList <RelatedFeatureQueryResult> relatedRequestsResult = await commentsTable.QueryRelatedFeaturesAsync(selectedComment, relatedQueryParams);

                // Get the first result.
                RelatedFeatureQueryResult result = relatedRequestsResult.FirstOrDefault();

                // Get the first feature from the result. If it's null, warn the user and return.
                ArcGISFeature serviceRequestFeature = result.FirstOrDefault() as ArcGISFeature;
                if (serviceRequestFeature == null)
                {
                    await Application.Current.MainPage.DisplayAlert("No Feature", "Related feature not found.", "OK");

                    return;
                }

                // Load the related service request feature (so its geometry is available).
                await serviceRequestFeature.LoadAsync();

                // Get the service request geometry (point).
                MapPoint serviceRequestPoint = serviceRequestFeature.Geometry as MapPoint;

                // Create a cyan marker symbol to display the related feature.
                Symbol selectedRequestSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Cyan, 14);

                // Create a graphic using the service request point and marker symbol.
                Graphic requestGraphic = new Graphic(serviceRequestPoint, selectedRequestSymbol);

                // Add the graphic to the graphics overlay and zoom the map view to its extent.
                _selectedFeaturesOverlay.Graphics.Add(requestGraphic);
                await MyMapView.SetViewpointCenterAsync(serviceRequestPoint, 150000);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
Ejemplo n.º 30
0
        private async void ProcessMessages()
        {
            try
            {
                await MyMapView.LayersLoadedAsync();

                _messageLayer = MyMapView.Map.Layers.OfType <MessageLayer>().First();

                // This function simulates real time message processing by processing a static set of messages from an XML document.

                /*
                 * |== Example Message ==|
                 *
                 * <message>
                 *      <_type>position_report</_type>
                 *      <_action>update</_action>
                 *      <_id>16986029-8295-48d1-aa6a-478f400a53c0</_id>
                 *      <_wkid>3857</_wkid>
                 *      <sic>GFGPOLKGS-----X</sic>n
                 *      <_control_points>-226906.99878,6679149.88998;-228500.51759,6677576.8009;-232194.67644,6675625.78198</_control_points>
                 *      <uniquedesignation>DIRECTION OF ATTACK</uniquedesignation>
                 * </message>
                 */

                var file = await ApplicationData.Current.LocalFolder.GetFileAsync(DATA_PATH);

                using (var stream = await file.OpenStreamForReadAsync())
                {
                    XDocument xmlDocument = XDocument.Load(stream);

                    // Create a collection of messages
                    IEnumerable <XElement> messagesXml = from n in xmlDocument.Root.Elements()
                                                         where n.Name == "message"
                                                         select n;

                    // Iterate through the messages passing each to the ProcessMessage method on the MessageProcessor.
                    foreach (XElement messageXml in messagesXml)
                    {
                        Message message = new Message(from n in messageXml.Elements() select new KeyValuePair <string, string>(n.Name.ToString(), n.Value));
                        var     messageProcessingSuccessful = _messageLayer.ProcessMessage(message);

                        if (messageProcessingSuccessful == false)
                        {
                            var _x = new MessageDialog("Could not process the message.", "Message Processing Sample").ShowAsync();
                        }
                    }
                }

                EnableSelection.IsEnabled = true;

                /*
                 * Alternatively you can programmatically construct the message and set the attributes.
                 * e.g.
                 *
                 * // Create a new message
                 * Message msg = new Message();
                 *
                 * // Set the ID and other parts of the message
                 * msg.Id = messageID;
                 * msg.Add("_type", "position_report");
                 * msg.Add("_action", "update");
                 * msg.Add("_control_points", X.ToString(CultureInfo.InvariantCulture) + "," + Y.ToString(CultureInfo.InvariantCulture));
                 * msg.Add("_wkid", "3857");
                 * msg.Add("sic", symbolID);
                 * msg.Add("uniquedesignation", "1");
                 *
                 * // Process the message using the MessageProcessor within the MessageGroupLayer
                 * _messageLayer.ProcessMessage(msg);
                 */
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Message Processing Sample").ShowAsync();
            }
        }