private static void ResetLabels()
        {
            QueuedTask.Run(async() =>
            {
                //Get the line feature we want to clear labels for
                var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().Where(f => f.Name == "U.S. Rivers (Generalized)").FirstOrDefault() as FeatureLayer;
                if (featureLayer == null)
                {
                    return;
                }

                // create an instance of the inspector class
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector();

                //Clear the previous "Yes" values for the LabelOn field.
                //Create a QueryFilter to search for all features that have the LabelOn field value set at Yes.
                var qf = new QueryFilter
                {
                    WhereClause = "LabelOn = 'Yes'"
                };
                var selectionLabelOnYes = featureLayer.Select(qf);
                var featuresToClear     = selectionLabelOnYes.GetObjectIDs()?.ToList();
                if (featuresToClear.Count > 0)
                {
                    // load the features into the inspector using a list of object IDs
                    await inspector.LoadAsync(featureLayer, featuresToClear);

                    // assign the attribute value of "No" to the field "LabelOn"
                    // if more than one features are loaded, the change applies to all features
                    inspector["LabelOn"] = "No";
                    // apply the changes as an edit operation
                    await inspector.ApplyAsync();
                }
            });
        }
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected async override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (CurrentTemplate == null || geometry == null)
            {
                //return Task.FromResult(false);
                return(false);
            }

            await QueuedTask.Run(async() =>
            {
                // Create an EditOperation and make updates using Inspector
                var createOperation  = new EditOperation();
                createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name);
                createOperation.SelectNewFeatures = true;
                createOperation.Create(CurrentTemplate, geometry);
                await createOperation.ExecuteAsync();
                var selectedFeatures = ArcGIS.Desktop.Mapping.MapView.Active.Map.GetSelection();
                var inspector        = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                inspector.Load(selectedFeatures.ToDictionary().Keys.First(), selectedFeatures.ToDictionary().Values.First());
                var squarefeetValue = inspector["Shape_Area"];
                long squarefeetValueLong;
                squarefeetValueLong        = Convert.ToInt64(squarefeetValue);
                inspector["High"]          = (squarefeetValueLong / _dockpane.HighSetting);
                inspector["Medium"]        = (squarefeetValueLong / _dockpane.MediumSetting);
                inspector["Low"]           = (squarefeetValueLong / _dockpane.LowSetting);
                inspector["HighSetting"]   = _dockpane.HighSetting;
                inspector["MediumSetting"] = _dockpane.MediumSetting;
                inspector["LowSetting"]    = _dockpane.LowSetting;
                inspector["TargetSetting"] = _dockpane.TargetSetting;
                await inspector.ApplyAsync();
                _dockpane.GetTotalValues();
            });

            return(true);
        }
        /// <summary>
        /// Called when the sketch finishes. This is where we will create the sketch operation and then execute it.
        /// </summary>
        /// <param name="geometry">The geometry created by the sketch.</param>
        /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
        protected async override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            if (CurrentTemplate == null || geometry == null)
            {
                //return Task.FromResult(false);
                return(false);
            }

            await QueuedTask.Run(async() =>
            {
                // Create an edit operation
                var createOperation  = new EditOperation();
                createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name);
                createOperation.SelectNewFeatures = true;
                createOperation.Create(CurrentTemplate, geometry);
                await createOperation.ExecuteAsync();
                var selectedFeatures = ArcGIS.Desktop.Mapping.MapView.Active.Map.GetSelection();
                // get the first layer and its corresponding selected feature OIDs
                var firstSelectionSet = selectedFeatures.First();
                // create an instance of the inspector class
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector();
                // load the selected features into the inspector using a list of object IDs
                inspector.Load(firstSelectionSet.Key, firstSelectionSet.Value);
                var squarefeetValue = inspector["Shape_Area"];
                long squarefeetValueLong;
                squarefeetValueLong        = Convert.ToInt64(squarefeetValue);
                inspector["High"]          = (squarefeetValueLong / _dockpane.HighSetting);
                inspector["Medium"]        = (squarefeetValueLong / _dockpane.MediumSetting);
                inspector["Low"]           = (squarefeetValueLong / _dockpane.LowSetting);
                inspector["HighSetting"]   = _dockpane.HighSetting;
                inspector["MediumSetting"] = _dockpane.MediumSetting;
                inspector["LowSetting"]    = _dockpane.LowSetting;
                inspector["TargetSetting"] = _dockpane.TargetSetting;
                await inspector.ApplyAsync();
                _dockpane.GetTotalValues();
            });

            return(true);
        }
Exemplo n.º 4
0
        public async void CalculateVolume()
        {
            // Update the viewmodel with values
            await FrameworkApplication.SetCurrentToolAsync("esri_mapping_exploreTool");

            // Check for an active mapview
            if (MapView.Active == null)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No MapView currently active. Exiting...", "Info");
                return;
            }

            // Prompt before proceeding with calculation work
            var response = ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Save edits and calculate volume on selected features?", "Calculate Volume", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question);

            if (response == MessageBoxResult.No)
            {
                return;
            }

            // Save edits for reading by GP Tool
            await Project.Current.SaveEditsAsync();

            try
            {
                await QueuedTask.Run((Func <Task>)(async() =>
                {
                    var featLayer = MapView.Active.Map.FindLayers("Clip_Polygon_Asphalt").FirstOrDefault() as FeatureLayer;

                    // Get the selected records, and check/exit if there are none:
                    var featSelectionOIDs = featLayer.GetSelection().GetObjectIDs();
                    if (featSelectionOIDs.Count == 0)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("No records selected for layer, " + featLayer.Name + ". Exiting...", "Info");
                        return;
                    }

                    // Ensure value for reference plane direction combobox
                    else if (SceneCalcVM.ReferencePlaneDirection == string.Empty)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Choose the reference plane direction for volume calculation. Exiting...", "Value Needed");
                        return;
                    }

                    // Ensure there is a valid reference plane height/elevation value for all selected records
                    RowCursor cursorPolygons = featLayer.GetSelection().Search(null);
                    while (cursorPolygons.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons.Current)
                        {
                            // Get values for dockpane
                            if (currentRow["PlaneHeight"] == null || Convert.ToDouble(currentRow["PlaneHeight"]) == 0)
                            {
                                string currentObjectID = Convert.ToString(currentRow["ObjectID"]);
                                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Empty or invalid Plane Height value for polygon ObjectID: " + currentObjectID + ". Exiting...", "Value Needed");
                                return;
                            }
                        }
                    }

                    // Get the name of the attribute to update, and the value to set:
                    double refPlaneElevation = SceneCalcVM.ReferencePlaneElevation;
                    string refPlaneDirection = SceneCalcVM.ReferencePlaneDirection;

                    // Start progress dialog
                    var progDialog = new ProgressDialog("Calculating Volume");
                    var progSource = new ProgressorSource(progDialog);
                    progDialog.Show();

                    // Prepare for run of GP tool -- Get the path to the LAS point layer
                    string surfaceLASDataset = "Asphalt3D_132_point_cloud.las";
                    var inspector            = new ArcGIS.Desktop.Editing.Attributes.Inspector(true);
                    inspector.Load(featLayer, featSelectionOIDs);
                    inspector["PlaneDirection"]    = refPlaneDirection;
                    inspector["DateOfCapture"]     = DateTime.Today;
                    inspector["ElevationMeshFile"] = "Asphalt3D_132_3d_mesh.slpk";
                    inspector["PointCloudFile"]    = surfaceLASDataset;

                    var editOp  = new EditOperation();
                    editOp.Name = "Edit " + featLayer.Name + ", " + Convert.ToString(featSelectionOIDs.Count) + " records.";
                    editOp.Modify(inspector);
                    await editOp.ExecuteAsync();
                    await Project.Current.SaveEditsAsync();

                    // Get the path to the layer's feature class
                    string infc = featLayer.Name;
                    // Place parameters into an array
                    var parameters = Geoprocessing.MakeValueArray(surfaceLASDataset, infc, "PlaneHeight", refPlaneDirection);
                    // Place environment settings in an array, in this case, OK to over-write
                    var environments = Geoprocessing.MakeEnvironmentArray(overwriteoutput: true);
                    // Execute the GP tool with parameters
                    var gpResult = await Geoprocessing.ExecuteToolAsync("PolygonVolume_3d", parameters, environments);
                    // Save edits again
                    await Project.Current.SaveEditsAsync();

                    // var selFeatures = featLayer.GetSelection().GetCount();
                    RowCursor cursorPolygons2 = featLayer.GetSelection().Search(null);

                    double totalVolumeValue  = 0;
                    double totalAreaValue    = 0;
                    double totalWeightInTons = 0;
                    double currentVolume;
                    double currentSArea;
                    double currentWeightInTons;
                    long currentOID;

                    while (cursorPolygons2.MoveNext())
                    {
                        using (Row currentRow = cursorPolygons2.Current)
                        {
                            // Get values for dockpane
                            currentOID = currentRow.GetObjectID();
                            // Convert volume in cubic meters from source data to cubic feet:
                            currentVolume = Convert.ToDouble(currentRow["Volume"]) * 35.3147;
                            // Convert surface area value from square meters from source data to square feet:
                            currentSArea = Convert.ToDouble(currentRow["SArea"]) * 10.7639;
                            // Calculate estimated weight in tons = (volume in square foot * 103.7 pounds per square foot) / 2000 pounds per ton
                            currentWeightInTons = (currentVolume * 103.7) / 2000;

                            // Update the new cubic feet and square feet values for the feature:
                            inspector.Load(featLayer, currentOID);
                            inspector["Volume"]          = currentVolume;
                            inspector["SArea"]           = currentSArea;
                            inspector["EstWeightInTons"] = currentWeightInTons;
                            await inspector.ApplyAsync();

                            // Combine values for display of total volume and surface area values in the dockpane:
                            totalVolumeValue  = totalVolumeValue + currentVolume;
                            totalAreaValue    = totalAreaValue + currentSArea;
                            totalWeightInTons = totalWeightInTons + currentWeightInTons;
                        }
                    }

                    // Apply the values and refresh selection update
                    await Project.Current.SaveEditsAsync();
                    FeatureSelectionChanged();
                    // Close progress dialog
                    progDialog.Hide();
                    progDialog.Dispose();
                }));
            }
            catch (Exception exc)
            {
                // Catch any exception found and display a message box.
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught while trying to perform update: " + exc.Message);
                return;
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// The features are labeled using a Field in the feature layer. The field LabelOn has values Yes or No.
        /// If the value is "Yes", that feature will be labeled. If value is No, the feature will not be labeled.
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        protected override Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            QueuedTask.Run(async() =>
            {
                //select features that intersect the sketch geometry
                var selection = MapView.Active.SelectFeatures(geometry, SelectionCombinationMethod.New);
                //Get the line feature we want to label
                var featureLayer = selection.Where(f => f.Key.Name == "U.S. Rivers (Generalized)").FirstOrDefault().Key as FeatureLayer;
                if (featureLayer == null)
                {
                    return;
                }
                //Get the list of line features that are selected
                var oidsOfSelectedFeature = selection[featureLayer];
                if (oidsOfSelectedFeature.Count == 0)
                {
                    return;
                }

                //We want to only label the selected features. So..
                //Clear the previous "Yes" values for the LabelOn field.
                //Create a QueryFilter to search for all features that have the LabelOn field value set at Yes.
                // create an instance of the inspector class
                var inspector = new ArcGIS.Desktop.Editing.Attributes.Inspector();

                var qf = new QueryFilter
                {
                    WhereClause = "LabelOn = 'Yes'"
                };
                var selectionLabelOnYes = featureLayer.Select(qf);
                var featuresToClear     = selectionLabelOnYes.GetObjectIDs()?.ToList();
                if (featuresToClear.Count > 0)
                {
                    // load the features into the inspector using a list of object IDs
                    await inspector.LoadAsync(featureLayer, featuresToClear);

                    // assign the attribute value of "No" to the field "LabelOn"
                    // if more than one features are loaded, the change applies to all features
                    inspector["LabelOn"] = "No";
                    // apply the changes as an edit operation
                    await inspector.ApplyAsync();
                }

                //Now modify the features that are selected by the tool to have the value Yes
                await inspector.LoadAsync(featureLayer, oidsOfSelectedFeature);
                // assign the attribute value of "Yes" to the field "LabelOn" for the features selected
                // if more than one features are loaded, the change applies to all features
                inspector["LabelOn"] = "Yes";
                // apply the changes as an edit operation
                await inspector.ApplyAsync();
                //Get the layer's definition
                var lyrDefn = featureLayer.GetDefinition() as CIMFeatureLayer;
                //Get the label classes - and check if the correct label class we need to label the line features with exists
                var listLabelClasses = lyrDefn.LabelClasses.ToList();
                var theLabelClass    = listLabelClasses.Where(l => l.Name == "LabelSelectedManyFeaturesWithLength").FirstOrDefault();
                if (theLabelClass == null) //create label class and add to the collection
                {
                    theLabelClass = await CreateAndApplyLabelClassAsync(featureLayer);
                    listLabelClasses.Add(theLabelClass);
                }

                //Turn off all the label classes except this one
                foreach (var lc in listLabelClasses)
                {
                    lc.Visibility = lc.Name == "LabelSelectedManyFeaturesWithLength" ? true : false;
                }
                //Apply the label classes back to the layer definition
                lyrDefn.LabelClasses = listLabelClasses.ToArray();
                //Set the layer definition
                featureLayer.SetDefinition(lyrDefn);
                //set the label's visiblity
                featureLayer.SetLabelVisibility(true);
            });
            return(base.OnSketchCompleteAsync(geometry));
        }