コード例 #1
0
        private async void BtnZoomToFeatures_Click(object sender, EventArgs e)
        {
            // Create the query parameters
            QueryParameters queryStates = new QueryParameters {
                WhereClause = $"upper(ST) LIKE '%{txtStateEntry.Text.ToUpper()}%'"
            };

            // Get the extent from the query
            Envelope resultExtent = await _myFeatureTable.QueryExtentAsync(queryStates);

            // Return if there is no result (might happen if query is invalid)
            if (resultExtent?.SpatialReference == null)
            {
                return;
            }

            // Create a viewpoint from the extent
            Viewpoint resultViewpoint = new Viewpoint(resultExtent);

            // Zoom to the viewpoint
            await MyMapView.SetViewpointAsync(resultViewpoint);

            // Update the UI
            txtResults.Text = $"Zoomed to features in {txtStateEntry.Text}";
        }
コード例 #2
0
        /// <summary>
        /// Updates the map with the latest layer selection
        /// </summary>
        private async void UpdateMapDisplay(ObservableCollection <LayerDisplayVM> displayList)
        {
            // Remove all existing layers
            MyMapView.Map.OperationalLayers.Clear();

            // Get a list of selected LayerInfos
            IEnumerable <WmsLayerInfo> selectedLayers = displayList.Where(vm => vm.IsEnabled).Select(vm => vm.Info);

            // Return if no layers selected
            if (selectedLayers.Count() < 1)
            {
                return;
            }

            // Create a new WmsLayer from the selected layers
            WmsLayer myLayer = new WmsLayer(selectedLayers);

            // Load the layer
            await myLayer.LoadAsync();

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

            // Update the viewpoint
            await MyMapView.SetViewpointAsync(new Viewpoint(myLayer.FullExtent));
        }
        private async void BtnZoomToFeaturesClick(object sender, RoutedEventArgs e)
        {
            // Create the query parameters.
            QueryParameters queryStates = new QueryParameters()
            {
                WhereClause = $"upper(State) LIKE '%{StateEntry.Text.ToUpper()}%'"
            };

            try
            {
                // Get the extent from the query.
                Envelope resultExtent = await _featureTable.QueryExtentAsync(queryStates);

                // Return if there is no result (might happen if query is invalid).
                if (resultExtent?.SpatialReference == null)
                {
                    return;
                }

                // Create a viewpoint from the extent.
                Viewpoint resultViewpoint = new Viewpoint(resultExtent);

                // Zoom to the viewpoint.
                await MyMapView.SetViewpointAsync(resultViewpoint);

                // Update the UI.
                ResultView.Text       = $"Zoomed to features in {StateEntry.Text}";
                ResultView.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.ToString(), "Error").ShowAsync();
            }
        }
        /// <summary>
        /// Updates the map with the latest layer selection.
        /// </summary>
        private async void UpdateMapDisplay(ObservableCollection <LayerDisplayVM> displayList)
        {
            // Remove all existing layers.
            MyMapView.Map.OperationalLayers.Clear();

            // Get a list of selected LayerInfos.
            List <WmsLayerInfo> selectedLayers = displayList.Where(vm => vm.IsEnabled).Select(vm => vm.Info).ToList();

            // Return if no layers selected.
            if (!selectedLayers.Any())
            {
                return;
            }

            // Create a new WmsLayer from the selected layers.
            WmsLayer myLayer = new WmsLayer(selectedLayers);

            try
            {
                // Load the layer.
                await myLayer.LoadAsync();

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

                // Update the viewpoint.
                await MyMapView.SetViewpointAsync(new Viewpoint(myLayer.FullExtent));
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }
コード例 #5
0
        private async void Initialize()
        {
            // Create a new map
            MyMapView.Map = new Map(Basemap.CreateLightGrayCanvas());

            // Get the full path
            string geoPackagePath = GetGeoPackagePath();

            // Open the GeoPackage
            GeoPackage myGeoPackage = await GeoPackage.OpenAsync(geoPackagePath);

            // Read the raster images and get the first one
            Raster gpkgRaster = myGeoPackage.GeoPackageRasters.FirstOrDefault();

            // Make sure an image was found in the package
            if (gpkgRaster == null)
            {
                return;
            }

            // Create a layer to show the raster
            RasterLayer newLayer = new RasterLayer(gpkgRaster);
            await newLayer.LoadAsync();

            // Set the viewpoint
            await MyMapView.SetViewpointAsync(new Viewpoint(newLayer.FullExtent));

            // Add the image as a raster layer to the map (with default symbology)
            MyMapView.Map.OperationalLayers.Add(newLayer);
        }
        private async void BtnZoomToFeatures_Click(object sender, EventArgs e)
        {
            // Create the query parameters.
            QueryParameters queryStates = new QueryParameters {
                WhereClause = $"upper(State) LIKE '%{txtStateEntry.Text.ToUpper()}%'"
            };

            try
            {
                // Get the extent from the query.
                Envelope resultExtent = await _featureTable.QueryExtentAsync(queryStates);

                // Return if there is no result (might happen if query is invalid).
                if (resultExtent?.SpatialReference == null)
                {
                    return;
                }

                // Create a viewpoint from the extent.
                Viewpoint resultViewpoint = new Viewpoint(resultExtent);

                // Zoom to the viewpoint.
                await MyMapView.SetViewpointAsync(resultViewpoint);

                // Update the UI.
                txtResults.Text = $"Zoomed to features in {txtStateEntry.Text}";
            }
            catch (Exception ex)
            {
                await((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
        private async void BtnZoomToFeaturesClick(object sender, RoutedEventArgs e)
        {
            // Create the query parameters.
            QueryParameters queryStates = new QueryParameters()
            {
                WhereClause = string.Format("upper(ST) LIKE '%{0}%'", StateTextbox.Text.ToUpper())
            };

            // Get the extent from the query.
            Envelope resultExtent = await _myFeatureTable.QueryExtentAsync(queryStates);

            // Return if there is no result (might happen if query is invalid).
            if (resultExtent == null || resultExtent.SpatialReference == null)
            {
                ResultsTextbox.Text = "No results. Search for an abbreviated name (e.g. NH).";
                return;
            }

            // Create a viewpoint from the extent.
            Viewpoint resultViewpoint = new Viewpoint(resultExtent);

            // Zoom to the viewpoint.
            await MyMapView.SetViewpointAsync(resultViewpoint);

            // Update the UI.
            ResultsTextbox.Text = string.Format("Zoomed to features in {0}", StateTextbox.Text);
        }
コード例 #8
0
        private async void BtnZoomToFeaturesClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Create the query parameters.
                QueryParameters queryStates = new QueryParameters {
                    WhereClause = $"upper(State) LIKE '%{StateTextbox.Text}%'"
                };

                // Get the extent from the query.
                Envelope resultExtent = await _featureTable.QueryExtentAsync(queryStates);

                // Return if there is no result (might happen if query is invalid).
                if (resultExtent?.SpatialReference == null)
                {
                    ResultsTextbox.Text = "No results. Search for an abbreviated name (e.g. NH).";
                    return;
                }

                // Create a viewpoint from the extent.
                Viewpoint resultViewpoint = new Viewpoint(resultExtent);

                // Zoom to the viewpoint.
                await MyMapView.SetViewpointAsync(resultViewpoint);

                // Update the UI.
                ResultsTextbox.Text = $"Zoomed to features in {StateTextbox.Text}";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
        }
コード例 #9
0
        private async Task Initialize()
        {
            // Handle the login to the feature service.
            AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(async(info) =>
            {
                try
                {
                    // WARNING: Never hardcode login information in a production application. This is done solely for the sake of the sample.
                    string sampleServer7User = "******";
                    string sampleServer7Pass = "******";
                    return(await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri, sampleServer7User, sampleServer7Pass));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    return(null);
                }
            });

            try
            {
                // Create a map.
                MyMapView.Map = new Map(BasemapStyle.ArcGISStreets);

                // Populate the combo boxes.
                AccessBox.ItemsSource = new List <VersionAccess> {
                    VersionAccess.Public, VersionAccess.Protected, VersionAccess.Private
                };
                DamageBox.ItemsSource = new List <string> {
                    "Destroyed", "Inaccessible", "Major", "Minor", "Affected"
                };

                // Create and load a service geodatabase.
                _serviceGeodatabase = new ServiceGeodatabase(new Uri("https://sampleserver7.arcgisonline.com/server/rest/services/DamageAssessment/FeatureServer/0"));
                await _serviceGeodatabase.LoadAsync();

                // When the service geodatabase has loaded get the default version name.
                CurrentVersionLabel.Content = $"Current version: {_serviceGeodatabase.DefaultVersionName}";

                // Get the service feature table from the service geodatabase.
                _featureTable = _serviceGeodatabase.GetTable(0);

                // Create a feature layer from the service feature table and add it to the map.
                _featureLayer = new FeatureLayer(_featureTable);
                MyMapView.Map.OperationalLayers.Add(_featureLayer);
                await _featureLayer.LoadAsync();

                // When the feature layer has loaded set the viewpoint and update the UI.
                await MyMapView.SetViewpointAsync(new Viewpoint(_featureLayer.FullExtent));

                // Enable the UI.
                CreateVersionButton.IsEnabled = true;
                MyMapView.GeoViewTapped      += MyMapView_GeoViewTapped;
            }
            catch (Exception ex)
            {
                ShowAlert(ex.Message, ex.GetType().Name);
            }
        }
コード例 #10
0
 private async void CollectionLayer_Loaded(object sender, EventArgs e)
 {
     var collectionLayer = sender as FeatureCollectionLayer;
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         MyMapView.SetViewpointAsync(new Viewpoint(collectionLayer.FullExtent));
     });
 }
コード例 #11
0
        private async void OnViewpointsClicked(object sender, EventArgs e)
        {
            try
            {
                // Show sheet and get title from the selection
                string selectedMapTitle =
                    await((Page)Parent).DisplayActionSheet("Select viewpoint", "Cancel", null, titles);

                // If selected cancel do nothing
                if (selectedMapTitle == "Cancel")
                {
                    return;
                }

                switch (selectedMapTitle)
                {
                case "Geometry":

                    // Set Viewpoint using Redlands envelope defined above and a padding of 20
                    await MyMapView.SetViewpointGeometryAsync(RedlandsEnvelope, 20);

                    break;

                case "Center & Scale":

                    // Set Viewpoint so that it is centered on the London coordinates defined above
                    await MyMapView.SetViewpointCenterAsync(LondonCoords);

                    // Set the Viewpoint scale to match the specified scale
                    await MyMapView.SetViewpointScaleAsync(LondonScale);

                    break;

                case "Animate":

                    // Navigate to full extent of the first baselayer before animating to specified geometry
                    await MyMapView.SetViewpointAsync(
                        new Viewpoint(MyMapView.Map.Basemap.BaseLayers.First().FullExtent));

                    // Create a new Viewpoint using the specified geometry
                    Viewpoint viewpoint = new Viewpoint(EdinburghEnvelope);

                    // Set Viewpoint of MapView to the Viewpoint created above and animate to it using a timespan of 5 seconds
                    await MyMapView.SetViewpointAsync(viewpoint, TimeSpan.FromSeconds(5));

                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
コード例 #12
0
        private async void OnButtonClick(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get .Content from the selected item
                Button myButton         = (Button)sender;
                string selectedMapTitle = myButton.Content.ToString();

                switch (selectedMapTitle)
                {
                case "Geometry":

                    // Set Viewpoint using Redlands envelope defined above and a padding of 20
                    await MyMapView.SetViewpointGeometryAsync(_redlandsEnvelope, 20);

                    break;

                case "Center and Scale":

                    // Set Viewpoint so that it is centered on the London coordinates defined above
                    await MyMapView.SetViewpointCenterAsync(_londonCoords);

                    // Set the Viewpoint scale to match the specified scale
                    await MyMapView.SetViewpointScaleAsync(_londonScale);

                    break;

                case "Animate":

                    // Navigate to full extent of the first baselayer before animating to specified geometry
                    await MyMapView.SetViewpointAsync(
                        new Viewpoint(MyMapView.Map.Basemap.BaseLayers.First().FullExtent));

                    // Create a new Viewpoint using the specified geometry
                    Viewpoint viewpoint = new Viewpoint(_edinburghEnvelope);

                    // Set Viewpoint of MapView to the Viewpoint created above and animate to it using a timespan of 5 seconds
                    await MyMapView.SetViewpointAsync(viewpoint, TimeSpan.FromSeconds(5));

                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog2(ex.ToString(), "Error").ShowAsync();
            }
        }
コード例 #13
0
        private async void Initialize()
        {
            // Assign a new map to the MapView
            MyMapView.Map = new Map
            {
                // Set the basemap to Streets
                Basemap = new Basemap(BasemapStyle.ArcGISStreets)
            };

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

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

                // Get the ArcGIS image service info (metadata) from the image service raster
                ArcGISImageServiceInfo myArcGISImageServiceInfo = myImageServiceRaster.ServiceInfo;

                // Get the full extent envelope of the image service raster (the Charlotte, NC area)
                Envelope myEnvelope = myArcGISImageServiceInfo.FullExtent;

                // Define a new view point from the full extent envelope
                Viewpoint myViewPoint = new Viewpoint(myEnvelope);

                // Zoom to the area of the full extent envelope of the image service raster
                await MyMapView.SetViewpointAsync(myViewPoint);

                // Get the rendering rule info (i.e. definitions of how the image should be drawn) info from the image service raster
                _myReadOnlyListRenderRuleInfos = myArcGISImageServiceInfo.RenderingRuleInfos;

                // Loop through each rendering rule info
                foreach (RenderingRuleInfo myRenderingRuleInfo in _myReadOnlyListRenderRuleInfos)
                {
                    // Get the name of the rendering rule info
                    string myRenderingRuleName = myRenderingRuleInfo.Name;

                    // Add the name of the rendering rule info into the list of names
                    _names.Add(myRenderingRuleName);
                }

                // Call the function to display the image service raster based up on user choice of rendering rules
                await ChangeRenderingRuleAsync();
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }
        private async void Initialize()
        {
            // Assign a new map to the MapView
            MyMapView.Map = new Map
            {
                // Set the basemap to Streets
                Basemap = new Basemap(BasemapStyle.ArcGISStreets)
            };

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

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

                // Get the ArcGIS image service info (metadata) from the image service raster
                ArcGISImageServiceInfo myArcGISImageServiceInfo = myImageServiceRaster.ServiceInfo;

                // Get the full extent envelope of the image service raster (the Charlotte, NC area)
                Envelope myEnvelope = myArcGISImageServiceInfo.FullExtent;

                // Define a new view point from the full extent envelope
                Viewpoint myViewPoint = new Viewpoint(myEnvelope);

                // Zoom to the area of the full extent envelope of the image service raster
                await MyMapView.SetViewpointAsync(myViewPoint);

                // Get the rendering rule info (i.e. definitions of how the image should be drawn) info from the image service raster
                _myReadOnlyListRenderRuleInfos = myArcGISImageServiceInfo.RenderingRuleInfos;

                // Loop through each rendering rule info
                foreach (RenderingRuleInfo myRenderingRuleInfo in _myReadOnlyListRenderRuleInfos)
                {
                    // Get the name of the rendering rule info
                    string myRenderingRuleName = myRenderingRuleInfo.Name;

                    // Add the name of the rendering rule info to the combo box
                    RenderingRuleChooser.Items.Add(myRenderingRuleName);
                }

                // Set the combo box index to the first rendering rule info name
                RenderingRuleChooser.SelectedIndex = 0;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
コード例 #15
0
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Provide Map to the MapView
            MyMapView.Map = myMap;

            // Create geometry for the center of the map
            MapPoint centerGeometry = new MapPoint(-13549402.587055, 4397264.96879385, SpatialReference.Create(3857));

            // Set the map's viewpoint to highlight the desired content
            await MyMapView.SetViewpointAsync(new Viewpoint(centerGeometry, 201555));

            // Get the path to the geodatabase
            string geodbFilePath = GetGeodatabasePath();

            // Load the geodatabase from local storage
            Geodatabase baseGeodatabase = await Geodatabase.OpenAsync(geodbFilePath);

            // Get the path to the symbol dictionary
            string symbolFilepath = GetStyleDictionaryPath();

            // Load the symbol dictionary from local storage
            //     Note that the type of the symbol definition must be explicitly provided along with the file name
            DictionarySymbolStyle symbolStyle = await DictionarySymbolStyle.OpenAsync("mil2525d", symbolFilepath);

            // Add geodatabase features to the map, using the defined symbology
            foreach (FeatureTable table in baseGeodatabase.GeodatabaseFeatureTables)
            {
                // Load the table
                await table.LoadAsync();

                // Create the feature layer from the table
                FeatureLayer myLayer = new FeatureLayer(table);

                // Load the layer
                await myLayer.LoadAsync();

                // Create a Dictionary Renderer using the DictionarySymbolStyle
                DictionaryRenderer dictRenderer = new DictionaryRenderer(symbolStyle);

                // Apply the dictionary renderer to the layer
                myLayer.Renderer = dictRenderer;

                // Add the layer to the map
                myMap.OperationalLayers.Add(myLayer);
            }
        }
コード例 #16
0
        private void LocationDisplay_LocationChanged(object sender, Esri.ArcGISRuntime.Location.Location e)
        {
            // Return if position is null; event is called with null position when location display is turned on
            if (e.Position == null) { return; }

            // Unsubscribe to the event (only want to zoom once)
            ((LocationDisplay)sender).LocationChanged -= LocationDisplay_LocationChanged;

            // Needed because the event is called from a background thread, but the code is manipulating UI
            Dispatcher.Invoke(() =>
            {
                // Zoom to the location
                MyMapView.SetViewpointAsync(new Viewpoint(e.Position, 100000));
            });
        }
コード例 #17
0
        private async Task Initialize()
        {
            // Create a raster layer using an image service.
            _imageServiceRaster = new ImageServiceRaster(new Uri("https://sampleserver7.arcgisonline.com/server/rest/services/amberg_germany/ImageServer"));
            RasterLayer rasterLayer = new RasterLayer(_imageServiceRaster);
            await rasterLayer.LoadAsync();

            // Create a map with the raster layer.
            MyMapView.Map = new Map(BasemapStyle.ArcGISTopographic);
            MyMapView.Map.OperationalLayers.Add(rasterLayer);
            await MyMapView.SetViewpointAsync(new Viewpoint(rasterLayer.FullExtent));

            // Populate the combo box.
            MosaicRulesBox.ItemsSource   = _mosaicRules.Keys;
            MosaicRulesBox.SelectedIndex = 0;
        }
コード例 #18
0
        private async void Initialize()
        {
            // Initialize the map with an oceans basemap
            MyMapView.Map = new Map(BasemapStyle.ArcGISOceans);

            // Get the path to the ENC Exchange Set
            string encPath = DataManager.GetDataFolder("9d2987a825c646468b3ce7512fb76e2d", "ExchangeSetwithoutUpdates", "ENC_ROOT",
                                                       "CATALOG.031");

            // Create the Exchange Set
            // Note: this constructor takes an array of paths because so that update sets can be loaded alongside base data
            EncExchangeSet myEncExchangeSet = new EncExchangeSet(encPath);

            try
            {
                // Wait for the exchange set to load
                await myEncExchangeSet.LoadAsync();

                // Store a list of data set extent's - will be used to zoom the mapview to the full extent of the Exchange Set
                List <Envelope> dataSetExtents = new List <Envelope>();

                // Add each data set as a layer
                foreach (EncDataset myEncDataSet in myEncExchangeSet.Datasets)
                {
                    EncLayer myEncLayer = new EncLayer(new EncCell(myEncDataSet));

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

                    // Wait for the layer to load
                    await myEncLayer.LoadAsync();

                    // Add the extent to the list of extents
                    dataSetExtents.Add(myEncLayer.FullExtent);
                }

                // Use the geometry engine to compute the full extent of the ENC Exchange Set
                Envelope fullExtent = GeometryEngine.CombineExtents(dataSetExtents);

                // Set the viewpoint
                await MyMapView.SetViewpointAsync(new Viewpoint(fullExtent));
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }
コード例 #19
0
        private async void doWheelZoomSim(int seconds = 3)
        {
            // Create a new Viewpoint using the specified geometry
            Viewpoint viewpoint = new Viewpoint(_Oslo);


            try
            {
                // Set Viewpoint of MapView to the Viewpoint created above and animate to it using a timespan of 5 seconds
                _time = DateTime.Now;
                await MyMapView.SetViewpointAsync(viewpoint, TimeSpan.FromSeconds(seconds));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error");
            }
        }
コード例 #20
0
        private async void CalculateViewshed(MapPoint location)
        {
            // Get the file name
            MapPoint Point = (MapPoint)GeometryEngine.Project(location, SpatialReferences.Wgs84);

            RunCmd(Point.X, Point.Y);
            string filepath = "C:\\Users\\zia13430\\dest.tif";

            // Load the raster file
            Raster myRasterFile = new Raster(filepath);

            // Create the layer
            RasterLayer myRasterLayer = new RasterLayer(myRasterFile);

            // Create a color map where values 0-149 are red and 150-249 are yellow.
            IEnumerable <Color> colors = new int[250]
                                         .Select((c, i) => i < 150 ? Color.Red : Color.Red);

            // Create a colormap renderer.
            ColormapRenderer colormapRenderer = new ColormapRenderer(colors);


            // Set the colormap renderer on the raster layer.
            myRasterLayer.Renderer = colormapRenderer;
            myRasterLayer.Opacity  = 0.6;
            await MyMapView.SetViewpointAsync(new Viewpoint(Point, 75000), TimeSpan.FromSeconds(1));

            //myMap.InitialViewpoint = ;

            // Add the layer to the map
            myMap.OperationalLayers.Clear();
            myMap.OperationalLayers.Add(myRasterLayer);

            try
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred. " + ex.ToString(), "Sample error");
            }
            finally
            {
                // Indicate that the geoprocessing is not running
                SetBusy(false);
            }
        }
コード例 #21
0
        private async void OnSetViewCommand()
        {
            var center = GetRandomPoint();
            var scale  = 625;

            if ((MyMapView.MapScale < 200000))
            {
                scale = 1000000;
            }
            if (UseAnimation)
            {
                await MyMapView.SetViewpointAsync(new Viewpoint(center, scale));
            }
            else
            {
                await MyMapView.SetViewpointAsync(new Viewpoint(center, scale), TimeSpan.Zero);
            }
        }
コード例 #22
0
        private async void OnButtonClick(object sender, RoutedEventArgs e)
        {
            // Get content from the selected item
            Button myButton = sender as Button;

            switch (myButton.Content.ToString())
            {
            case "Geometry":

                // Set Viewpoint using Redlands envelope defined above and a padding of 20
                await MyMapView.SetViewpointGeometryAsync(_redlandsEnvelope, 20);

                break;

            case "Center and Scale":

                // Set Viewpoint so that it is centered on the London coordinates defined above
                await MyMapView.SetViewpointCenterAsync(_londonCoords);

                // Set the Viewpoint scale to match the specified scale
                await MyMapView.SetViewpointScaleAsync(_londonScale);

                break;

            case "Animate":

                // Navigate to full extent of the first baselayer before animating to specified geometry
                await MyMapView.SetViewpointAsync(
                    new Viewpoint(Basemap.FullExtent));

                // Create a new Viewpoint using the specified geometry
                var viewpoint = new Viewpoint(_edinburghEnvelope);

                // Set Viewpoint of MapView to the Viewpoint created above and animate to it using a timespan of 5 seconds
                await MyMapView.SetViewpointAsync(viewpoint, TimeSpan.FromSeconds(5));

                break;

            default:
                break;
            }
        }
コード例 #23
0
        private async void Initialize()
        {
            // Set up the basemap.
            MyMapView.Map = new Map(Basemap.CreateDarkGrayCanvasVector());

            // Create the dataset.
            KmlDataset dataset = new KmlDataset(new Uri("https://www.wpc.ncep.noaa.gov/kml/noaa_chart/WPC_Day1_SigWx.kml"));

            // Create the layer from the dataset.
            _forecastLayer = new KmlLayer(dataset);

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

            // Zoom to the extent of the United States.
            await MyMapView.SetViewpointAsync(new Viewpoint(_usEnvelope));

            // Listen for taps to identify features.
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
        }
        private void SetExtent()
        {
            // Get all of the graphics contained in the graphics overlay
            GraphicCollection myGraphicCollection = _overlay.Graphics;

            // Create a new envelope builder using the same spatial reference as the graphics
            EnvelopeBuilder myEnvelopeBuilder = new EnvelopeBuilder(SpatialReferences.Wgs84);

            // Loop through each graphic in the graphic collection
            foreach (Graphic oneGraphic in myGraphicCollection)
            {
                // Union the extent of each graphic in the envelope builder
                myEnvelopeBuilder.UnionOf(oneGraphic.Geometry.Extent);
            }

            // Expand the envelope builder by 30%
            myEnvelopeBuilder.Expand(1.3);

            // Adjust the viewable area of the map to encompass all of the graphics in the
            // graphics overlay plus an extra 30% margin for better viewing
            MyMapView.SetViewpointAsync(new Viewpoint(myEnvelopeBuilder.Extent));
        }
        private async void Initialize()
        {
            // Initialize the map with an oceans basemap
            MyMapView.Map = new Map(Basemap.CreateOceans());

            // Get the path to the ENC Exchange Set
            string encPath = GetEncPath();

            // Create the cell and layer
            EncLayer encLayer = new EncLayer(new EncCell(encPath));

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

            // Wait for the layer to load
            await encLayer.LoadAsync();

            // Set the viewpoint
            await MyMapView.SetViewpointAsync(new Viewpoint(encLayer.FullExtent));

            // Subscribe to tap events (in order to use them to identify and select features)
            MyMapView.GeoViewTapped += MyMapView_GeoViewTapped;
        }
        private async void Initialize()
        {
            // Create a new map
            MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray);

            // Get the full path
            string geoPackagePath = GetGeoPackagePath();

            try
            {
                // Open the GeoPackage
                GeoPackage myGeoPackage = await GeoPackage.OpenAsync(geoPackagePath);

                // Read the raster images and get the first one
                Raster gpkgRaster = myGeoPackage.GeoPackageRasters.FirstOrDefault();

                // Make sure an image was found in the package
                if (gpkgRaster == null)
                {
                    return;
                }

                // Create a layer to show the raster
                RasterLayer newLayer = new RasterLayer(gpkgRaster);
                await newLayer.LoadAsync();

                // Set the viewpoint
                await MyMapView.SetViewpointAsync(new Viewpoint(newLayer.FullExtent));

                // Add the image as a raster layer to the map (with default symbology)
                MyMapView.Map.OperationalLayers.Add(newLayer);
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Error", e.ToString(), "OK");
            }
        }
コード例 #27
0
        private async void OnAnalyzeHotspotsClicked(object sender, RoutedEventArgs e)
        {
            // Clear any existing results
            MyMapView.Map.OperationalLayers.Clear();

            // Show the waiting indication
            ShowBusyOverlay();

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

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

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

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

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

            // 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)
                {
                    MessageBox.Show("Executing geoprocessing failed. " + _hotspotJob.Error.Message, "Geoprocessing error");
                }
                else
                {
                    MessageBox.Show("An error occurred. " + ex, "Sample error");
                }
            }
            finally
            {
                // Remove the waiting
                ShowBusyOverlay(false);
            }
        }
コード例 #28
0
        private async void Initialize()
        {
            try
            {
                // Disable the UI.
                FilterOptions.Visibility = Visibility.Collapsed;

                // 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.Visibility = Visibility.Visible;
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message, ex.GetType().Name).ShowAsync();
            }
            finally
            {
                LoadingBar.Visibility = Visibility.Collapsed;
            }
        }
        private async void Initialize()
        {
            try
            {
                // Create the utility network.
                _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServerUrl));

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

                // Get all of the edges and junctions in the network.
                IEnumerable <UtilityNetworkSource> edges     = _utilityNetwork.Definition.NetworkSources.Where(n => n.SourceType == UtilityNetworkSourceType.Edge);
                IEnumerable <UtilityNetworkSource> junctions = _utilityNetwork.Definition.NetworkSources.Where(n => n.SourceType == UtilityNetworkSourceType.Junction);

                // Add all edges that are not subnet lines to the map.
                foreach (UtilityNetworkSource source in edges)
                {
                    if (source.SourceUsageType != UtilityNetworkSourceUsageType.SubnetLine && source.FeatureTable != null)
                    {
                        MyMapView.Map.OperationalLayers.Add(new FeatureLayer(source.FeatureTable));
                    }
                }

                // Add all junctions to the map.
                foreach (UtilityNetworkSource source in junctions)
                {
                    if (source.FeatureTable != null)
                    {
                        MyMapView.Map.OperationalLayers.Add(new FeatureLayer(source.FeatureTable));
                    }
                }

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

                // Symbols for the associations.
                Symbol attachmentSymbol   = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, Color.Green, 5d);
                Symbol connectivitySymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, Color.Red, 5d);

                // Create a renderer for the associations.
                var attachmentValue   = new UniqueValue("Attachment", string.Empty, attachmentSymbol, UtilityAssociationType.Attachment.ToString());
                var connectivityValue = new UniqueValue("Connectivity", string.Empty, connectivitySymbol, UtilityAssociationType.Connectivity.ToString());
                _associationsOverlay.Renderer = new UniqueValueRenderer(new List <string> {
                    "AssociationType"
                }, new List <UniqueValue> {
                    attachmentValue, connectivityValue
                }, string.Empty, null);


                // Populate the legend in the UI.
                RuntimeImage attachmentSwatch = await attachmentSymbol.CreateSwatchAsync();

                AttachmentImage.Source = await Esri.ArcGISRuntime.Xamarin.Forms.RuntimeImageExtensions.ToImageSourceAsync(attachmentSwatch);

                RuntimeImage connectSwatch = await connectivitySymbol.CreateSwatchAsync();

                ConnectivityImage.Source = await Esri.ArcGISRuntime.Xamarin.Forms.RuntimeImageExtensions.ToImageSourceAsync(connectSwatch);

                // Set the starting viewpoint.
                await MyMapView.SetViewpointAsync(InitialViewpoint);

                // Add the associations in the starting viewpoint.
                AddAssociations();
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert(ex.GetType().Name, ex.Message, "OK");
            }
        }
        private async void Initialize()
        {
            // As of ArcGIS Enterprise 10.8.1, using utility network functionality requires a licensed user. The following login for the sample server is licensed to perform utility network operations.
            AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(async(info) =>
            {
                try
                {
                    // WARNING: Never hardcode login information in a production application. This is done solely for the sake of the sample.
                    string sampleServer7User = "******";
                    string sampleServer7Pass = "******";

                    return(await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri, sampleServer7User, sampleServer7Pass));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    return(null);
                }
            });

            try
            {
                // Create the utility network.
                _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServerUrl));

                // Create the map.
                MyMapView.Map = new Map(BasemapStyle.ArcGISTopographic);

                // Get all of the edges and junctions in the network.
                IEnumerable <UtilityNetworkSource> edges     = _utilityNetwork.Definition.NetworkSources.Where(n => n.SourceType == UtilityNetworkSourceType.Edge);
                IEnumerable <UtilityNetworkSource> junctions = _utilityNetwork.Definition.NetworkSources.Where(n => n.SourceType == UtilityNetworkSourceType.Junction);

                // Add all edges that are not subnet lines to the map.
                foreach (UtilityNetworkSource source in edges)
                {
                    if (source.SourceUsageType != UtilityNetworkSourceUsageType.SubnetLine && source.FeatureTable != null)
                    {
                        MyMapView.Map.OperationalLayers.Add(new FeatureLayer(source.FeatureTable));
                    }
                }

                // Add all junctions to the map.
                foreach (UtilityNetworkSource source in junctions)
                {
                    if (source.FeatureTable != null)
                    {
                        MyMapView.Map.OperationalLayers.Add(new FeatureLayer(source.FeatureTable));
                    }
                }

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

                // Symbols for the associations.
                Symbol attachmentSymbol   = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, Color.Green, 5d);
                Symbol connectivitySymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dot, Color.Red, 5d);

                // Create a renderer for the associations.
                var attachmentValue   = new UniqueValue("Attachment", string.Empty, attachmentSymbol, UtilityAssociationType.Attachment.ToString());
                var connectivityValue = new UniqueValue("Connectivity", string.Empty, connectivitySymbol, UtilityAssociationType.Connectivity.ToString());
                _associationsOverlay.Renderer = new UniqueValueRenderer(new List <string> {
                    "AssociationType"
                }, new List <UniqueValue> {
                    attachmentValue, connectivityValue
                }, string.Empty, null);

                // Populate the legend in the UI.
                Dictionary <UtilityAssociationType, System.Windows.Media.ImageSource> legend;
                legend = new Dictionary <UtilityAssociationType, System.Windows.Media.ImageSource>();

                RuntimeImage attachmentSwatch = await attachmentSymbol.CreateSwatchAsync();

                legend[UtilityAssociationType.Attachment] = await attachmentSwatch?.ToImageSourceAsync();

                RuntimeImage connectSwatch = await connectivitySymbol.CreateSwatchAsync();

                legend[UtilityAssociationType.Connectivity] = await connectSwatch?.ToImageSourceAsync();

                AssociationLegend.ItemsSource = legend;

                // Set the starting viewpoint.
                await MyMapView.SetViewpointAsync(InitialViewpoint);

                // Add the associations in the starting viewpoint.
                AddAssociations();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }