コード例 #1
0
        private async void BtnCountFeaturesClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get the current visible extent.
                Geometry currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry;

                // Create the query parameters.
                QueryParameters queryCityCount = new QueryParameters
                {
                    Geometry = currentExtent,
                    // Specify the interpretation of the Geometry query parameters.
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // Get the count of matching features.
                long count = await _featureTable.QueryFeatureCountAsync(queryCityCount);

                // Update the UI.
                ResultsTextbox.Text = $"{count} features in extent";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
        }
コード例 #2
0
 protected override void OnKeyUp(KeyEventArgs e)
 {
     base.OnKeyUp(e);
     if (e.Key == Key.Space)
     {
         if (Keyboard.Modifiers == ModifierKeys.Control)
         {
             try
             {
                 var targetFile = "Viewpoints.json";
                 var json       = string.Join($",{Environment.NewLine}", _viewpoints.Select(JsonAsString));
                 File.WriteAllText(targetFile, json);
                 MessageBox.Show(this, $"Saved to file {targetFile}");
             }
             catch (Exception ex)
             {
                 MessageBox.Show(this, ex.Message);
             }
         }
         else
         {
             var viewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale);
             Trace.WriteLine(viewpoint.ToJson());
             _viewpoints.Add(viewpoint);
         }
     }
 }
コード例 #3
0
        // Creates a two-part polygon and a four-part polyline to use as test graphics for the Boundary method
        private void CreateTestGraphics()
        {
            // Get current viewpoints extent from the MapView
            var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;
            var center           = viewpointExtent.GetCenter();
            var width            = viewpointExtent.Width / 4;
            var left             = new MapPoint(center.X - width, center.Y, MyMapView.SpatialReference);
            var right            = new MapPoint(center.X + width, center.Y, MyMapView.SpatialReference);

            var fillSymbol = new SimpleFillSymbol()
            {
                Color = Colors.Red, Style = SimpleFillStyle.Solid
            };
            var lineSymbol = new SimpleLineSymbol()
            {
                Color = Colors.Red, Style = SimpleLineStyle.Solid, Width = 2
            };

            _testGraphics.Graphics.Add(new Graphic()
            {
                Geometry = CreatePolygonBox(left, width), Symbol = fillSymbol
            });
            _testGraphics.Graphics.Add(new Graphic()
            {
                Geometry = CreatePolylineBox(right, width), Symbol = lineSymbol
            });
        }
コード例 #4
0
        // Function to get suitable datum transformations for the specified input and output spatial references.
        private void GetSuitableTransformations(SpatialReference inSpatialRef, SpatialReference outSpatialRef, bool considerExtent)
        {
            // Get suitable transformations. Use the current extent to evaluate suitability, if requested.
            IReadOnlyList <DatumTransformation> transformations;

            if (considerExtent)
            {
                Envelope currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;
                transformations = TransformationCatalog.GetTransformationsBySuitability(inSpatialRef, outSpatialRef, currentExtent);
            }
            else
            {
                transformations = TransformationCatalog.GetTransformationsBySuitability(inSpatialRef, outSpatialRef);
            }

            // Get the default transformation for the specified input and output spatial reference.
            DatumTransformation defaultTransform = TransformationCatalog.GetTransformation(inSpatialRef, outSpatialRef);

            // Reset list.
            SuitableTransformationsList.Clear();

            // Wrap the transformations in a class that includes a boolean to indicate if it's the default transformation.
            foreach (DatumTransformation transform in transformations)
            {
                DatumTransformationListBoxItem item = new DatumTransformationListBoxItem(transform)
                {
                    IsDefault = (transform.Name == defaultTransform.Name)
                };
                SuitableTransformationsList.Add(item);
            }
        }
コード例 #5
0
        private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
        {
            try
            {
                _trafficOverlay.Visibility  = Visibility.Collapsed;
                _trafficOverlay.DataContext = null;

                var identifyTask = new IdentifyTask(new Uri(_trafficLayer.ServiceUri));
                // Get current viewpoints extent from the MapView
                var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

                IdentifyParameters identifyParams = new IdentifyParameters(e.Location, viewpointExtent, 5, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth)
                {
                    LayerIDs         = new int[] { 2, 3, 4 },
                    LayerOption      = LayerOption.Top,
                    SpatialReference = MyMapView.SpatialReference,
                };

                var result = await identifyTask.ExecuteAsync(identifyParams);

                if (result != null && result.Results != null && result.Results.Count > 0)
                {
                    _trafficOverlay.DataContext = result.Results.First();
                    _trafficOverlay.Visibility  = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
コード例 #6
0
        // Continually accepts user-entered points
        // - Buffered polygons are created from the points and added to the graphics layer
        private async Task AcceptClassPointsAsync()
        {
            // Get current viewpoints extent from the MapView
            var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

            try
            {
                while (true)
                {
                    var point = await MyMapView.Editor.RequestPointAsync();

                    var polygon = GeometryEngine.Buffer(point, viewpointExtent.Width * .01);
                    var attr    = new Dictionary <string, object>()
                    {
                        { "ID", _graphicsOverlay.Graphics.Count + 1 }
                    };
                    _graphicsOverlay.Graphics.Add(new Graphic(polygon, attr));
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                var _ = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
        }
コード例 #7
0
        // Draw and densify a user defined polygon
        private async void DensifyButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _inputOverlay.Graphics.Clear();
                _resultOverlay.Graphics.Clear();

                // Request polygon from the user
                var poly = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon, _polySymbol) as Polygon;

                // Add original polygon and vertices to input graphics layer
                _inputOverlay.Graphics.Add(new Graphic(poly, _polySymbol));
                foreach (var coord in poly.Parts.First().GetPoints())
                {
                    _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 polygon
                var densify = GeometryEngine.Densify(poly, viewpointExtent.Width / 100) as Polygon;

                // Add new vertices to result graphics layer
                foreach (var coord in densify.Parts.First().GetPoints())
                {
                    _resultOverlay.Graphics.Add(new Graphic(coord, _newVertexSymbol));
                }
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog("Densify Error: " + ex.Message, "Sample Error").ShowAsync();
            }
        }
コード例 #8
0
        private async void MyMapView_LayerLoaded(object sender, LayerLoadedEventArgs e)
        {
            if (e.Layer.ID == "ParcelsGraphicsLayer")
            {
                if (parcelGraphicsLayer != null && parcelGraphicsLayer.Graphics.Count == 0)
                {
                    QueryTask queryTask = new QueryTask(new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/TaxParcel/AssessorsParcelCharacteristics/MapServer/1"));

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

                    //Create a geometry to use as the extent within which parcels will be returned
                    var contractRatio  = viewpointExtent.Width / 6;
                    var extentGeometry = new Envelope(viewpointExtent.GetCenter().X - contractRatio,
                                                      viewpointExtent.GetCenter().Y - contractRatio,
                                                      viewpointExtent.GetCenter().X + contractRatio,
                                                      viewpointExtent.GetCenter().Y + contractRatio,
                                                      MyMapView.SpatialReference);
                    Query query = new Query(extentGeometry);
                    query.ReturnGeometry      = true;
                    query.OutSpatialReference = MyMapView.SpatialReference;


                    var results = await queryTask.ExecuteAsync(query, CancellationToken.None);

                    foreach (Graphic g in results.FeatureSet.Features)
                    {
                        parcelGraphicsLayer.Graphics.Add(g);
                    }
                }
                await DoIntersection();
            }
        }
        // Update the UI grid with bird data queried from local gdb
        private async Task RefreshDataView()
        {
            LocalBirdFeatures = await _localBirdsLayer.FeatureTable.QueryAsync(new QueryFilter()
            {
                WhereClause = "1=1"
            });

            QueryTask queryTask = new QueryTask(new Uri(_onlineBirdsLayer.ServiceUri + "/1"));
            // Get current viewpoints extent from the MapView
            var   currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var   viewpointExtent  = currentViewpoint.TargetGeometry.Extent;
            Query query            = new Query("1=1")
            {
                Geometry = viewpointExtent, OutFields = new OutFields(new string[] { "globalid" })
            };
            var queryResult = await queryTask.ExecuteAsync(query);

            var onlineBirdIds = queryResult.FeatureSet.Features.Select(f => f.Attributes["globalid"]);
            var localBirdIds  = LocalBirdFeatures.Select(b => b.Attributes["globalid"]);
            var newBirdsIds   = localBirdIds.Except(onlineBirdIds);

            var newBirdOIDs = from newBird in LocalBirdFeatures
                              join newBirdId in newBirdsIds on newBird.Attributes["globalid"] equals newBirdId
                              select(long) newBird.Attributes["objectid"];

            _localBirdsLayer.ClearSelection();
            _localBirdsLayer.SelectFeatures(newBirdOIDs.ToArray());
        }
        private async void BtnCountFeatures_Click(object sender, EventArgs e)
        {
            // Get the current visible extent.
            Geometry currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry;

            // Create the query parameters.
            QueryParameters queryCityCount = new QueryParameters
            {
                Geometry = currentExtent,
                // Specify the interpretation of the Geometry query parameters.
                SpatialRelationship = SpatialRelationship.Intersects
            };

            try
            {
                // Get the count of matching features.
                long count = await _featureTable.QueryFeatureCountAsync(queryCityCount);

                // Update the UI.
                txtResults.Text = $"{count} features in extent";
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
コード例 #11
0
        private async void OnSaveMapClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Create a challenge request for portal credentials (OAuth credential request for arcgis.com)
                CredentialRequestInfo challengeRequest = new CredentialRequestInfo();

                // Use the OAuth implicit grant flow
                challengeRequest.GenerateTokenOptions = new GenerateTokenOptions
                {
                    TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit
                };

                // Indicate the url (portal) to authenticate with (ArcGIS Online)
                challengeRequest.ServiceUri = new Uri("https://www.arcgis.com/sharing/rest");

                // Call GetCredentialAsync on the AuthenticationManager to invoke the challenge handler
                await AuthenticationManager.Current.GetCredentialAsync(challengeRequest, false);

                // Get information for the new portal item
                var title       = TitleTextBox.Text;
                var description = DescriptionTextBox.Text;
                var tags        = TagsTextBox.Text.Split(',');

                // Throw an exception if the text is null or empty for title or description
                if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(description))
                {
                    throw new Exception("Title and description are required");
                }

                // Get current map extent (viewpoint) for the map initial extent
                var currentViewpoint = MyMapView.GetCurrentViewpoint(Esri.ArcGISRuntime.Mapping.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
                if (!_mapViewModel.MapIsSaved)
                {
                    // Call the SaveNewMapAsync method on the view model, pass in the required info
                    await _mapViewModel.SaveNewMapAsync(currentViewpoint, title, description, tags, thumbnailImg);

                    // Report success
                    MessageBox.Show("Map '" + title + "' was saved to your portal");
                }
                else
                {
                    // Map has previously been saved as a portal item, update it (title, description, and tags will remain the same)
                    _mapViewModel.UpdateMapItem();

                    // Report success
                    MessageBox.Show("Changes to '" + title + "' were updated to the portal.");
                }
            }
            catch (Exception ex)
            {
                // Report error
                MessageBox.Show("Error while saving: " + ex.Message);
            }
        }
コード例 #12
0
        /// <summary>
        /// Begins the export process
        /// </summary>
        private void MyExportPreviewButton_Clicked(object sender, EventArgs e)
        {
            // If preview isn't open, start an export
            if (!_previewOpen)
            {
                // Show the progress bar
                MyProgressBar.IsVisible = true;

                // Save the map viewpoint
                _originalView = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

                // Start the export
                StartExport();
            }
            else // Otherwise, close the preview
            {
                // Change the button text
                MyExportPreviewButton.Text = "Export Tiles";

                // Clear the preview open flag
                _previewOpen = false;

                // Re-size the mapview
                MyMapView.Margin = new Thickness(0);

                // Re-apply the original map
                MyMapView.Map = _basemap;

                // Re-apply the original viewpoint
                MyMapView.SetViewpoint(_originalView);
            }
        }
        // Generate / download and display layers from a generated geodatabase
        private async void GenerateGeodatabaseButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                panelUI.IsEnabled      = false;
                panelStatus.Visibility = Visibility.Visible;

                ReportStatus("Creating GeodatabaseSyncTask...");
                var syncTask = new GeodatabaseSyncTask(new Uri(BASE_URL));

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

                var options = new GenerateGeodatabaseParameters(new int[] { 0, 1, 2 }, viewpointExtent)
                {
                    GeodatabasePrefixName = GDB_PREFIX,
                    ReturnAttachments     = false,
                    OutSpatialReference   = MyMapView.SpatialReference,
                    SyncModel             = SyncModel.PerLayer
                };

                var tcs = new TaskCompletionSource <GeodatabaseStatusInfo>();
                Action <GeodatabaseStatusInfo, Exception> completionAction = (info, ex) =>
                {
                    if (ex != null)
                    {
                        tcs.SetException(ex);
                    }
                    tcs.SetResult(info);
                };

                var generationProgress = new Progress <GeodatabaseStatusInfo>();
                generationProgress.ProgressChanged += (sndr, sts) => { ReportStatus(sts.Status.ToString()); };

                ReportStatus("Starting GenerateGeodatabase...");
                var result = await syncTask.GenerateGeodatabaseAsync(options, completionAction,
                                                                     TimeSpan.FromSeconds(3), generationProgress, CancellationToken.None);

                ReportStatus("Waiting on geodatabase from server...");
                var statusResult = await tcs.Task;

                ReportStatus("Downloading Geodatabase...");
                var gdbPath = await DownloadGeodatabase(statusResult);

                ReportStatus("Create local feature layers...");
                await CreateFeatureLayersAsync(gdbPath);

                MyMapView.Map.Layers["wildfireGroup"].IsVisible = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Sample Error");
            }
            finally
            {
                panelStatus.Visibility = Visibility.Collapsed;
                panelUI.IsEnabled      = true;
            }
        }
        // Process user selection and point clicks
        private async Task ProcessUserPointsAsync(bool isTargetSelected)
        {
            try
            {
                txtResult.Visibility = Visibility.Collapsed;
                txtResult.Text       = string.Empty;

                if (MyMapView.Editor.IsActive)
                {
                    MyMapView.Editor.Cancel.Execute(null);
                }

                if (!isTargetSelected)
                {
                    await SelectTargetGeometryAsync();
                }

                while (MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry.Extent != null)
                {
                    await GetNearestCoordAsync((bool)cboVertexOnly.IsChecked);
                }
            }
            catch (TaskCanceledException) { }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Nearest Coordinate Sample");
            }
        }
コード例 #15
0
        // Accept user map clicks and add points to the graphics layer with the selected symbol
        private async Task AcceptPointsAsync()
        {
            try
            {
                while (MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry.Extent != null)
                {
                    SampleSymbol sampleSymbol = _symbols[symbolCombo.SelectedIndex];

                    Esri.ArcGISRuntime.Geometry.Geometry shape = null;
                    if (sampleSymbol.Symbol is LineSymbol)
                    {
                        shape = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polyline, sampleSymbol.Symbol);
                    }
                    else
                    {
                        shape = await MyMapView.Editor.RequestShapeAsync(DrawShape.Polygon, sampleSymbol.Symbol);
                    }

                    _graphicsOverlay.Graphics.Add(new Graphic(shape, sampleSymbol.Symbol));
                    await Task.Delay(100);
                }
            }
            catch (TaskCanceledException)
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Line and Fill Symbols");
            }
        }
コード例 #16
0
        // Draw the unsimplified polygon
        private void DrawPolygon()
        {
            // Get current viewpoints extent from the MapView
            var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

            MapPoint center    = viewpointExtent.GetCenter();
            double   lat       = center.Y;
            double   lon       = center.X + 300;
            double   latOffset = 300;
            double   lonOffset = 300;

            var points = new PointCollection()
            {
                new MapPoint(lon - lonOffset, lat),
                new MapPoint(lon, lat + latOffset),
                new MapPoint(lon + lonOffset, lat),
                new MapPoint(lon, lat - latOffset),
                new MapPoint(lon - lonOffset, lat),
                new MapPoint(lon - 2 * lonOffset, lat + latOffset),
                new MapPoint(lon - 3 * lonOffset, lat),
                new MapPoint(lon - 2 * lonOffset, lat - latOffset),
                new MapPoint(lon - 1.5 * lonOffset, lat + latOffset),
                new MapPoint(lon - lonOffset, lat)
            };

            _unsimplifiedPolygon = new Polygon(points, MyMapView.SpatialReference);

            _polygonOverlay.Graphics.Clear();
            _polygonOverlay.Graphics.Add(new Graphic(_unsimplifiedPolygon));
        }
コード例 #17
0
        private void OnViewpointChanged(object sender, EventArgs e)
        {
            // Get the MapView or SceneView that sent the event
            GeoView sendingView = (GeoView)sender;

            // Only take action if this geoview is the one that the user is navigating.
            // Viewpoint changed events are fired when SetViewpoint is called; This check prevents a feedback loop
            if (sendingView.IsNavigating)
            {
                // If the MapView sent the event, update the SceneView's viewpoint
                if (sender is MapView)
                {
                    // Get the viewpoint
                    Viewpoint updateViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.CenterAndScale);

                    // Set the viewpoint
                    MySceneView.SetViewpoint(updateViewpoint);
                }
                else // Else, update the MapView's viewpoint
                {
                    // Get the viewpoint
                    Viewpoint updateViewpoint = MySceneView.GetCurrentViewpoint(ViewpointType.CenterAndScale);

                    // Set the viewpoint
                    MyMapView.SetViewpoint(updateViewpoint);
                }
            }
        }
コード例 #18
0
        // Find matching places, create graphics and add them to the UI
        private async void FindButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                progress.Visibility    = Visibility.Visible;
                listResults.Visibility = Visibility.Collapsed;
                _addressOverlay.Graphics.Clear();

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

                var param = new OnlineLocatorFindParameters(SearchTextBox.Text)
                {
                    SearchExtent        = viewpointExtent,
                    Location            = viewpointExtent.GetCenter(),
                    MaxLocations        = 5,
                    OutSpatialReference = MyMapView.SpatialReference,
                    OutFields           = new string[] { "Place_addr" }
                };

                var candidateResults = await _locatorTask.FindAsync(param, CancellationToken.None);

                if (candidateResults == null || candidateResults.Count == 0)
                {
                    throw new Exception("No candidates found in the current map extent.");
                }

                foreach (var candidate in candidateResults)
                {
                    AddGraphicFromLocatorCandidate(candidate);
                }

                var extent = GeometryEngine.Union(_addressOverlay.Graphics.Select(g => g.Geometry)).Extent.Expand(1.1);
                await MyMapView.SetViewAsync(extent);

                listResults.Visibility = Visibility.Visible;
            }
            catch (AggregateException ex)
            {
                var innermostExceptions = ex.Flatten().InnerExceptions;
                if (innermostExceptions != null && innermostExceptions.Count > 0)
                {
                    var _x = new MessageDialog(string.Join(" > ", innermostExceptions.Select(i => i.Message).ToArray()), "Sample Error").ShowAsync();
                }
                else
                {
                    var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
                }
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
            finally
            {
                progress.Visibility = Visibility.Collapsed;
            }
        }
コード例 #19
0
        private async Task RunIdentify(MapPoint mp)
        {
            // Get current viewpoints extent from the MapView
            var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;
            IdentifyParameters identifyParams = new IdentifyParameters(mp, viewpointExtent, 2, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth)
            {
                LayerOption      = LayerOption.Visible,
                SpatialReference = MyMapView.SpatialReference,
            };

            IdentifyTask identifyTask = new IdentifyTask(new Uri("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/" +
                                                                 "Demographics/ESRI_Census_USA/MapServer"));

            progress.IsActive = true;

            try
            {
                TitleComboBox.ItemsSource = null;
                ResultsGrid.ItemsSource   = null;
                var result = await identifyTask.ExecuteAsync(identifyParams);

                GraphicsLayer graphicsLayer = MyMapView.Map.Layers["MyGraphicsLayer"] as GraphicsLayer;
                graphicsLayer.Graphics.Clear();
                graphicsLayer.Graphics.Add(new Graphic()
                {
                    Geometry = mp
                });

                var _dataItems = new List <DataItem>();
                if (result != null && result.Results != null && result.Results.Count > 0)
                {
                    foreach (var r in result.Results)
                    {
                        Feature feature = r.Feature;
                        string  title   = r.Value.ToString() + " (" + r.LayerName + ")";
                        _dataItems.Add(new DataItem()
                        {
                            Title = title,
                            Data  = feature.Attributes
                        });
                    }
                }
                TitleComboBox.ItemsSource = _dataItems;
                if (_dataItems.Count > 0)
                {
                    TitleComboBox.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                progress.IsActive = false;
            }
        }
コード例 #20
0
        // Download the tile cache
        private async void ExportTilesButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                panelTOC.Visibility = Visibility.Collapsed;
                progress.Visibility = Visibility.Visible;

                var downloadOptions = new DownloadTileCacheParameters(ApplicationData.Current.TemporaryFolder)
                {
                    OverwriteExistingFiles = true
                };

                var localTiledLayer = MyMapView.Map.Layers.FirstOrDefault(lyr => lyr.ID == LOCAL_LAYER_ID);
                if (localTiledLayer != null)
                {
                    MyMapView.Map.Layers.Remove(localTiledLayer);
                }

                var result = await _exportTilesTask.GenerateTileCacheAndDownloadAsync(
                    _genOptions, downloadOptions, TimeSpan.FromSeconds(5), CancellationToken.None,
                    new Progress <ExportTileCacheJob>((job) =>                    // Callback for reporting status during tile cache generation
                {
                    Debug.WriteLine(getTileCacheGenerationStatusMessage(job));
                }),
                    new Progress <ExportTileCacheDownloadProgress>((downloadProgress) =>                    // Callback for reporting status during tile cache download
                {
                    Debug.WriteLine(getDownloadStatusMessage(downloadProgress));
                }));

                localTiledLayer = new ArcGISLocalTiledLayer(result.OutputPath)
                {
                    ID = LOCAL_LAYER_ID
                };
                MyMapView.Map.Layers.Insert(1, localTiledLayer);

                _onlineTiledLayer.IsVisible = false;

                if (MyMapView.Scale < _genOptions.MinScale)
                {
                    // Get current viewpoints extent from the MapView
                    var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                    var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;
                    await MyMapView.SetViewAsync(viewpointExtent.GetCenter(), _genOptions.MinScale);
                }


                panelTOC.Visibility    = Visibility.Visible;
                panelExport.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog(ex.Message, "Sample Error").ShowAsync();
            }
            finally
            {
                progress.Visibility = Visibility.Collapsed;
            }
        }
コード例 #21
0
        // Create polyline graphics on the map in the center and the center of four equal quadrants
        private void MyMapView_NavigationCompleted(object sender, EventArgs e)
        {
            MyMapView.NavigationCompleted -= MyMapView_NavigationCompleted;
            try
            {
                // Get current viewpoints extent from the MapView
                var currentViewpoint  = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent   = currentViewpoint.TargetGeometry.Extent;
                var myViewpointExtent = viewpointExtent;
                var height            = myViewpointExtent.Height / 4;
                var width             = myViewpointExtent.Width / 4;
                var length            = width / 4;
                var center            = myViewpointExtent.GetCenter();

                var topLeft     = new MapPoint(center.X - width, center.Y + height, MyMapView.SpatialReference);
                var topRight    = new MapPoint(center.X + width, center.Y + height, MyMapView.SpatialReference);
                var bottomLeft  = new MapPoint(center.X - width, center.Y - height, MyMapView.SpatialReference);
                var bottomRight = new MapPoint(center.X + width, center.Y - height, MyMapView.SpatialReference);

                var redSymbol = new SimpleLineSymbol()
                {
                    Color = System.Windows.Media.Colors.Red,
                    Width = 4,
                    Style = SimpleLineStyle.Solid
                };
                var blueSymbol = new SimpleLineSymbol()
                {
                    Color = System.Windows.Media.Colors.Blue,
                    Width = 4,
                    Style = SimpleLineStyle.Solid
                };

                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolylineX(center, length), Symbol = blueSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolylineX(topLeft, length), Symbol = redSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolylineX(topRight, length), Symbol = redSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolylineX(bottomLeft, length), Symbol = redSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolylineX(bottomRight, length), Symbol = redSymbol
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occurred : " + ex.Message, "Create Polygons Sample");
            }
        }
コード例 #22
0
        // Accept user map clicks and add points to the graphics layer with the selected symbol
        private async Task AcceptPointsAsync()
        {
            while (MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry.Extent != null)
            {
                var point = await MyMapView.Editor.RequestPointAsync();

                _graphicsOverlay.Graphics.Add(new Graphic(point, _symbols[symbolCombo.SelectedIndex]));
            }
        }
コード例 #23
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
            var 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
                var cred = await EnsureLoggedInAsync();

                AuthenticationManager.Current.AddCredential(cred);

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

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

                // 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
                    RuntimeImage img = null;
                    await myMap.SaveAsAsync(agsOnline, null, title, description, tags, img, false);

                    // Report a successful save
                    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();

                    // Report update was successful
                    DisplayAlert("Updates Saved", "Saved changes to '" + myMap.Item.Title + "'", "OK");
                }
            }
            catch (Exception ex)
            {
                // Show the exception message
                DisplayAlert("Unable to save map", ex.Message, "OK");
            }
            finally
            {
                // Hide the progress bar
                SaveMapProgressBar.IsVisible = false;
            }
        }
コード例 #24
0
        /// <summary>
        /// Function used to keep the overlaid preview area marker in position
        /// This is called by MyMapView_ViewpointChanged every time the user pans/zooms
        ///     and updates the red box graphic to outline 80% of the current view
        /// </summary>
        private void UpdateMapExtentGraphic()
        {
            // Return if mapview is null.
            if (MyMapView == null)
            {
                return;
            }

            // Get the new viewpoint.
            Viewpoint myViewPoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);

            // Return if viewpoint is null.
            if (myViewPoint == null)
            {
                return;
            }

            // Get the updated extent for the new viewpoint.
            Envelope extent = myViewPoint.TargetGeometry as Envelope;

            // Return if extent is null.
            if (extent == null)
            {
                return;
            }

            // Create an envelope that is a bit smaller than the extent.
            EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent);

            envelopeBldr.Expand(0.80);

            // Get the (only) graphics overlay in the map view.
            GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.FirstOrDefault();

            // Return if the extent overlay is null.
            if (extentOverlay == null)
            {
                return;
            }

            // Get the extent graphic.
            Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault();

            // Create the extent graphic and add it to the overlay if it doesn't exist.
            if (extentGraphic == null)
            {
                extentGraphic = new Graphic(envelopeBldr.ToGeometry());
                extentOverlay.Graphics.Add(extentGraphic);
            }
            else
            {
                // Otherwise, update the graphic's geometry.
                extentGraphic.Geometry = envelopeBldr.ToGeometry();
            }
        }
コード例 #25
0
        // Create four point graphics on the map in the center of four equal quadrants
        private void MyMapView_NavigationCompleted(object sender, EventArgs e)
        {
            MyMapView.NavigationCompleted -= MyMapView_NavigationCompleted;
            try
            {
                // Get current viewpoints extent from the MapView
                var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
                var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

                var myViewpointExtent = viewpointExtent;
                var height            = myViewpointExtent.Height / 4;
                var width             = myViewpointExtent.Width / 4;
                var center            = myViewpointExtent.GetCenter();

                var topLeft     = new MapPoint(center.X - width, center.Y + height, MyMapView.SpatialReference);
                var topRight    = new MapPoint(center.X + width, center.Y + height, MyMapView.SpatialReference);
                var bottomLeft  = new MapPoint(center.X - width, center.Y - height, MyMapView.SpatialReference);
                var bottomRight = new MapPoint(center.X + width, center.Y - height, MyMapView.SpatialReference);

                var symbol = new SimpleMarkerSymbol()
                {
                    Color = Colors.Red, Size = 15, Style = SimpleMarkerStyle.Diamond
                };

                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = topLeft, Symbol = symbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = topRight, Symbol = symbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = bottomLeft, Symbol = symbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = bottomRight, Symbol = symbol
                });

                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = new MapPoint(0, 0),
                    Symbol   = new SimpleMarkerSymbol()
                    {
                        Size = 15, Color = Colors.Blue
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured : " + ex.Message, "Create Points Sample");
            }
        }
コード例 #26
0
        private async void OnExecuteStatisticsQueryClicked(object sender, EventArgs e)
        {
            // Create definitions for each statistic to calculate
            StatisticDefinition statDefinitionAvgPop    = new StatisticDefinition("POP", StatisticType.Average, "");
            StatisticDefinition statDefinitionMinPop    = new StatisticDefinition("POP", StatisticType.Minimum, "");
            StatisticDefinition statDefinitionMaxPop    = new StatisticDefinition("POP", StatisticType.Maximum, "");
            StatisticDefinition statDefinitionSumPop    = new StatisticDefinition("POP", StatisticType.Sum, "");
            StatisticDefinition statDefinitionStdDevPop = new StatisticDefinition("POP", StatisticType.StandardDeviation, "");
            StatisticDefinition statDefinitionVarPop    = new StatisticDefinition("POP", StatisticType.Variance, "");

            // Create a definition for count that includes an alias for the output
            StatisticDefinition statDefinitionCount = new StatisticDefinition("POP", StatisticType.Count, "CityCount");

            // Add the statistics definitions to a list
            List <StatisticDefinition> statDefinitions = new List <StatisticDefinition>
            {
                statDefinitionAvgPop,
                statDefinitionCount,
                statDefinitionMinPop,
                statDefinitionMaxPop,
                statDefinitionSumPop,
                statDefinitionStdDevPop,
                statDefinitionVarPop
            };

            // Create the statistics query parameters, pass in the list of definitions
            StatisticsQueryParameters statQueryParams = new StatisticsQueryParameters(statDefinitions);

            // If only using features in the current extent, set up the spatial filter for the statistics query parameters
            if (OnlyInExtentSwitch.IsToggled)
            {
                // Get the current extent (envelope) from the map view
                Envelope currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;

                // Set the statistics query parameters geometry with the envelope
                statQueryParams.Geometry = currentExtent;

                // Set the spatial relationship to Intersects (which is the default)
                statQueryParams.SpatialRelationship = SpatialRelationship.Intersects;
            }

            // If only evaluating the largest cities (over 5 million in population), set up an attribute filter
            if (OnlyBigCitiesSwitch.IsToggled)
            {
                // Set a where clause to get the largest cities (could also use "POP_CLASS = '5,000,000 and greater'")
                statQueryParams.WhereClause = "POP_RANK = 1";
            }

            // Execute the statistical query with these parameters and await the results
            StatisticsQueryResult statQueryResult = await _worldCitiesTable.QueryStatisticsAsync(statQueryParams);

            // Display results in the list box
            StatResultsList.ItemsSource = statQueryResult.FirstOrDefault().Statistics.ToList();
            ResultsGrid.IsVisible       = true;
        }
コード例 #27
0
        // Estimate local tile cache size / space
        private async void EstimateCacheSizeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                panelUI.IsEnabled      = false;
                panelExport.Visibility = Visibility.Collapsed;
                panelTOC.Visibility    = Visibility.Collapsed;
                progress.Visibility    = Visibility.Visible;

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

                _aoiOverlay.Graphics.Clear();
                _aoiOverlay.Graphics.Add(new Graphic(viewpointExtent));
                _aoiOverlay.IsVisible = true;

                _genOptions = new GenerateTileCacheParameters()
                {
                    Format         = ExportTileCacheFormat.TilePackage,
                    MinScale       = _onlineTiledLayer.ServiceInfo.TileInfo.Lods[(int)sliderLOD.Value].Scale,
                    MaxScale       = _onlineTiledLayer.ServiceInfo.TileInfo.Lods[0].Scale,
                    GeometryFilter = GeometryEngine.Project(viewpointExtent, SpatialReferences.Wgs84)
                };

                var job = await _exportTilesTask.EstimateTileCacheSizeAsync(_genOptions,
                                                                            (result, ex) => // Callback for when estimate operation has completed
                {
                    if (ex == null)                                                         // Check whether operation completed with errors
                    {
                        txtExportSize.Text     = string.Format("Tiles: {0} - Size (kb): {1:0}", result.TileCount, result.Size / 1024);
                        panelExport.Visibility = Visibility.Visible;
                        panelTOC.Visibility    = Visibility.Collapsed;
                    }
                    else
                    {
                        MessageBox.Show(ex.Message, "Sample Error");
                    }
                    panelUI.IsEnabled   = true;
                    progress.Visibility = Visibility.Collapsed;
                },
                                                                            TimeSpan.FromSeconds(1),                 // Check the operation every five seconds
                                                                            CancellationToken.None,
                                                                            new Progress <ExportTileCacheJob>((j) => // Callback for status updates
                {
                    Debug.WriteLine(getTileCacheGenerationStatusMessage(j));
                }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Sample Error");
                panelExport.Visibility = Visibility.Visible;
                panelTOC.Visibility    = Visibility.Collapsed;
            }
        }
        // Utility: Generate a random MapPoint within the current extent
        private MapPoint GetRandomMapPoint()
        {
            // Get current viewpoints extent from the MapView
            var currentViewpoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
            var viewpointExtent  = currentViewpoint.TargetGeometry.Extent;

            double x = viewpointExtent.XMin + (_random.NextDouble() * viewpointExtent.Width);
            double y = viewpointExtent.YMin + (_random.NextDouble() * viewpointExtent.Height);

            return(new MapPoint(x, y, MyMapView.SpatialReference));
        }
        /// <summary>
        /// Identifies feature to highlight.
        /// </summary>
        private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
        {
            // Ignore tap events while in edit mode so we do not interfere with edit geometry.
            var inEditMode = EditButton.IsEnabled;

            if (inEditMode)
            {
                return;
            }

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

            var layer     = MyMapView.Map.Layers["RecreationalArea"] as ArcGISDynamicMapServiceLayer;
            var task      = new IdentifyTask(new Uri(layer.ServiceUri));
            var mapPoint  = MyMapView.ScreenToLocation(e.Position);
            var parameter = new IdentifyParameters(mapPoint, viewpointExtent, 2, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth);

            // Clears map of any highlights.
            var overlay = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay;

            overlay.Graphics.Clear();

            SetGeometryEditor();

            string message = null;

            try
            {
                // Performs an identify and adds feature result as selected into overlay.
                var result = await task.ExecuteAsync(parameter);

                if (result == null || result.Results == null || result.Results.Count < 1)
                {
                    return;
                }
                var graphic = (Graphic)result.Results[0].Feature;
                graphic.IsSelected = true;
                overlay.Graphics.Add(graphic);

                // Prepares geometry editor.
                var featureID = Convert.ToInt64(graphic.Attributes["Objectid"], CultureInfo.InvariantCulture);
                SetGeometryEditor(featureID);
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                await new MessageDialog(message).ShowAsync();
            }
        }
コード例 #30
0
        void MyMapView_SpatialReferenceChanged(object sender, EventArgs e)
        {
            MyMapView.SpatialReferenceChanged -= MyMapView_SpatialReferenceChanged;

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

                var height      = viewpointExtent.Height / 4;
                var width       = viewpointExtent.Width / 4;
                var length      = width / 4;
                var center      = viewpointExtent.GetCenter();
                var topLeft     = new MapPoint(center.X - width, center.Y + height, MyMapView.SpatialReference);
                var topRight    = new MapPoint(center.X + width, center.Y + height, MyMapView.SpatialReference);
                var bottomLeft  = new MapPoint(center.X - width, center.Y - height, MyMapView.SpatialReference);
                var bottomRight = new MapPoint(center.X + width, center.Y - height, MyMapView.SpatialReference);

                var redSymbol = new SimpleFillSymbol()
                {
                    Color = Colors.Red
                };
                var blueSymbol = new SimpleFillSymbol()
                {
                    Color = Colors.Blue
                };

                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolygonBox(center, length), Symbol = blueSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolygonBox(topLeft, length), Symbol = redSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolygonBox(topRight, length), Symbol = redSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolygonBox(bottomLeft, length), Symbol = redSymbol
                });
                _graphicsOverlay.Graphics.Add(new Graphic()
                {
                    Geometry = CreatePolygonBox(bottomRight, length), Symbol = redSymbol
                });
            }
            catch (Exception ex)
            {
                var _x = new MessageDialog("Error occurred : " + ex.Message, "Sample Error").ShowAsync();
            }
        }