private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(BasemapType.Topographic, 34.056, -117.196, 4);

            // Create uri to the used feature service
            var serviceUri = new Uri(
                "http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0");

            // Initialize a new feature layer
            ServiceFeatureTable myFeatureTable = new ServiceFeatureTable(serviceUri);
            FeatureLayer myFeatureLayer = new FeatureLayer(myFeatureTable);

            // Make sure that the feature layer gets loaded
            await myFeatureLayer.LoadAsync();

            // Add the feature layer to the Map
            myMap.OperationalLayers.Add(myFeatureLayer);

            // Provide used Map to the MapView
            _myMapView.Map = myMap;

            // Hook up the DrawStatusChanged event
            _myMapView.DrawStatusChanged += OnMapViewDrawStatusChanged;

            // Animate the activity spinner
            _activityIndicator.StartAnimating();
        }
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create a MapPoint the map should zoom to
            MapPoint mapPoint = new MapPoint(
                -13630484, 4545415, SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(mapPoint, 90000);

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

            // Create the uri for the feature service
            Uri featureServiceUri = new Uri(
                "https://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Initialize feature table using a url to feature server url
            ServiceFeatureTable featureTable = new ServiceFeatureTable(featureServiceUri);

            // Initialize a new feature layer based on the feature table
            _featureLayer = new FeatureLayer(featureTable);

            //Add the feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);

            // TODO: https://github.com/Esri/arcgis-runtime-samples-xamarin/issues/96
            if (Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Other)
            {
                await _featureLayer.RetryLoadAsync();
            }
        }
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map location
            MapPoint initialLocation = new MapPoint(
                -13630484, 4545415, SpatialReferences.WebMercator);
            myMap.InitialViewpoint = new Viewpoint(initialLocation, 500000);

            // Create uri to the used feature service
            var serviceUri = new Uri(
               "http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Create feature table for the incident feature service
            _incidentsFeatureTable = new ServiceFeatureTable(serviceUri);

            // Define the request mode
            _incidentsFeatureTable.FeatureRequestMode = FeatureRequestMode.ManualCache;

            // When feature table is loaded, populate data
            _incidentsFeatureTable.LoadStatusChanged += OnLoadedPopulateData;

            // Create FeatureLayer that uses the created table
            FeatureLayer incidentsFeatureLayer = new FeatureLayer(_incidentsFeatureTable);

            // Add created layer to the map
            myMap.OperationalLayers.Add(incidentsFeatureLayer);

            // Assign the map to the MapView
            _myMapView.Map = myMap;
        }
        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map area
            Envelope initialLocation = new Envelope(
                -1.30758164047166E7, 4014771.46954516, -1.30730056797177E7, 4016869.78617381,
                SpatialReferences.WebMercator);
            myMap.InitialViewpoint = new Viewpoint(initialLocation);

            // Create uri to the used feature service
            var serviceUri = new Uri(
               "http://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0");

            // Create feature table for the pools feature service
            ServiceFeatureTable poolsFeatureTable = new ServiceFeatureTable(serviceUri);

            // Define the request mode
            poolsFeatureTable.FeatureRequestMode = FeatureRequestMode.OnInteractionNoCache;

            // Create FeatureLayer that uses the created table
            FeatureLayer poolsFeatureLayer = new FeatureLayer(poolsFeatureTable);

            // Add created layer to the map
            myMap.OperationalLayers.Add(poolsFeatureLayer);

            // Assign the map to the MapView
            MyMapView.Map = myMap;
        }
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create a mappoint the map should zoom to
            MapPoint mapPoint = new MapPoint(-13630484, 4545415, SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(mapPoint, 90000);

            // Provide used Map to the MapView
            _myMapView.Map = myMap;

            // Create the uri for the feature service
            Uri featureServiceUri = new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/SF311/FeatureServer/0");

            // Initialize feature table using a url to feature server url
            ServiceFeatureTable featureTable = new ServiceFeatureTable(featureServiceUri);

            // Initialize a new feature layer based on the feature table
            _featureLayer = new FeatureLayer(featureTable);

            //Add the feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);
        }
        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map location
            MapPoint initialLocation = new MapPoint(
                -11000000, 5000000, SpatialReferences.WebMercator);
                myMap.InitialViewpoint = new Viewpoint(initialLocation, 100000000);

            // Create feature table using a url
            _featureTable = new ServiceFeatureTable(new Uri(_statesUrl));

            // Create feature layer using this feature table
            _featureLayer = new FeatureLayer(_featureTable);

            // Set the Opacity of the Feature Layer
            _featureLayer.Opacity = 0.6;

            // Create a new renderer for the States Feature Layer
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid, Color.Black, 1); 
            SimpleFillSymbol fillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, Color.Yellow, lineSymbol);

            // Set States feature layer renderer
            _featureLayer.Renderer = new SimpleRenderer(fillSymbol);

            // Add feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);

            // Assign the map to the MapView
            _myMapView.Map = myMap;
        }
        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create uri to the used feature service
            var serviceUri = new Uri(
                "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3");

            // Create service feature table
            ServiceFeatureTable statesFeatureTable = new ServiceFeatureTable(serviceUri);

            // Create a new feature layer using the service feature table
            FeatureLayer statesLayer = new FeatureLayer(statesFeatureTable);

            // Create a new unique value renderer
            UniqueValueRenderer regionRenderer = new UniqueValueRenderer();

            // Add the "SUB_REGION" field to the renderer
            regionRenderer.FieldNames.Add("SUB_REGION");

            // Define a line symbol to use for the region fill symbols
            SimpleLineSymbol stateOutlineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid, System.Drawing.Color.White, 0.7);

            // Define distinct fill symbols for a few regions (use the same outline symbol)
            SimpleFillSymbol pacificFillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, System.Drawing.Color.Blue, stateOutlineSymbol);
            SimpleFillSymbol mountainFillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, System.Drawing.Color.LawnGreen, stateOutlineSymbol);
            SimpleFillSymbol westSouthCentralFillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, System.Drawing.Color.SandyBrown, stateOutlineSymbol);

            // Add values to the renderer: define the label, description, symbol, and attribute value for each
            regionRenderer.UniqueValues.Add(
                new UniqueValue("Pacific", "Pacific Region", pacificFillSymbol, "Pacific"));
            regionRenderer.UniqueValues.Add(
                new UniqueValue("Mountain", "Rocky Mountain Region", mountainFillSymbol, "Mountain"));
            regionRenderer.UniqueValues.Add(
                new UniqueValue("West South Central", "West South Central Region", westSouthCentralFillSymbol, "West South Central"));

            // Set the default region fill symbol (transparent with no outline) for regions not explicitly defined in the renderer
            SimpleFillSymbol defaultFillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Null, System.Drawing.Color.Transparent, null);
            regionRenderer.DefaultSymbol = defaultFillSymbol;
            regionRenderer.DefaultLabel = "Other";

            // Apply the unique value renderer to the states layer
            statesLayer.Renderer = regionRenderer;

            // Add created layer to the map
            myMap.OperationalLayers.Add(statesLayer);

            // Assign the map to the MapView
            _myMapView.Map = myMap;

            // Feature table initialization
            statesFeatureTable.RetryLoadAsync();
        }
        private async void Initialize()
        {
            // Create new Map with basemap
            var myMap = new Map(Basemap.CreateTopographic());

            // Create envelope to be used as a target extent for map's initial viewpoint
            Envelope myEnvelope = new Envelope(
                -1131596.019761, 3893114.069099, 3926705.982140, 7977912.461790,
                SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(myEnvelope);

            // Provide used Map to the MapView
            _myMapView.Map = myMap;

            // Create Uri for the feature service
            Uri featureServiceUri = new Uri(
                "http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0");

            // Initialize feature table using a url to feature server url
            var featureTable = new ServiceFeatureTable(featureServiceUri);

            // Initialize a new feature layer based on the feature table
            _featureLayer = new FeatureLayer(featureTable);

            // Set the selection color for feature layer
            _featureLayer.SelectionColor = Color.Cyan;

            // Set the selection width
            _featureLayer.SelectionWidth = 3;

            // Make sure that used feature layer is loaded before we hook into the tapped event
            // This prevents us trying to do selection on the layer that isn't initialized
            await _featureLayer.LoadAsync();

            // Check for the load status. If the layer is loaded then add it to map
            if (_featureLayer.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
            {
                // Add the feature layer to the map
                myMap.OperationalLayers.Add(_featureLayer);

                // Add tap event handler for mapview
                _myMapView.GeoViewTapped += OnMapViewTapped;
            }
        }
示例#9
0
        public async Task GetRedlineCountAsync_CountFeatures_FiveFeaturesFound()
        {
            QueryCountResult results = null;
            Map map = null;

            var table = new ServiceFeatureTable(
                new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer/2"));

            await table.InitializeAsync();
            map = new Map();
            map.Layers.Add(new FeatureLayer(table) { ID = "test" });

            var queryTask = new QueryTask(new Uri(table.ServiceUri));
            results = await queryTask.ExecuteCountAsync(new Query("1=1"));

            //Assert.IsNotNull(map);
            //Assert.IsNotNull(results);
            Assert.AreEqual(5, results.Count);
        }
        private async void Initialize()
        {
            // Hook up the DrawStatusChanged event
            _myMapView.DrawStatusChanged += OnDrawStatusChanged;

            // Create new Map with basemap
            Map myMap = new Map(BasemapType.Topographic, 34.056, -117.196, 4);

            // Create uri to the used feature service
            var serviceUri = new Uri(
                "http://sampleserver6.arcgisonline.com/arcgis/rest/services/DamageAssessment/FeatureServer/0");

            // Initialize a new feature layer
            ServiceFeatureTable myFeatureTable = new ServiceFeatureTable(serviceUri);
            FeatureLayer myFeatureLayer = new FeatureLayer(myFeatureTable);

            // Add the feature layer to the Map
            myMap.OperationalLayers.Add(myFeatureLayer);

            // Provide used Map to the MapView
            _myMapView.Map = myMap;
        }
        private async void GetFeaturesFromQuery()
        {
            // Create a service feature table to get features from
            ServiceFeatureTable featTable = new ServiceFeatureTable(new Uri(FeatureLayerUrl));

            // Create a query to get all features in the table
            QueryParameters queryParams = new QueryParameters();
            queryParams.WhereClause = "1=1";

            // Query the table to get all features
            FeatureQueryResult featureResult = await featTable.QueryFeaturesAsync(queryParams);

            // Create a new feature collection table from the result features
            FeatureCollectionTable collectTable = new FeatureCollectionTable(featureResult);

            // Create a feature collection and add the table
            FeatureCollection featCollection = new FeatureCollection();
            featCollection.Tables.Add(collectTable);

            // Create a layer to display the feature collection, add it to the map's operational layers
            FeatureCollectionLayer featCollectionTable = new FeatureCollectionLayer(featCollection);
            MyMapView.Map.OperationalLayers.Add(featCollectionTable);
        }
        private async void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map area
            Envelope initialLocation = new Envelope(
                -1.30758164047166E7, 4014771.46954516, -1.30730056797177E7, 4016869.78617381,
                SpatialReferences.WebMercator);

            // Set the initial viewpoint for map
            myMap.InitialViewpoint = new Viewpoint(initialLocation);

            // Provide used Map to the MapView
            _myMapView.Map = myMap;

            // Create uri to the used feature service
            var serviceUri = new Uri(
               "http://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0");

            // Initialize feature table using a url to feature server url
            ServiceFeatureTable featureTable = new ServiceFeatureTable(serviceUri);

            // Initialize a new feature layer based on the feature table
            _featureLayer = new FeatureLayer(featureTable);

            // Make sure that the feature layer gets loaded
            await _featureLayer.LoadAsync();

            // Check for the load status. If the layer is loaded then add it to map
            if (_featureLayer.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
            {
                // Add the feature layer to the map
                myMap.OperationalLayers.Add(_featureLayer);
            }
        }
示例#13
0
        public async Task GetRedlineCountAsync_CountFeatures_FiveFeaturesFound()
        {
            await ThreadHelper.Run(async () =>
            {
                QueryCountResult results = null;
                Map map = null;

                var table = new ServiceFeatureTable(
                    new Uri("http://sampleserver6.arcgisonline.com/arcgis/rest/services/Water_Network/FeatureServer/2"));

                await table.InitializeAsync();

                map = new Map();
                map.Layers.Add(new FeatureLayer(table) { ID = "test" });
                
                var queryTask = new QueryTask(new Uri(table.ServiceUri));
                results = await queryTask.ExecuteCountAsync(new Query("1=1"));

                //Assert.IsNotNull(map);
                //Assert.IsNotNull(results);
                Assert.AreEqual(5, results.Count);
                System.Diagnostics.Debug.WriteLine("Results count: " + results.Count.ToString());
            });
        }
示例#14
0
        private async void Initialize()
        {
            // Create a map with a light gray canvas basemap.
            Map sampleMap = new Map(Basemap.CreateLightGrayCanvas());

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

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

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

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

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

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

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

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

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

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

            // Enable the visibility of labels to be seen.
            highwaysFeatureLayer.LabelsEnabled = true;
        }
示例#15
0
        // When a comment is clicked, get the related feature (service request) and select it on the map.
        private async void CommentsListBox_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

            // Get the clicked record (ArcGISFeature) using the list position. If one is not found, return.
            ArcGISFeature selectedComment = _commentFeatures[e.Position] as ArcGISFeature;

            if (selectedComment == null)
            {
                return;
            }

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

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

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

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

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

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

                // Get the first feature from the result. If it's null, warn the user and return.
                ArcGISFeature serviceRequestFeature = result.FirstOrDefault() as ArcGISFeature;
                if (serviceRequestFeature == null)
                {
                    // Report to the user that a related feature was not found, then return.
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                    AlertDialog         alert        = alertBuilder.Create();
                    alert.SetMessage("Related feature not found.");
                    alert.Show();

                    return;
                }

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

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

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

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

                // Add the graphic to the graphics overlay and zoom the map view to its extent.
                _selectedFeaturesOverlay.Graphics.Add(requestGraphic);
                await _myMapView.SetViewpointCenterAsync(serviceRequestPoint, 150000);
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }
示例#16
0
        private async void Initialize()
        {
            try
            {
                // Create a tile cache and load it with the SanFrancisco streets tpk.
                TileCache _tileCache = new TileCache(DataManager.GetDataFolder("e4a398afe9a945f3b0f4dca1e4faccb5", "SanFrancisco.tpkx"));

                // Create the corresponding layer based on the tile cache.
                ArcGISTiledLayer _tileLayer = new ArcGISTiledLayer(_tileCache);

                // Create the basemap based on the tile cache.
                Basemap _sfBasemap = new Basemap(_tileLayer);

                // Create the map with the tile-based basemap.
                Map myMap = new Map(_sfBasemap);

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

                // Create a new symbol for the extent graphic.
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);

                // Create a graphics overlay for the extent graphic and apply a renderer.
                GraphicsOverlay extentOverlay = new GraphicsOverlay
                {
                    Renderer = new SimpleRenderer(lineSymbol)
                };

                // Add graphics overlay to the map view.
                MyMapView.GraphicsOverlays.Add(extentOverlay);

                // Set up an event handler for when the viewpoint (extent) changes.
                MyMapView.ViewpointChanged += MapViewExtentChanged;

                // Create a task for generating a geodatabase (GeodatabaseSyncTask).
                _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

                // Add all layers from the service to the map.
                foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
                {
                    // Create the ServiceFeatureTable for this particular layer.
                    ServiceFeatureTable onlineTable = new ServiceFeatureTable(new Uri(_featureServiceUri + "/" + layer.Id));

                    // Wait for the table to load.
                    await onlineTable.LoadAsync();

                    // Add the layer to the map's operational layers if load succeeds.
                    if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                    {
                        myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                    }
                }

                // Update the extent graphic so that it is valid before user interaction.
                UpdateMapExtent();

                // Enable the generate button now that the sample is ready.
                GenerateButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                ShowStatusMessage(ex.ToString());
            }
        }
示例#17
0
        /// <summary>
        /// Enables attribute editing, submits attribute edit back to the server and refreshes dynamic layer.
        /// </summary>
        private async void ChoiceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ChoiceList.SelectionChanged -= ChoiceList_SelectionChanged;
            var    featureID = (Int64)EditButton.Tag;
            var    selected  = (string)ChoiceList.SelectedItem;
            var    layer     = MyMapView.Map.Layers["PoolPermit"] as ArcGISDynamicMapServiceLayer;
            var    overlay   = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay;
            string message   = null;

            try
            {
                if (table == null)
                {
                    // Creates table based on visible layer of dynamic layer
                    // using FeatureServer specifying has_pool field to enable editing.
                    var id  = layer.VisibleLayers[0];
                    var url = layer.ServiceUri.Replace("MapServer", "FeatureServer");
                    url   = string.Format("{0}/{1}", url, id);
                    table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference);

                    table.OutFields = new OutFields(new string[] { "has_pool" });
                }
                // Retrieves feature identified by ID and updates its attributes.
                var feature = await table.QueryAsync(featureID);

                if (choices != null)
                {
                    var value = choices.FirstOrDefault(item => string.Equals(item.Value, selected)).Key;
                    feature.Attributes["has_pool"] = value;
                    await table.UpdateAsync(feature);
                }
                if (table.HasEdits)
                {
                    // Pushes attribute edits back to the server.
                    var result = await table.ApplyEditsAsync();

                    if (result.UpdateResults == null || result.UpdateResults.Count < 1)
                    {
                        return;
                    }
                    var updateResult = result.UpdateResults[0];
                    if (updateResult.Error != null)
                    {
                        message = updateResult.Error.Message;
                    }
                    // Refreshes layer to reflect attribute edits.
                    layer.Invalidate();
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                overlay.Graphics.Clear();
                SetAttributeEditor();
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                await new MessageDialog(message).ShowAsync();
            }
        }
示例#18
0
        private async void Initialize()
        {
            // Create a map with a light gray canvas basemap.
            Map sampleMap = new Map(Basemap.CreateLightGrayCanvas());

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

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

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

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

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

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

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

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

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

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

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

            // Enable the visibility of labels to be seen.
            districtFeatureLabel.LabelsEnabled = true;
        }
        private void cBoxBaseMaps_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            btnGetParvelAddress.Visibility  = Visibility.Collapsed;
            pnlParcelAddressInfo.Visibility = Visibility.Collapsed;
            btnGetRoute.Visibility          = Visibility.Collapsed;
            txtFrom.Visibility = Visibility.Collapsed;
            txtTo.Visibility   = Visibility.Collapsed;

            Esri.ArcGISRuntime.Controls.Map map = new Esri.ArcGISRuntime.Controls.Map();
            Esri.ArcGISRuntime.Layers.ArcGISTiledMapServiceLayer baseMaplayer = new Esri.ArcGISRuntime.Layers.ArcGISTiledMapServiceLayer();
            baseMaplayer.ServiceUri = "http://services.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer";
            baseMaplayer.ID         = "BaseMap";

            map.Layers.Add(baseMaplayer);

            if (cBoxBaseMaps.SelectedItem.ToString() == "Projects")
            {
                ArcGISDynamicMapServiceLayer layer2 = new ArcGISDynamicMapServiceLayer();
                layer2.ServiceUri = "http://192.168.1.47:6080/arcgis/rest/services/PROJECTS/MapServer";
                layer2.ID         = "Projects";
                map.Layers.Add(layer2);
            }
            else if (cBoxBaseMaps.SelectedItem.ToString() == "Feature")
            {
                btnGetParvelAddress.Visibility  = Visibility.Visible;
                pnlParcelAddressInfo.Visibility = Visibility.Visible;
                ServiceFeatureTable featureTable = new ServiceFeatureTable();
                featureTable.ServiceUri = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/PoolPermits/FeatureServer/0";
                featureTable.Where      = "has_pool = 1 AND pool_permit = 0";
                FeatureLayer   layer    = new FeatureLayer(featureTable);
                SimpleRenderer renderer = new SimpleRenderer();
                renderer.Symbol = new SimpleFillSymbol()
                {
                    Color = Color.FromRgb(66, 134, 244), Style = SimpleFillStyle.DiagonalCross
                };
                layer.Renderer = renderer;

                map.InitialViewpoint = new Viewpoint(new Envelope(-13075816.40, 4014771.46, -13073005.67, 4016869.78));

                layer.ID = "Feature";
                map.Layers.Add(layer);
            }
            else if (cBoxBaseMaps.SelectedItem.ToString() == "Route")
            {
                btnGetRoute.Visibility = Visibility.Visible;
                txtFrom.Visibility     = Visibility.Visible;
                txtTo.Visibility       = Visibility.Visible;

                GraphicsLayer layer2 = new GraphicsLayer();
                layer2.ID = "Graphics";
                map.Layers.Add(layer2);
            }
            else if (cBoxBaseMaps.SelectedItem.ToString() == "Map 1")
            {
                map = new Map();
                ArcGISTiledMapServiceLayer ArcGISTiledMapServiceLayer1 = new ArcGISTiledMapServiceLayer();
                ArcGISTiledMapServiceLayer1.ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer";
                ArcGISTiledMapServiceLayer1.ID         = "World_Light_Gray_Base";

                Esri.ArcGISRuntime.Layers.ArcGISDynamicMapServiceLayer ArcGISDynamicMapServiceLayer1 = new Esri.ArcGISRuntime.Layers.ArcGISDynamicMapServiceLayer();
                ArcGISDynamicMapServiceLayer1.ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/Demographics/USA_1990-2000_Population_Change/MapServer";
                ArcGISDynamicMapServiceLayer1.ID         = "USA_1990-2000_Population_Change";

                map.Layers.Add(ArcGISTiledMapServiceLayer1);
                map.Layers.Add(ArcGISDynamicMapServiceLayer1);

                mapView.Map = map;
            }
            else if (cBoxBaseMaps.SelectedItem.ToString() == "Map 3")
            {
                map = new Esri.ArcGISRuntime.Controls.Map();
                Esri.ArcGISRuntime.Layers.ArcGISTiledMapServiceLayer ArcGISTiledMapServiceLayer3 = new Esri.ArcGISRuntime.Layers.ArcGISTiledMapServiceLayer();
                ArcGISTiledMapServiceLayer3.ServiceUri = "http://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer";
                ArcGISTiledMapServiceLayer3.ID         = "World_Light_Gray_Base";

                Esri.ArcGISRuntime.Layers.FeatureLayer      FeatureLayer3        = new Esri.ArcGISRuntime.Layers.FeatureLayer();
                Esri.ArcGISRuntime.Data.ServiceFeatureTable ServiceFeatureTable3 = new Esri.ArcGISRuntime.Data.ServiceFeatureTable();
                ServiceFeatureTable3.ServiceUri = "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/HomelandSecurity/operations/FeatureServer/0";
                ServiceFeatureTable3.OutFields  = Esri.ArcGISRuntime.Tasks.Query.OutFields.All;
                FeatureLayer3.FeatureTable      = ServiceFeatureTable3;

                map.Layers.Add(ArcGISTiledMapServiceLayer3);
                map.Layers.Add(FeatureLayer3);

                mapView.Map = map;
            }

            mapView.Map = map;
        }
示例#20
0
        private async void AddAttachment_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedFeature == null)
            {
                return;
            }

            // Adjust the UI.
            AddAttachmentButton.IsEnabled = false;
            ActivityIndicator.Visibility  = Visibility.Visible;

            try
            {
                // Show a file dialog.
                // Allow the user to specify a file path - create the dialog.
                OpenFileDialog dlg = new OpenFileDialog
                {
                    DefaultExt       = ".jpg",
                    Filter           = "Image Files(*.JPG;*.JPEG)|*.JPG;*.JPEG",
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)
                };

                // Show the dialog and get the results.
                bool?result = dlg.ShowDialog();

                // Take action if the user selected a file.
                if (result != true)
                {
                    return;
                }

                // Get the name of the file from the full path (dlg.FileName is the full path).
                string filename = Path.GetFileName(dlg.FileName);

                // Create a stream for reading the file.
                FileStream fs = new FileStream(dlg.FileName,
                                               FileMode.Open,
                                               FileAccess.Read);

                // Create a binary reader from the stream.
                BinaryReader br = new BinaryReader(fs);

                // Populate the attachment data with the binary content.
                long   numBytes       = new FileInfo(dlg.FileName).Length;
                byte[] attachmentData = br.ReadBytes((int)numBytes);

                // Close the stream.
                fs.Close();

                // Add the attachment.
                // The contentType string is the MIME type for JPEG files, image/jpeg.
                await _selectedFeature.AddAttachmentAsync(filename, "image/jpeg", attachmentData);

                // Get a reference to the feature's service feature table.
                ServiceFeatureTable serviceTable = (ServiceFeatureTable)_selectedFeature.FeatureTable;

                // Apply the edits to the service feature table.
                await serviceTable.ApplyEditsAsync();

                // Update UI.
                _selectedFeature.Refresh();
                AttachmentsListBox.ItemsSource = await _selectedFeature.GetAttachmentsAsync();

                MessageBox.Show("Successfully added attachment", "Success!");
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString(), "Error adding attachment");
            }
            finally
            {
                // Adjust the UI.
                AddAttachmentButton.IsEnabled = true;
                ActivityIndicator.Visibility  = Visibility.Collapsed;
            }
        }
示例#21
0
        private async void AddAttachment_Click(object sender, EventArgs e)
        {
            if (_selectedFeature == null)
            {
                return;
            }

            // Adjust the UI.
            AddAttachmentButton.IsEnabled         = false;
            AttachmentActivityIndicator.IsVisible = true;

            // Get the file.
            string contentType = "image/jpeg";

            try
            {
                byte[] attachmentData;
                string filename;

                // Xamarin.Plugin.FilePicker shows the iCloud picker (not photo picker) on iOS.
                // This iOS code shows the photo picker.
#if __IOS__
                Stream imageStream = await GetImageStreamAsync();

                if (imageStream == null)
                {
                    return;
                }

                attachmentData = new byte[imageStream.Length];
                imageStream.Read(attachmentData, 0, attachmentData.Length);
                filename = _filename ?? "file1.jpeg";
#else
                // Show a file picker - this uses the Xamarin.Plugin.FilePicker NuGet package.
                FileData fileData = await CrossFilePicker.Current.PickFile(new[] { ".jpg", ".jpeg" });

                if (fileData == null)
                {
                    return;
                }

                if (!fileData.FileName.EndsWith(".jpg") && !fileData.FileName.EndsWith(".jpeg"))
                {
                    await Application.Current.MainPage.DisplayAlert("Try again!", "This sample only allows uploading jpg files.", "OK");

                    return;
                }

                attachmentData = fileData.DataArray;
                filename       = fileData.FileName;
#endif
                // Add the attachment.
                // The contentType string is the MIME type for JPEG files, image/jpeg.
                await _selectedFeature.AddAttachmentAsync(filename, contentType, attachmentData);

                // Get a reference to the feature's service feature table.
                ServiceFeatureTable serviceTable = (ServiceFeatureTable)_selectedFeature.FeatureTable;

                // Apply the edits to the service feature table.
                await serviceTable.ApplyEditsAsync();

                // Update UI.
                _selectedFeature.Refresh();
                AttachmentsListBox.ItemsSource = await _selectedFeature.GetAttachmentsAsync();

                await Application.Current.MainPage.DisplayAlert("Success!", "Successfully added attachment", "OK");
            }
            catch (Exception exception)
            {
                await Application.Current.MainPage.DisplayAlert("Error adding attachment", exception.ToString(), "OK");
            }
            finally
            {
                // Adjust the UI.
                AddAttachmentButton.IsEnabled         = true;
                AttachmentActivityIndicator.IsVisible = false;
            }
        }
        /// <summary>
        /// Enables geometry editing, submits geometry edit back to the server and refreshes dynamic layer.
        /// </summary>
        private async void EditButton_Click(object sender, RoutedEventArgs e)
        {
            var    layer     = MyMapView.Map.Layers["WildFire"] as ArcGISDynamicMapServiceLayer;
            var    overlay   = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay;
            var    featureID = (long)EditButton.Tag;
            string message   = null;

            try
            {
                // Hides graphic from overlay and dynamic layer while its geometry is being modified.
                overlay.Graphics.Clear();
                // Negative IDs indicate they do not exist on server yet.
                if (featureID > 0)
                {
                    if (layer.LayerDefinitions == null)
                    {
                        layer.LayerDefinitions = new ObservableCollection <LayerDefinition>();
                    }
                    else
                    {
                        layer.LayerDefinitions.Clear();
                    }
                    layer.LayerDefinitions.Add(new LayerDefinition()
                    {
                        LayerID    = layer.VisibleLayers[0],
                        Definition = string.Format("objectid <> {0}", featureID)
                    });
                }
                if (table == null)
                {
                    // Creates table based on visible layer of dynamic layer
                    // using FeatureServer specifying shape field to enable editing.
                    var id  = layer.VisibleLayers[0];
                    var url = layer.ServiceUri.Replace("MapServer", "FeatureServer");
                    url   = string.Format("{0}/{1}", url, id);
                    table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference);

                    table.OutFields = new OutFields(new string[] { "shape" });
                }
                // Retrieves feature identified by ID and updates its geometry
                // using GeometryEngine to correct ring orientation.
                var feature = await table.QueryAsync(featureID);

                var geometry = await MyMapView.Editor.EditGeometryAsync(feature.Geometry);

                feature.Geometry = GeometryEngine.Simplify(geometry);
                await table.UpdateAsync(feature);

                if (table.HasEdits)
                {
                    // Pushes geometry edits back to the server.
                    var result = await table.ApplyEditsAsync();

                    if (result.UpdateResults == null || result.UpdateResults.Count < 1)
                    {
                        return;
                    }
                    var updateResult = result.UpdateResults[0];
                    if (updateResult.Error != null)
                    {
                        message = updateResult.Error.Message;
                    }
                }
            }
            catch (TaskCanceledException)
            {
                // Handles canceling out of Editor.
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                SetGeometryEditor();
                if (layer.LayerDefinitions != null)
                {
                    layer.LayerDefinitions.Clear();
                    // Refreshes layer to reflect geometry edits.
                    layer.Invalidate();
                }
            }
            if (!string.IsNullOrWhiteSpace(message))
            {
                await new MessageDialog(message).ShowAsync();
            }
        }
示例#23
0
        private void Initialize()
        {
            try
            {
                // Define the URI for the service feature table (US state polygons).
                Uri featureTableUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3");

                // Create a new service feature table from the URI.
                ServiceFeatureTable censusServiceFeatureTable = new ServiceFeatureTable(featureTableUri);

                // Create a new feature layer from the service feature table.
                FeatureLayer censusFeatureLayer = new FeatureLayer(censusServiceFeatureTable)
                {
                    // Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work).
                    RenderingMode = FeatureRenderingMode.Dynamic
                };

                // Create a new simple line symbol for the feature layer.
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1);

                // Create a new simple fill symbol for the feature layer.
                SimpleFillSymbol fillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, lineSymbol);

                // Create a new simple renderer for the feature layer.
                SimpleRenderer renderer = new SimpleRenderer(fillSymbol);

                // Get the scene properties from the simple renderer.
                RendererSceneProperties sceneProperties = renderer.SceneProperties;

                // Set the extrusion mode for the scene properties.
                sceneProperties.ExtrusionMode = ExtrusionMode.AbsoluteHeight;

                // Set the initial extrusion expression.
                sceneProperties.ExtrusionExpression = "[POP2007] / 10";

                // Set the feature layer's renderer to the define simple renderer.
                censusFeatureLayer.Renderer = renderer;

                // Create a new scene with a topographic basemap.
                Scene myScene = new Scene(BasemapType.Topographic);

                // Set the scene view's scene to the newly create one.
                _mySceneView.Scene = myScene;

                // Add the feature layer to the scene's operational layer collection.
                myScene.OperationalLayers.Add(censusFeatureLayer);

                // Create a new map point to define where to look on the scene view.
                MapPoint myMapPoint = new MapPoint(-10974490, 4814376, 0, SpatialReferences.WebMercator);

                // Create and use an orbit location camera controller defined by a point and distance.
                _mySceneView.CameraController = new OrbitLocationCameraController(myMapPoint, 20000000);
            }
            catch (Exception ex)
            {
                // Something went wrong, display the error.
                UIAlertController alert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);
            }
        }
        private async void AddAttachment_Click(object sender, RoutedEventArgs e)
        {
            if (_selectedFeature == null)
            {
                return;
            }

            // Adjust the UI.
            AddAttachmentButton.IsEnabled = false;
            ActivityIndicator.Visibility  = Visibility.Visible;

            // Get the file.
            string contentType = "image/jpeg";

            byte[] attachmentData;

            try
            {
                // Show a file picker.
                // Allow the user to specify a file path - create the picker.
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.FileTypeFilter.Add(".jpg");

                // Show the picker.
                StorageFile file = await openPicker.PickSingleFileAsync();

                // Take action if the user selected a file.
                if (file == null)
                {
                    return;
                }

                // Read the file contents into memory.
                Stream dataStream = await file.OpenStreamForReadAsync();

                attachmentData = new byte[dataStream.Length];
                dataStream.Read(attachmentData, 0, attachmentData.Length);
                dataStream.Close();

                // Add the attachment.
                // The contentType string is the MIME type for JPEG files, image/jpeg.
                await _selectedFeature.AddAttachmentAsync(file.Name, contentType, attachmentData);

                // Get a reference to the feature's service feature table.
                ServiceFeatureTable serviceTable = (ServiceFeatureTable)_selectedFeature.FeatureTable;

                // Apply the edits to the service feature table.
                await serviceTable.ApplyEditsAsync();

                // Update UI.
                _selectedFeature.Refresh();
                AttachmentsListBox.ItemsSource = await _selectedFeature.GetAttachmentsAsync();

                await new MessageDialog("Successfully added attachment", "Success!").ShowAsync();
            }
            catch (Exception exception)
            {
                await new MessageDialog(exception.ToString(), "Error adding attachment").ShowAsync();
            }
            finally
            {
                // Adjust the UI.
                AddAttachmentButton.IsEnabled = true;
                ActivityIndicator.Visibility  = Visibility.Collapsed;
            }
        }
        private async void Initialize()
        {
            try
            {
                // Construct the map and set the MapView.Map property.
                _myMapView.Map = new Map(BasemapStyle.ArcGISLightGray);

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

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

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

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

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

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

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

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

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

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

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

                await _incidentLayer.LoadAsync();

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

                // Enable the solve button.
                _solveRoutesButton.Enabled = true;
            }
            catch (Exception exception)
            {
                CreateErrorDialog("An exception has occurred.\n" + exception.Message);
            }
        }
示例#26
0
        private async void Initialize()
        {
            // Create a new Map with a vector streets basemap.
            Map myMap = new Map(Basemap.CreateStreetsVector());

            // Create the URI to the Service Requests map service.
            Uri serviceRequestUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/ServiceRequest/MapServer");

            // Create a new ArcGISMapImageLayer that uses the service URI.
            ArcGISMapImageLayer serviceRequestsMapImageLayer = new ArcGISMapImageLayer(serviceRequestUri);

            try
            {
                // Load all sublayers and tables contained by the map image layer.
                await serviceRequestsMapImageLayer.LoadTablesAndLayersAsync();

                // Set the initial map extent to the extent of all service request features.
                Envelope requestsExtent = serviceRequestsMapImageLayer.FullExtent;
                myMap.InitialViewpoint = new Viewpoint(requestsExtent);

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

                // Get the service request comments table from the map image layer.
                ServiceFeatureTable commentsTable = serviceRequestsMapImageLayer.Tables[0];

                // Create query parameters to get all non-null service request comment records (features) from the table.
                QueryParameters queryToGetNonNullComments = new QueryParameters
                {
                    WhereClause = "requestid <> '' AND comments <> ''"
                };

                // Query the comments table to get the non-null records.
                FeatureQueryResult commentQueryResult = await commentsTable.QueryFeaturesAsync(queryToGetNonNullComments, QueryFeatureFields.LoadAll);

                // Show the records from the service request comments table in the UITableView control.
                foreach (ArcGISFeature commentFeature in commentQueryResult)
                {
                    _serviceRequestComments.Add(commentFeature);
                }

                // Create the table view source that uses the list of features.
                ServiceRequestCommentsTableSource commentsTableSource = new ServiceRequestCommentsTableSource(_serviceRequestComments);

                // Handle a new selection in the table source.
                commentsTableSource.ServiceRequestCommentSelected += CommentsTableSource_ServiceRequestCommentSelected;

                // Assign the table view source to the table view control.
                _tableView.Source = commentsTableSource;

                // Create a graphics overlay to show selected features and add it to the map view.
                _selectedFeaturesOverlay = new GraphicsOverlay();
                _myMapView.GraphicsOverlays.Add(_selectedFeaturesOverlay);

                // Assign the map to the MapView.
                _myMapView.Map = myMap;

                // Reload the table view data to refresh the display.
                _tableView.ReloadData();
            }
            catch (Exception e)
            {
                new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show();
            }
        }
        // Handle a new selected comment record in the table view.
        private async void CommentsListBox_SelectionChanged(object sender, SelectedItemChangedEventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

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

            if (selectedComment == null)
            {
                return;
            }

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

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

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

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

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

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

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

                    return;
                }

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

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

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

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

                // Add the graphic to the graphics overlay and zoom the map view to its extent.
                _selectedFeaturesOverlay.Graphics.Add(requestGraphic);
                await MyMapView.SetViewpointCenterAsync(serviceRequestPoint, 150000);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
 /// <summary>
 /// Displays current attribute values of related record.
 /// </summary>
 private async void RelatedRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (RelatedRecords.SelectedItem == null)
         return;
     var graphic = (Graphic)RelatedRecords.SelectedItem;
     SetAttributeEditor();
     string message = null;
     try
     {
         if (table == null)
             table = await GetRelatedTableAsync();
         var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture);
         var feature = await table.QueryAsync(featureID);
         SetAttributeEditor(feature);
     }
     catch (Exception ex)
     {
         message = ex.Message;
     }
     if (!string.IsNullOrWhiteSpace(message))
         MessageBox.Show(message);
 }
示例#29
0
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk.
            try
            {
                TileCache tileCache = new TileCache(DataManager.GetDataFolder("3f1bbf0ec70b409a975f5c91f363fe7d", "SanFrancisco.tpk"));

                // Create the corresponding layer based on the tile cache.
                ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

                // Create the basemap based on the tile cache.
                Basemap sfBasemap = new Basemap(tileLayer);

                // Create the map with the tile-based basemap.
                Map myMap = new Map(sfBasemap);

                // Assign the map to the MapView.
                myMapView.Map = myMap;

                // Create a new symbol for the extent graphic.
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Red, 2);

                // Create a graphics overlay for the extent graphic and apply a renderer.
                GraphicsOverlay extentOverlay = new GraphicsOverlay
                {
                    Renderer = new SimpleRenderer(lineSymbol)
                };

                // Add the graphics overlay to the map view.
                myMapView.GraphicsOverlays.Add(extentOverlay);

                // Set up an event handler for when the viewpoint (extent) changes.
                myMapView.ViewpointChanged += MapViewExtentChanged;

                // Create a task for generating a geodatabase (GeodatabaseSyncTask).
                _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

                // Add all layers from the service to the map.
                foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
                {
                    // Get the URL for this layer.
                    Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                    // Create the ServiceFeatureTable.
                    ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                    // Wait for the table to load.
                    await onlineTable.LoadAsync();

                    // Add the layer to the map's operational layers if load succeeds.
                    if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                    {
                        myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                    }
                }

                // Update the graphic - needed in case the user decides not to interact before pressing the button.
                UpdateMapExtent();

                // Enable the generate button now that sample is ready.
                myGenerateButton.IsEnabled = true;
            }
            catch (Exception ex)
            {
                await((Page)Parent).DisplayAlert("Error", ex.ToString(), "OK");
            }
        }
 /// <summary>
 /// Adds a new related record to highlighted feature.
 /// </summary>
 private async void AddButton_Click(object sender, RoutedEventArgs e)
 {
     SetAttributeEditor();
     var featureID = (Int64)AddButton.Tag;
     var requestID = (string)RelatedRecords.Tag;
     string message = null;
     try
     {
         if (table == null)
             table = await GetRelatedTableAsync();
         var feature = new GeodatabaseFeature(table.Schema);
         feature.Attributes[relationship.KeyField] = requestID;
         feature.Attributes["rank"] = 5;
         feature.Attributes["comments"] = "Describe service requirement here.";
         feature.Attributes["submitdt"] = DateTime.UtcNow;
         var relatedFeatureID = await table.AddAsync(feature);
         await SaveEditsAsync();
         await QueryRelatedRecordsAsync();
     }
     catch (Exception ex)
     {
         message = ex.Message;
     }
     if (!string.IsNullOrWhiteSpace(message))
         await new MessageDialog(message).ShowAsync();
 }
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk
            TileCache tileCache = new TileCache(GetTpkPath());

            // Create the corresponding layer based on the tile cache
            ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

            // Create the basemap based on the tile cache
            Basemap sfBasemap = new Basemap(tileLayer);

            // Create the map with the tile-based basemap
            Map myMap = new Map(sfBasemap);

            // Assign the map to the MapView
            myMapView.Map = myMap;

            // Create a new symbol for the extent graphic
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);

            // Create graphics overlay for the extent graphic and apply a renderer
            GraphicsOverlay extentOverlay = new GraphicsOverlay();

            extentOverlay.Renderer = new SimpleRenderer(lineSymbol);

            // Add graphics overlay to the map view
            myMapView.GraphicsOverlays.Add(extentOverlay);

            // Set up an event handler for 'tapped' events
            myMapView.GeoViewTapped += GeoViewTapped;

            // Set up an event handler for when the viewpoint (extent) changes
            myMapView.ViewpointChanged += MapViewExtentChanged;

            // Create a task for generating a geodatabase (GeodatabaseSyncTask)
            _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

            // Add all graphics from the service to the map
            foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
            {
                // Get the Uri for this particular layer
                Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                // Create the ServiceFeatureTable
                ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                // Wait for the table to load
                await onlineTable.LoadAsync();

                // Add the layer to the map's operational layers if load succeeds
                if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                {
                    myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                }
            }

            // Update the graphic - needed in case the user decides not to interact before pressing the button
            UpdateMapExtent();

            // Enable the generate button now that the sample is ready
            myGenerateButton.Enabled = true;
        }
示例#32
0
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk.
            TileCache tileCache = new TileCache(DataManager.GetDataFolder("e4a398afe9a945f3b0f4dca1e4faccb5", "SanFrancisco.tpkx"));

            // Create the corresponding layer based on the tile cache.
            ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

            // Create the basemap based on the tile cache.
            Basemap sfBasemap = new Basemap(tileLayer);

            // Create the map with the tile-based basemap.
            Map myMap = new Map(sfBasemap);

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

            // Create a new symbol for the extent graphic.
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);

            // Create a graphics overlay for the extent graphic and apply a renderer.
            GraphicsOverlay extentOverlay = new GraphicsOverlay
            {
                Renderer = new SimpleRenderer(lineSymbol)
            };

            // Add graphics overlay to the map view.
            MyMapView.GraphicsOverlays.Add(extentOverlay);

            // Set up an event handler for when the viewpoint (extent) changes.
            MyMapView.ViewpointChanged += MapViewExtentChanged;

            try
            {
                // Create a task for generating a geodatabase (GeodatabaseSyncTask).
                _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

                // Add all graphics from the service to the map.
                foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
                {
                    // Get the URL for this particular layer.
                    Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                    // Create the ServiceFeatureTable.
                    ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                    // Wait for the table to load.
                    await onlineTable.LoadAsync();

                    // Skip tables that aren't for point features.{
                    if (onlineTable.GeometryType != GeometryType.Point)
                    {
                        continue;
                    }

                    // Add the layer to the map's operational layers if load succeeds.
                    if (onlineTable.LoadStatus == LoadStatus.Loaded)
                    {
                        myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                    }
                }

                // Update the graphic - needed in case the user decides not to interact before pressing the button.
                UpdateMapExtent();

                // Enable the generate button.
                MyGenerateButton.IsEnabled = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
		/// <summary>
		/// Enables attribute editing, submits attribute edit back to the server and refreshes dynamic layer.
		/// </summary>
		private async void ChoiceList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			ChoiceList.SelectionChanged -= ChoiceList_SelectionChanged;
			var featureID = (Int64)EditButton.Tag;
			var selected = (string)ChoiceList.SelectedItem;
			var layer = MyMapView.Map.Layers["PoolPermit"] as ArcGISDynamicMapServiceLayer;
			var overlay = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay;
			string message = null;
			try
			{
				if (table == null)
				{
					// Creates table based on visible layer of dynamic layer 
					// using FeatureServer specifying has_pool field to enable editing.
					var id = layer.VisibleLayers[0];
					var url = layer.ServiceUri.Replace("MapServer", "FeatureServer");
					url = string.Format("{0}/{1}", url, id);
					table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference);
					table.OutFields = new OutFields(new string[] { "has_pool" });
				}
				// Retrieves feature identified by ID and updates its attributes.
				var feature = await table.QueryAsync(featureID);
				if (choices != null)
				{
					var value = choices.FirstOrDefault(item => string.Equals(item.Value, selected)).Key;
					feature.Attributes["has_pool"] = value;
					await table.UpdateAsync(feature);
				}
				if (table.HasEdits)
				{
					// Pushes attribute edits back to the server.
					var result = await table.ApplyEditsAsync();
					if (result.UpdateResults == null || result.UpdateResults.Count < 1)
						return;
					var updateResult = result.UpdateResults[0];
					if (updateResult.Error != null)
						message = updateResult.Error.Message;
					// Refreshes layer to reflect attribute edits.
					layer.Invalidate();
				}

			}
			catch (Exception ex)
			{
				message = ex.Message;
			}
			finally
			{
				overlay.Graphics.Clear();
				SetAttributeEditor();
			}
			if (!string.IsNullOrWhiteSpace(message))
				await new MessageDialog(message).ShowAsync();
		}
示例#34
0
        /// <summary>
        /// 레이어 보이기/끄기 - LocalServer버전
        /// </summary>
        /// <param name="_map"></param>
        /// <param name="layer"></param>
        /// <param name="chk"></param>
        public async void ShowLocalServerLayer(MapView _mapView, string _layerNm, bool chk)
        {
            try
            {
                // 0.해당레이어 가져오기
                string filterExp = "";
                string shapeNm   = "";

                try
                {
                    string[] ary = _layerNm.Split('^');
                    shapeNm   = ary[0];                     //레이어테이블명
                    filterExp = "FTR_CDE='" + ary[1] + "'"; //필터표현식
                }
                catch (Exception) { }

                FeatureLayer layer = CmmRun.layers[_layerNm];
                //Type memberType = this.GetType();



                // 1.레이어 ON
                if (chk)
                {
                    if (_mapView.Map.OperationalLayers.Contains(layer))
                    {
                        //on상태 아무것도 안함
                    }
                    else
                    {
                        if (layer != null && layer.LoadStatus == LoadStatus.Loaded) //레이어객체 있으면 단순추가
                        {
                            // 필터링 인수있으면 하위시설물으로 필터
                            if (!FmsUtil.IsNull(filterExp))
                            {
                                layer.DefinitionExpression = filterExp;
                            }
                            _mapView.Map.OperationalLayers.Add(layer);
                        }
                        else //레이어객체 없으면 Shape 로딩
                        {
                            if (LocalServer.Instance.Status == LocalServerStatus.Started)
                            {
                                // Get the path to the first layer - the local feature service url + layer ID
                                string layerUrl = _localFeatureService.Url + "/" + GetLayerId(_layerNm);

                                // Create the ServiceFeatureTable
                                ServiceFeatureTable myFeatureTable = new ServiceFeatureTable(new Uri(layerUrl));

                                // Create the Feature Layer from the table
                                FeatureLayer myFeatureLayer = new FeatureLayer(myFeatureTable);
                                CmmRun.layers[_layerNm] = myFeatureLayer; //생성한레이어를 딕셔너리에 저장

                                // 필터링 인수있으면 하위시설물으로 필터
                                if (!FmsUtil.IsNull(filterExp))
                                {
                                    myFeatureLayer.DefinitionExpression = filterExp;
                                }


                                //렌더러는 레이어 각각 할당해야하므로 렌더러복사하여 할당
                                myFeatureLayer.Renderer = CmmRun.uniqueValueRenderer.Clone();

                                // Add the layer to the map
                                _mapView.Map.OperationalLayers.Add(myFeatureLayer);

                                try
                                {
                                    // Wait for the layer to load
                                    await myFeatureLayer.LoadAsync();

                                    //한반도이내인 경우만
                                    if (myFeatureLayer.FullExtent.XMax < 14566451.0 && myFeatureLayer.FullExtent.YMax < 5362210.0 &&
                                        myFeatureLayer.FullExtent.XMin > 13691400.0 && myFeatureLayer.FullExtent.YMin < 3797264.0)
                                    {
                                        // Set the viewpoint on the MapView to show the layer data
                                        await _mapView.SetViewpointGeometryAsync(myFeatureLayer.FullExtent, 50);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.ToString(), "Error");
                                }
                            }
                        }
                    }
                }
                // 2.레이어 OFF
                else
                {
                    // 필터링 인수있으면 하위시설물으로 필터
                    if (!FmsUtil.IsNull(filterExp))
                    {
                        layer.DefinitionExpression = filterExp;
                    }

                    if (_mapView.Map.OperationalLayers.Contains(layer))
                    {
                        _mapView.Map.OperationalLayers.Remove(layer);
                    }
                    else
                    {
                        //off상태 아무것도 안함
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("레이어가 존재하지 않습니다.");
            }
        }
        private async void Initialize()
        {
            try
            {
                // Create a tile cache and load it with the SanFrancisco streets tpk.
                TileCache tileCache = new TileCache(DataManager.GetDataFolder("3f1bbf0ec70b409a975f5c91f363fe7d", "SanFrancisco.tpk"));

                // Create the corresponding layer based on the tile cache.
                ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

                // Create the basemap based on the tile cache.
                Basemap sfBasemap = new Basemap(tileLayer);

                // Create the map with the tile-based basemap.
                Map map = new Map(sfBasemap);

                // Assign the map to the MapView.
                _myMapView.Map = map;

                // Create a new symbol for the extent graphic.
                SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);

                // Create graphics overlay for the extent graphic and apply a renderer.
                GraphicsOverlay extentOverlay = new GraphicsOverlay
                {
                    Renderer = new SimpleRenderer(lineSymbol)
                };

                // Add graphics overlay to the map view.
                _myMapView.GraphicsOverlays.Add(extentOverlay);

                // Create a task for generating a geodatabase (GeodatabaseSyncTask).
                _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

                // Add all graphics from the service to the map.
                foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
                {
                    // Get the Uri for this particular layer.
                    Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                    // Create the ServiceFeatureTable.
                    ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                    // Wait for the table to load.
                    await onlineTable.LoadAsync();

                    // Skip tables that aren't for point features.{
                    if (onlineTable.GeometryType != GeometryType.Point)
                    {
                        continue;
                    }

                    // Add the layer to the map's operational layers if load succeeds.
                    if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                    {
                        map.OperationalLayers.Add(new FeatureLayer(onlineTable));
                    }
                }

                // Update the graphic - needed in case the user decides not to interact before pressing the button.
                UpdateMapExtent();

                // Enable the generate button now that the sample is ready.
                _generateButton.Enabled = true;
            }
            catch (Exception ex)
            {
                ShowStatusMessage(ex.ToString());
            }
        }
示例#36
0
        // Function to query map image sublayers when the query button is clicked.
        private async void QuerySublayers_Click(object sender, EventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

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

            if (!double.TryParse(_populationValueInput.Text.Trim(), out populationNumber))
            {
                UIAlertController alert = UIAlertController.Create("Invalid number", "Population value must be numeric.", UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alert, true, null);

                return;
            }

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

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

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

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

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

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

            FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery);

            FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery);

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

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

                _selectedFeaturesOverlay.Graphics.Add(cityGraphic);
            }

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

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

                _selectedFeaturesOverlay.Graphics.Add(countyGraphic);
            }

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

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

                _selectedFeaturesOverlay.Graphics.Add(stateGraphic);
            }
        }
 /// <summary>
 /// Deletes related record.
 /// </summary>
 private async void DeleteButton_Click(object sender, RoutedEventArgs e)
 {
     if (RelatedRecords.SelectedItem == null) return;
     var graphic = (Graphic)RelatedRecords.SelectedItem;
     string message = null;
     try
     {
         if (table == null)
             table = await GetRelatedTableAsync();
         var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture);
         await table.DeleteAsync(featureID);
         await SaveEditsAsync();
         await QueryRelatedRecordsAsync();
         SetAttributeEditor();
     }
     catch (Exception ex)
     {
         message = ex.Message;
     }
     if (!string.IsNullOrWhiteSpace(message))
         await new MessageDialog(message).ShowAsync();
 }
示例#38
0
        private async void QuerySublayers_Click(object sender, EventArgs e)
        {
            // Clear selected features from the graphics overlay.
            _selectedFeaturesOverlay.Graphics.Clear();

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

            if (!double.TryParse(_populationValueInput.Text.Trim(), out populationNumber))
            {
                Toast messageToast = Toast.MakeText(this.ApplicationContext, "Population value must be numeric.", ToastLength.Short);
                messageToast.Show();

                return;
            }

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

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

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

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

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

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

                FeatureQueryResult statesQueryResult = await statesTable.QueryFeaturesAsync(populationQuery);

                FeatureQueryResult countiesQueryResult = await countiesTable.QueryFeaturesAsync(populationQuery);

                // Display the selected cities in the graphics overlay.
                SimpleMarkerSymbol citySymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, Color.Red, 16);
                foreach (Feature city in citiesQueryResult)
                {
                    Graphic cityGraphic = new Graphic(city.Geometry, citySymbol);

                    _selectedFeaturesOverlay.Graphics.Add(cityGraphic);
                }

                // Display the selected counties in the graphics overlay.
                SimpleLineSymbol countyLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, Color.Cyan, 2);
                SimpleFillSymbol countySymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.DiagonalCross, Color.Cyan, countyLineSymbol);
                foreach (Feature county in countiesQueryResult)
                {
                    Graphic countyGraphic = new Graphic(county.Geometry, countySymbol);

                    _selectedFeaturesOverlay.Graphics.Add(countyGraphic);
                }

                // Display the selected states in the graphics overlay.
                SimpleLineSymbol stateLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.DarkCyan, 6);
                SimpleFillSymbol stateSymbol     = new SimpleFillSymbol(SimpleFillSymbolStyle.Null, Color.Cyan, stateLineSymbol);
                foreach (Feature state in statesQueryResult)
                {
                    Graphic stateGraphic = new Graphic(state.Geometry, stateSymbol);

                    _selectedFeaturesOverlay.Graphics.Add(stateGraphic);
                }
            }
            catch (Exception ex)
            {
                new AlertDialog.Builder(this).SetMessage(ex.ToString()).SetTitle("Error").Show();
            }
        }
示例#39
0
        public static async Task <ArcCrudEnum> EditBin(BinViewModel binViewModel)
        {
            IBinstance    bin           = binViewModel.Binstance;
            ArcGISFeature featureToEdit = binViewModel.ArcGISFeature;

            try
            {
                await featureToEdit.LoadAsync();

                featureToEdit.Attributes["identifier"]  = bin.Identifier;
                featureToEdit.Attributes["modified_by"] = binViewModel.EmpoyeeNumber;

                switch (bin.BinType)
                {
                case BinTypeEnum.RoundStorage:
                    featureToEdit.Attributes["bin_type"] = "round_storage";
                    break;

                case BinTypeEnum.GravityWagon:
                    featureToEdit.Attributes["bin_type"] = "gravity_wagon";
                    break;

                case BinTypeEnum.PolygonStructure:
                    featureToEdit.Attributes["bin_type"] = "polygon_structure";
                    break;

                case BinTypeEnum.FlatStructure:
                    featureToEdit.Attributes["bin_type"] = "flat_structure";
                    break;
                }

                featureToEdit.Attributes["year_collected"] = bin.YearCollected;


                if (bin.IsLeased.HasValue)
                {
                    featureToEdit.Attributes["owned_or_leased"] = bin.IsLeased.Value ? "leased" : "owned";
                }

                if (bin.HasDryingDevice.HasValue)
                {
                    featureToEdit.Attributes["drying_device"] = bin.HasDryingDevice.Value ? "true" : "false";
                }

                if (bin.HasGrainHeightIndicator.HasValue)
                {
                    featureToEdit.Attributes["bin_level_indicator_device"] = bin.HasGrainHeightIndicator.Value ? "true" : "false";
                }

                switch (bin.LadderType)
                {
                case Ladder.None:
                    featureToEdit.Attributes["ladder_type"] = "none";
                    break;

                case Ladder.Ladder:
                    featureToEdit.Attributes["ladder_type"] = "ladder";
                    break;

                case Ladder.Stairs:
                    featureToEdit.Attributes["ladder_type"] = "stairs";
                    break;
                }

                featureToEdit.Attributes["notes"] = bin.Notes;

                double dr;
                //double.TryParse(bin.BinVolume, out dr);
                //featureToEdit.Attributes["bin_volume"] = dr;

                //bin type specific logic below
                Type t = bin.GetType();
                if (bin.BinType == BinTypeEnum.FlatStructure)
                {
                    if (t.Equals(typeof(FlatBin)))
                    {
                        FlatBin flat = (FlatBin)bin;
                        featureToEdit.Attributes["crib_height"] = flat.CribLength;
                        featureToEdit.Attributes["crib_width"]  = flat.CribWidth;
                    }
                }
                else if (bin.BinType == BinTypeEnum.GravityWagon)
                {
                    if (t.Equals(typeof(GravityBin)))
                    {
                        GravityBin gravityBin = (GravityBin)bin;
                        featureToEdit.Attributes["chute_length"]     = gravityBin.ChuteLength;
                        featureToEdit.Attributes["hopper_height"]    = gravityBin.HopperHeight;
                        featureToEdit.Attributes["rectangle_height"] = gravityBin.RectangleHeight;
                        featureToEdit.Attributes["rectangle_length"] = gravityBin.RectangleLength;
                        featureToEdit.Attributes["rectangle_width"]  = gravityBin.RectangleWidth;
                    }
                }
                else if (bin.BinType == BinTypeEnum.PolygonStructure)
                {
                    if (t.Equals(typeof(PolygonBin)))
                    {
                        PolygonBin polygonBin = (PolygonBin)bin;
                        featureToEdit.Attributes["side_height"]     = polygonBin.SideHeight;
                        featureToEdit.Attributes["side_width"]      = polygonBin.SideWidth;
                        featureToEdit.Attributes["number_of_sides"] = polygonBin.NumberOfSides;
                    }
                }
                else if (bin.BinType == BinTypeEnum.RoundStorage)
                {
                    if (t.Equals(typeof(PolygonBin)))
                    {
                        RoundBin round = (RoundBin)bin;
                        if (round.HasHopper.HasValue)
                        {
                            featureToEdit.Attributes["has_hopper"] = round.HasHopper.Value ? "true" : "false";
                        }

                        featureToEdit.Attributes["radius"]        = round.Radius;
                        featureToEdit.Attributes["wall_height"]   = round.WallHeight;
                        featureToEdit.Attributes["roof_height"]   = round.RoofHeight;
                        featureToEdit.Attributes["hopper_height"] = round.HopperHeight;
                    }
                }


                // can't be null
                if (binViewModel.Binstance.YTYDatas == null)
                {
                    binViewModel.Binstance.YTYDatas = new List <YTYData>();
                }
                //use data in _binViewModel

                System.Diagnostics.Debug.Print("Feature can edit attachments" + (featureToEdit.CanEditAttachments ? "Yes" : "No"));
                //-------- Formatting --------
                //create json
                string jsonString = JsonConvert.SerializeObject(binViewModel.Binstance.YTYDatas);

                //System.Diagnostics.Debug.Print(jsonString);
                //System.Diagnostics.Debug.Print(((Binstance)(binViewModel.Binstance)).YTYDatasString());
                // convert json to byte array
                byte[] byteArray = Encoding.UTF8.GetBytes(jsonString);


                //-------- ARC Connection --------
                //remove old YTYData
                List <Attachment>          attachmentsToRemove = new List <Attachment>();
                IReadOnlyList <Attachment> attachments         = await featureToEdit.GetAttachmentsAsync();

                foreach (Attachment attachment in attachments)
                {
                    System.Diagnostics.Debug.Print(attachment.Name);
                    if (attachment.Name.Equals(YTY_FILE_NAME))
                    {
                        System.Diagnostics.Debug.Print("Found YTY attachment");
                        attachmentsToRemove.Add(attachment);
                    }
                }
                System.Diagnostics.Debug.Print("Attachments to remove:");
                foreach (Attachment attachment in attachments)
                {
                    System.Diagnostics.Debug.Print(attachment.Name);
                }

                if (attachmentsToRemove.Any())
                {
                    //update the json file
                    await featureToEdit.UpdateAttachmentAsync(attachmentsToRemove.First(), YTY_FILE_NAME, "application/json", byteArray);
                }

                _featureTable = (ServiceFeatureTable)featureToEdit.FeatureTable;

                // update feature after attachment added
                await _featureTable.UpdateFeatureAsync(featureToEdit); //agsFeature

                System.Diagnostics.Debug.Print("Feature table updated");

                // push to ArcGIS Online feature service
                IReadOnlyList <EditResult> editResults = await _featureTable.ApplyEditsAsync();

                System.Diagnostics.Debug.Print("Arc updated");

                foreach (var er in editResults)
                {
                    if (er.CompletedWithErrors)
                    {
                        // handle error (er.Error.Message)
                        return(ArcCrudEnum.Failure);
                    }
                }

                return(ArcCrudEnum.Success);
            }
            catch (ArcGISWebException)
            {
                return(ArcCrudEnum.Exception);
            }
        }
示例#40
0
        private void get_feature_layer()
        {
            /***********************************************************************
             *   This function loads a feature layer from arcGIS online
             ************************************************************************/
            // Create new Map with basemap
            myMap = new Map(Basemap.CreateTopographic());


            // Create and set initial map area
            Envelope initialLocation = new Envelope(
                -160.6739, 13.3844, -179.5449, 80.2319,
                SpatialReferences.Wgs84);

            myMap.InitialViewpoint = new Viewpoint(initialLocation);


            /***********************************************************************
             *   Turtle Feature Layer
             ************************************************************************/
            // Create uri to the used feature service
            var serviceUri = new Uri(
                "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Turtles/FeatureServer/0");

            // Create feature table using a URL.
            _featureTable = new ServiceFeatureTable(serviceUri);

            MyMapView.Map = myMap;

            // Create feature layer using this feature table. Make it slightly transparent.
            _featureLayer = new FeatureLayer(_featureTable);

            string theJSON_String =
                @"{
                    ""labelExpressionInfo"":{""expression"":""$feature.Species""},
                    ""labelPlacement"":""esriServerLinePlacementAboveAlong"",
                    ""where"":""Species <> ' '"",
                    ""symbol"":
                        { 
                            ""angle"":0,
                            ""backgroundColor"":[0,0,0,0],
                            ""borderLineColor"":[0,0,0,0],
                            ""borderLineSize"":0,
                            ""color"":[51, 51, 51, 255],
                            ""font"":
                                {
                                    ""decoration"":""none"",
                                    ""size"":10,
                                    ""style"":""normal"",
                                    ""weight"":""normal""
                                },
                            ""haloColor"":[0,0,0,0],
                            ""haloSize"":1.5,
                            ""horizontalAlignment"":""center"",
                            ""kerning"":false,
                            ""type"":""esriTS"",
                            ""verticalAlignment"":""middle"",
                            ""xoffset"":0,
                            ""yoffset"":0
                        }
               }";

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


            /***********************************************************************
             *   Air Temp Feature Layer
             ************************************************************************/
            var airServiceUri = new Uri(
                "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Air_Temp_/FeatureServer/0");

            // Create feature table using a URL.
            _airFeatureTable = new ServiceFeatureTable(airServiceUri);

            // Create feature layer using this feature table. Make it slightly transparent.
            _airFeatureLayer = new FeatureLayer(_airFeatureTable)
            {
                Opacity = 0.6
            };

            /***********************************************************************
             *   Wind Feature Layer
             ************************************************************************/
            var windServiceUri = new Uri(
                "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Wind/FeatureServer/0");

            // Create feature table using a URL.
            _windFeatureTable = new ServiceFeatureTable(windServiceUri);

            // Create feature layer using this feature table. Make it slightly transparent.
            _windFeatureLayer = new FeatureLayer(_windFeatureTable)
            {
                Opacity = 0.6
            };

            /***********************************************************************
             *   Sea Surface Temperature Feature Layer
             ************************************************************************/
            var seaTempServiceUri = new Uri(
                "https://services6.arcgis.com/kInEIOmrLNzXMSuZ/arcgis/rest/services/Sea_Temp/FeatureServer/0");

            // Create feature table using a URL.
            _seaTempFeatureTable = new ServiceFeatureTable(seaTempServiceUri);

            // Create feature layer using this feature table. Make it slightly transparent.
            _seaTempFeatureLayer = new FeatureLayer(_seaTempFeatureTable)
            {
                Opacity = 0.6
            };

            // add feature layers to map

            /* myMap.OperationalLayers.Add(_featureLayer);
             * myMap.OperationalLayers.Add(_airFeatureLayer);
             * myMap.OperationalLayers.Add(_windFeatureLayer);
             * myMap.OperationalLayers.Add(_seaTempFeatureLayer);*/


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

            // Enable the visibility of labels to be seen.
            _featureLayer.LabelsEnabled = true;

            MyMapView.TimeExtent = new TimeExtent(start, end);

            // add the map to the map view
            MyMapView.Map = myMap;
        }
示例#41
0
 static ArcGisService()
 {
     _featureTable = new ServiceFeatureTable(new Uri(FeatureServiceUrl));
     _featureLayer = new FeatureLayer(_featureTable);
 }
示例#42
0
        private void Initialize()
        {
            try
            {
                // Define the Uri for the service feature table (US state polygons)
                Uri myServiceFeatureTable_Uri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Census/MapServer/3");

                // Create a new service feature table from the Uri
                ServiceFeatureTable myServiceFeatureTable = new ServiceFeatureTable(myServiceFeatureTable_Uri);

                // Create a new feature layer from the service feature table
                FeatureLayer myFeatureLayer = new FeatureLayer(myServiceFeatureTable)
                {
                    // Set the rendering mode of the feature layer to be dynamic (needed for extrusion to work)
                    RenderingMode = FeatureRenderingMode.Dynamic
                };

                // Create a new simple line symbol for the feature layer
                SimpleLineSymbol mySimpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Black, 1);

                // Create a new simple fill symbol for the feature layer
                SimpleFillSymbol mysimpleFillSymbol = new SimpleFillSymbol(SimpleFillSymbolStyle.Solid, Color.Blue, mySimpleLineSymbol);

                // Create a new simple renderer for the feature layer
                SimpleRenderer mySimpleRenderer = new SimpleRenderer(mysimpleFillSymbol);

                // Get the scene properties from the simple renderer
                RendererSceneProperties myRendererSceneProperties = mySimpleRenderer.SceneProperties;

                // Set the extrusion mode for the scene properties
                myRendererSceneProperties.ExtrusionMode = ExtrusionMode.AbsoluteHeight;

                // Set the initial extrusion expression
                myRendererSceneProperties.ExtrusionExpression = "[POP2007] / 10";

                // Set the feature layer's renderer to the define simple renderer
                myFeatureLayer.Renderer = mySimpleRenderer;

                // Create a new scene with the topographic backdrop
                Scene myScene = new Scene(BasemapType.Topographic);

                // Set the scene view's scene to the newly create one
                _mySceneView.Scene = myScene;

                // Add the feature layer to the scene's operational layer collection
                myScene.OperationalLayers.Add(myFeatureLayer);

                // Create a new map point to define where to look on the scene view
                MapPoint myMapPoint = new MapPoint(-10974490, 4814376, 0, SpatialReferences.WebMercator);

                // Create a new orbit location camera controller using the map point and defined distance
                OrbitLocationCameraController myOrbitLocationCameraController = new OrbitLocationCameraController(myMapPoint, 20000000);

                // Set the scene view's camera controller to the orbit location camera controller
                _mySceneView.CameraController = myOrbitLocationCameraController;
            }
            catch (Exception ex)
            {
                // Something went wrong, display the error
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.SetTitle("Error");
                alert.SetMessage(ex.Message);
                alert.Show();
            }
        }
        /// <summary>
        /// Enables geometry editing, submits geometry edit back to the server and refreshes dynamic layer.
        /// </summary>
        private async void EditButton_Click(object sender, RoutedEventArgs e)
        {
            var layer = MyMapView.Map.Layers["WildFire"] as ArcGISDynamicMapServiceLayer;
            var overlay = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay;
            var featureID = (long)EditButton.Tag;
            string message = null;
            try
            {
                // Hides graphic from overlay and dynamic layer while its geometry is being modified.
                overlay.Graphics.Clear();
                // Negative IDs indicate they do not exist on server yet.
                if (featureID > 0)
                {
                    if (layer.LayerDefinitions == null)
                        layer.LayerDefinitions = new ObservableCollection<LayerDefinition>();
                    else
                        layer.LayerDefinitions.Clear();
                    layer.LayerDefinitions.Add(new LayerDefinition()
                    {
                        LayerID = layer.VisibleLayers[0],
                        Definition = string.Format("objectid <> {0}", featureID)
                    });
                }
                if (table == null)
                {
                    // Creates table based on visible layer of dynamic layer 
                    // using FeatureServer specifying shape field to enable editing.
                    var id = layer.VisibleLayers[0];
                    var url = layer.ServiceUri.Replace("MapServer", "FeatureServer");
                    url = string.Format("{0}/{1}", url, id);
                    table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference);
                    table.OutFields = new OutFields(new string[] { "shape" });
                }
                // Retrieves feature identified by ID and updates its geometry 
                // using GeometryEngine to correct ring orientation.
                var feature = await table.QueryAsync(featureID);
                var geometry = await MyMapView.Editor.EditGeometryAsync(feature.Geometry);
                feature.Geometry = GeometryEngine.Simplify(geometry);
                await table.UpdateAsync(feature);
                if (table.HasEdits)
                {
                    // Pushes geometry edits back to the server.
                    var result = await table.ApplyEditsAsync();
                    if (result.UpdateResults == null || result.UpdateResults.Count < 1)
                        return;
                    var updateResult = result.UpdateResults[0];
                    if (updateResult.Error != null)
                        message = updateResult.Error.Message;
                }

            }
            catch (TaskCanceledException te)
            {
                // Handles canceling out of Editor.
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            finally
            {
                SetGeometryEditor();
                if (layer.LayerDefinitions != null)
                {
                    layer.LayerDefinitions.Clear();
                    // Refreshes layer to reflect geometry edits.
                    layer.Invalidate();
                }
            }
            if (!string.IsNullOrWhiteSpace(message))
                MessageBox.Show(message);
        }
        private async void Initialize()
        {
            // Create a tile cache and load it with the SanFrancisco streets tpk
            TileCache tileCache = new TileCache(GetTpkPath());

            // Create the corresponding layer based on the tile cache
            ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);

            // Create the basemap based on the tile cache
            Basemap sfBasemap = new Basemap(tileLayer);

            // Create the map with the tile-based basemap
            Map myMap = new Map(sfBasemap);

            // Assign the map to the MapView
            myMapView.Map = myMap;

            // Create a new symbol for the extent graphic
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);

            // Create graphics overlay for the extent graphic and apply a renderer
            GraphicsOverlay extentOverlay = new GraphicsOverlay();

            extentOverlay.Renderer = new SimpleRenderer(lineSymbol);

            // Add graphics overlay to the map view
            myMapView.GraphicsOverlays.Add(extentOverlay);

            // Set up an event handler for when the viewpoint (extent) changes
            myMapView.ViewpointChanged += MapViewExtentChanged;

            // Set up an event handler for 'tapped' events
            myMapView.GeoViewTapped += GeoViewTapped;

            // Update the local data path for the geodatabase file
            String iOSFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

            _gdbPath = Path.Combine(iOSFolder, "wildfire.geodatabase");

            // Create a task for generating a geodatabase (GeodatabaseSyncTask)
            _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);

            // Add all graphics from the service to the map
            foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
            {
                // Get the Uri for this particular layer
                Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);

                // Create the ServiceFeatureTable
                ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);

                // Wait for the table to load
                await onlineTable.LoadAsync();

                // Add the layer to the map's operational layers if load succeeds
                if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
                {
                    myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
                }
            }
        }