public int CountSelection(QueryFilter filter = null) { if (filter == null) { return(SelectionCount); } var selection = _layer.GetSelection(); var filtered = selection.Select(filter); return(filtered.GetCount()); }
public static IEnumerable <Feature> GetSelectedFeatures([CanBeNull] BasicFeatureLayer layer) { Selection selection = layer?.GetSelection(); if (selection == null) { yield break; } RowCursor cursor = selection.Search(null, false); try { while (cursor.MoveNext()) { var feature = (Feature)cursor.Current; yield return(feature); } } finally { cursor.Dispose(); } }
/// <summary> /// Get Selected Guid From Active Map /// </summary> /// <returns>Collection of GUID</returns> internal static List <Guid> GetSelectedGuidFromActiveMap() { List <Guid> listIds = new List <Guid>(); Map map = MapView.Active.Map; Dictionary <MapMember, List <long> > selected = map.GetSelection().ToDictionary(); foreach (var v in selected) { if (v.Key.GetType() == typeof(FeatureLayer)) { FeatureLayer fl = v.Key as FeatureLayer; Selection sel = fl.GetSelection(); //Table table = fl.GetTable(); QueryFilter queryFilter = new QueryFilter { ObjectIDs = sel.GetObjectIDs(), SubFields = "*" }; RowCursor cursor = sel.Search(queryFilter); while (cursor.MoveNext()) { Row row = cursor.Current; listIds.Add(row.GetGlobalID()); } } else if (v.Key.GetType() == typeof(BasicFeatureLayer)) { BasicFeatureLayer fl = v.Key as BasicFeatureLayer; Selection sel = fl.GetSelection(); if (sel.SelectionType == SelectionType.GlobalID) { listIds.AddRange(sel.GetGlobalIDs()); } else { listIds.AddRange(GetGuidFromLayer(fl, sel)); } } } return(listIds); }
/// <summary> /// Get the selected features GUID from the active map /// </summary> /// <returns>List of GUID</returns> internal static List <Guid> GetSelectedGuidFromActiveMap() { List <Guid> listIds = new List <Guid>(); Map map = MapView.Active.Map; SelectionSet selected = map.GetSelection(); foreach (var v in selected.ToDictionary()) { if (v.Key.GetType() == typeof(FeatureLayer)) { FeatureLayer fl = v.Key as FeatureLayer; Selection sel = fl.GetSelection(); if (sel.SelectionType == ArcGIS.Core.Data.SelectionType.GlobalID) { listIds.AddRange(sel.GetGlobalIDs()); } else { listIds.AddRange(GetGuidFromLayer(fl, sel)); } } else if (v.Key.GetType() == typeof(BasicFeatureLayer)) { BasicFeatureLayer fl = v.Key as BasicFeatureLayer; Selection sel = fl.GetSelection(); if (sel.SelectionType == ArcGIS.Core.Data.SelectionType.GlobalID) { listIds.AddRange(sel.GetGlobalIDs()); } else { listIds.AddRange(GetGuidFromLayer(fl, sel)); } } } return(listIds); }
protected override async void OnClick() { SharedFunctions.Log("Search for candidate dams started"); pointsIntervalOnContour = Convert.ToInt32(Parameter.PointIntervalBox.Text); DateTime startTime = DateTime.Now; chosenCandidates = new List <CandidateDam>(); PotentialCandidates = 0; var pd = new ProgressDialog("Search for candidate dams", "Canceled", 100, false); cps = new CancelableProgressorSource(pd); cps.Progressor.Max = 100; PointsAnalyzed = 0; TotalPointsCount = 0; try { await Project.Current.SaveEditsAsync(); BasicFeatureLayer layer = null; await QueuedTask.Run(async() => { if (!SharedFunctions.LayerExists("ContourPoints")) { return; } CancellationToken ctoken = new CancellationToken(); //create line feature layer if it does not exist BasicFeatureLayer damCandidatesLayer = await CreateDamFeatureClass("DamCandidates"); var contourPointsLayer = MapView.Active.Map.FindLayers("ContourPoints").FirstOrDefault(); layer = contourPointsLayer as BasicFeatureLayer; // store the spatial reference of the current layer SpatialReference = layer.GetSpatialReference(); //Cursor for selected points RowCursor cursor = layer.GetSelection().Search(); //If no selection was set, use full points layer if (layer.GetSelection().GetCount() == 0) { cursor = layer.Search(); } Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > > contourHeights = new Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > >(); cps.Progressor.Status = "Loading ContourPoints into memory"; SharedFunctions.Log("Loading all ContourPoints into memory"); while (cursor.MoveNext()) { if (ctoken.IsCancellationRequested) { SharedFunctions.Log("Canceled"); return; } using (Row row = cursor.Current) { var point = row[1] as MapPoint; var pointID = (int)row[0]; var contourHeight = (int)(double)row[4]; var contourID = (int)row[2]; if (!ContourLengths.ContainsKey(contourID)) { ContourLengths.Add(contourID, (double)row["Shape_Length"]); } if (!contourHeights.ContainsKey((int)contourHeight)) { contourHeights.Add((int)contourHeight, new SortedDictionary <int, SortedDictionary <long, MapPoint> >()); } if (!contourHeights[contourHeight].ContainsKey((int)contourID)) { contourHeights[contourHeight].Add((int)contourID, new SortedDictionary <long, MapPoint>()); } contourHeights[contourHeight][(int)contourID].Add(pointID, point); TotalPointsCount++; } } cps.Progressor.Status = "Analyze Contours"; SharedFunctions.Log("Analyze Contours"); bool multiThreading = (Parameter.MultiThreadingBox == null || !Parameter.MultiThreadingBox.IsChecked.HasValue || Parameter.MultiThreadingBox.IsChecked.Value); if (multiThreading) { HeightsToProcess = contourHeights.Keys.ToList(); int ThreadCount = Math.Min(HeightsToProcess.Count, Environment.ProcessorCount); SharedFunctions.Log("Divided work into " + ThreadCount + " threads..."); await Task.WhenAll(Enumerable.Range(1, ThreadCount).Select(c => Task.Run( () => { while (HeightsToProcess.Count > 0) // && !ctoken.IsCancellationRequested) { int height = -1; lock (HeightsToProcess) { height = HeightsToProcess.FirstOrDefault(); if (height != 0) { HeightsToProcess.Remove(height); } } if (height != -1) { var calc = new Dictionary <int, SortedDictionary <int, SortedDictionary <long, MapPoint> > >(); calc.Add(height, contourHeights[height]); AnalyseContourHeights(calc, ctoken); } } } , ctoken)) ); } else { //Single Thread: AnalyseContourHeights(contourHeights, ctoken); } cps.Progressor.Status = "Saving all " + chosenCandidates.Count + " candidates"; SharedFunctions.Log("Saving all " + chosenCandidates.Count + " candidates"); foreach (var candidate in chosenCandidates) { if (ctoken.IsCancellationRequested) { SharedFunctions.Log("Canceled"); return; } //Create coordinates for Polyline Feature with height ContourHeight + 5 Meters! List <Coordinate3D> coordinates = new List <Coordinate3D>() { new Coordinate3D(candidate.StartPoint.X, candidate.StartPoint.Y, candidate.ContourHeight + 5), new Coordinate3D(candidate.EndPoint.X, candidate.EndPoint.Y, candidate.ContourHeight + 5) }; //save all selected candidates into the db var attributes = new Dictionary <string, object> { { "Shape", PolylineBuilder.CreatePolyline(coordinates) }, { "ContourID", (long)candidate.ContourID }, { "StartPointID", (long)candidate.StartPointID }, { "EndPointID", (long)candidate.EndPointID }, { "ContourHeight", (short)candidate.ContourHeight }, { "LengthRating", (float)candidate.Rating }, { "DistanceOnLine", (long)candidate.DistanceOnLine }, { "Length", (short)candidate.Length }, { "StartPointDistance", (long)candidate.StartPointDistance }, { "EndPointDistance", (long)candidate.EndPointDistance }, { "DamSpansContourStart", (short)(candidate.DamSpansContourStart ? 1 : 0) } }; var editOp = new EditOperation() { Name = "Create dam candidate", SelectNewFeatures = false }; editOp.Create(damCandidatesLayer, attributes); ////Execute the operations editOp.Execute(); } }, cps.Progressor); //save all edits await Project.Current.SaveEditsAsync(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { DateTime endTime = DateTime.Now; SharedFunctions.Log("Analysed " + PotentialCandidates.ToString("N0") + " candidates ( " + chosenCandidates.Count.ToString("N0") + " selected) in " + (endTime - startTime).TotalSeconds.ToString("N") + " seconds"); } }
private async static void Visualize(BasicFeatureLayer dam3dLayer, BasicFeatureLayer reservoirVisLayer, BasicFeatureLayer reservoirSurfacesLayer, BasicFeatureLayer damLayer) { SharedFunctions.DeleteAllFeatures(reservoirVisLayer); SharedFunctions.DeleteAllFeatures(dam3dLayer); List <long> damIDs = new List <long>(); var reservoirPairsLayer = MapView.Active.Map.FindLayers("ReservoirPairs").FirstOrDefault(); if (reservoirPairsLayer != null && ((BasicFeatureLayer)reservoirPairsLayer).SelectionCount > 0) { var reservoirPairsCursor = ((BasicFeatureLayer)reservoirPairsLayer).GetSelection().Search(); while (reservoirPairsCursor.MoveNext()) { using (Row row = reservoirPairsCursor.Current) { int damId = (int)row["LowerDamId"]; if (!damIDs.Contains(damId)) { damIDs.Add(damId); } damId = (int)row["UpperDamId"]; if (!damIDs.Contains(damId)) { damIDs.Add(damId); } } } } if (damLayer.SelectionCount > 0) { var damCursor = damLayer.GetSelection().Search(); while (damCursor.MoveNext()) { using (Row row = damCursor.Current) { int damId = (int)row["ObjectID"]; if (!damIDs.Contains(damId)) { damIDs.Add(damId); } } } } List <CandidateDam> candidates = new List <CandidateDam>(); SharedFunctions.LoadDamCandidatesFromLayer(candidates, damLayer); foreach (var dam in candidates.Where(c => damIDs.Contains(c.ObjectID)).ToList()) { double contourHeight = dam.ContourHeight; try { MapPoint startPoint = dam.StartPoint; MapPoint endPoint = dam.EndPoint; double damHeight = (double)dam.DamHeight; double damLength = (double)dam.Length; Coordinate3D coord1 = startPoint.Coordinate3D; int factor = ((startPoint.Y <endPoint.Y && startPoint.X> endPoint.X) || (startPoint.Y > endPoint.Y && startPoint.X < endPoint.X) ) ? 1 : -1; Coordinate3D coord2 = new Coordinate3D(coord1.X + factor * damHeight / damLength * Math.Abs(startPoint.Y - endPoint.Y) //X , coord1.Y + damHeight / damLength * Math.Abs(startPoint.X - endPoint.X) //Y , coord1.Z - damHeight); //Z Coordinate3D coord3 = new Coordinate3D(coord1.X - factor * damHeight / damLength * Math.Abs(startPoint.Y - endPoint.Y) //X , coord1.Y - damHeight / damLength * Math.Abs(startPoint.X - endPoint.X) //Y , coord1.Z - damHeight); //Z //Workaround for Bug in ArcGIS Pro 2.4.1: if values are equal, extrusion will fail coord2.X += 0.1; coord2.Y += 0.1; coord3.X += 0.1; coord3.Y += 0.1; List <Coordinate3D> coords = new List <Coordinate3D>(); coords.Add(coord1); coords.Add(coord2); coords.Add(coord3); var newPolygon3D = PolygonBuilder.CreatePolygon(coords, SpatialReference); Coordinate3D coord = new Coordinate3D(endPoint.X - startPoint.X, endPoint.Y - startPoint.Y, 0.1); var multipatch = GeometryEngine.Instance.ConstructMultipatchExtrudeAlongVector3D(newPolygon3D, coord); var attributes2 = new Dictionary <string, object> { { "Shape", multipatch }, { "DamID", (long)dam.ObjectID } }; var createOperation2 = new EditOperation() { Name = "Create multipatch", SelectNewFeatures = false }; createOperation2.Create(dam3dLayer, attributes2); await createOperation2.ExecuteAsync(); //add SurfacePolygon to Visualization: var queryFilter = new QueryFilter { WhereClause = string.Format("DamID = {0}", dam.ObjectID) }; var surfaceCursor = reservoirSurfacesLayer.Select(queryFilter).Search(); if (surfaceCursor.MoveNext()) { using (Row row = surfaceCursor.Current) { var polygon = (row as Feature).GetShape() as Polygon; attributes2 = new Dictionary <string, object> { { "Shape", polygon }, { "DamID", (long)dam.ObjectID } }; var createOperationSurface = new EditOperation() { Name = "Create surface", SelectNewFeatures = false }; createOperationSurface.Create(reservoirVisLayer, attributes2); await createOperationSurface.ExecuteAsync(); } } } catch (Exception ex) { SharedFunctions.Log("Error for 3D Dam with DamID " + dam.ObjectID + ": " + ex.Message); } SharedFunctions.Log("3D Dam created for Dam " + dam.ObjectID); } await Project.Current.SaveEditsAsync(); }
//Using Inspector... internal async void UpdateAnnotation() { BasicFeatureLayer annoLayer = MapView.Active.Map.GetLayersAsFlattenedList().First() as BasicFeatureLayer; var oid = 1; #region Update Annotation Text await QueuedTask.Run(() => { //annoLayer is ~your~ Annotation layer... // use the inspector methodology var insp = new Inspector(true); insp.Load(annoLayer, oid); // get the annotation properties AnnotationProperties annoProperties = insp.GetAnnotationProperties(); // set the attribute annoProperties.TextString = "Hello World"; // assign the annotation proeprties back to the inspector insp.SetAnnotationProperties(annoProperties); //create and execute the edit operation EditOperation op = new EditOperation(); op.Name = "Update annotation"; op.Modify(insp); op.Execute(); }); #endregion #region Modify Annotation Shape await QueuedTask.Run(() => { //Don't use 'Shape'....Shape is the bounding box of the annotation text. This is NOT what you want... // //var insp = new Inspector(); //insp.Load(annoLayer, oid); //var shape = insp["SHAPE"] as Polygon; //...wrong shape... //Instead, we must use the AnnotationProperties //annoLayer is ~your~ Annotation layer var insp = new Inspector(true); insp.Load(annoLayer, oid); AnnotationProperties annoProperties = insp.GetAnnotationProperties(); var shape = annoProperties.Shape; if (shape.GeometryType != GeometryType.GeometryBag) { var newGeometry = GeometryEngine.Instance.Move(shape, 10, 10); annoProperties.Shape = newGeometry; insp.SetAnnotationProperties(annoProperties); EditOperation op = new EditOperation(); op.Name = "Change annotation angle"; op.Modify(insp); op.Execute(); } }); #endregion #region Modify Annotation Text Graphic await QueuedTask.Run(() => { var selection = annoLayer.GetSelection(); if (selection.GetCount() == 0) { return; } // use the first selelcted feature var insp = new Inspector(true); insp.Load(annoLayer, selection.GetObjectIDs().FirstOrDefault()); // getAnnoProperties should return null if not an annotation feature AnnotationProperties annoProperties = insp.GetAnnotationProperties(); // get the textGraphic CIMTextGraphic textGraphic = annoProperties.TextGraphic; // change text textGraphic.Text = "Hello world"; // set x,y offset via the symbol var symbol = textGraphic.Symbol.Symbol; var textSymbol = symbol as CIMTextSymbol; textSymbol.OffsetX = 2; textSymbol.OffsetY = 3; textSymbol.HorizontalAlignment = HorizontalAlignment.Center; // load the updated textGraphic annoProperties.LoadFromTextGraphic(textGraphic); // assign the annotation properties back insp.SetAnnotationProperties(annoProperties); EditOperation op = new EditOperation(); op.Name = "modify symbol"; op.Modify(insp); bool result = op.Execute(); }); #endregion }
/// <summary> /// マップ内の選択状態が変わった場合に発生 /// </summary> private void OnMapSelectionChanged(MapSelectionChangedEventArgs args) { var mapView = MapView.Active; if (mapView == null) { return; } RemoveFromMapOverlay(); // アノテーション操作タブの場合 if (_tabPage == 2) { QueuedTask.Run(() => { var selection = mapView.Map.GetSelection(); // 選択しているフィーチャクラスがある場合 if (selection.Count > 0) { var featureLayer = selection.FirstOrDefault().Key as BasicFeatureLayer; // アノテーションの場合 if (featureLayer.GetType().Name == "AnnotationLayer") { var table = featureLayer.GetTable(); var feature = featureLayer.GetSelection(); // OBJECTIDを指定 QueryFilter queryFilter = new QueryFilter { WhereClause = "ObjectId =" + feature.GetObjectIDs().First(), }; // 複数選択した場合は最初に取得したアノテーションの角度を使用する using (RowCursor rowCursor = table.Search(queryFilter)) { rowCursor.MoveNext(); using (Row row = rowCursor.Current) { // 角度取得 Angle = Convert.ToDouble(row["Angle"]); } } } } }); } else { QueuedTask.Run(() => { // レイヤーを選択していない場合 if (_selectedFeatureLayer == null) { return; } try { var listColumnNames = new List <KeyValuePair <string, string> >(); var listValues = new List <List <string> >(); // 選択したフィーチャを処理する using (var rowCursor = _selectedFeatureLayer.GetSelection().Search(null)) { bool bDefineColumns = true; while (rowCursor.MoveNext()) { var anyRow = rowCursor.Current; if (bDefineColumns) { // 選択したフィーチャのフィールドを取得 foreach (var fld in anyRow.GetFields().Where(fld => fld.FieldType != FieldType.Geometry)) { listColumnNames.Add(new KeyValuePair <string, string>(fld.Name, fld.AliasName)); } } // 選択したフィーチャの属性を取得 var newRow = new List <string>(); foreach (var fld in anyRow.GetFields().Where(fld => fld.FieldType != FieldType.Geometry)) { newRow.Add((anyRow[fld.Name] == null) ? string.Empty : anyRow[fld.Name].ToString()); } listValues.Add(newRow); bDefineColumns = false; } } // DataGridにカラムを設定 SelectedFeatureDataTable = new DataTable(); foreach (var col in listColumnNames) { SelectedFeatureDataTable.Columns.Add(new DataColumn(col.Key, typeof(string)) { Caption = col.Value }); } // DataGridに選択したフィーチャの属性を格納 foreach (var row in listValues) { var newRow = SelectedFeatureDataTable.NewRow(); newRow.ItemArray = row.ToArray(); SelectedFeatureDataTable.Rows.Add(newRow); } if (_selectedFeatureDataTable.Rows.Count > 0) { // ズーム ZoomToSelection(); } // データが多い場合たまにDataGridにデータが表示されないことがある。これで回避。 NotifyPropertyChanged(() => SelectedFeatureDataTable); } catch (Exception) { MessageBox.Show("フィーチャ属性の抽出に失敗しました。"); } }); } }
protected async void Button_Click(object sender, RoutedEventArgs e) { gesture = new List <Point>(); sketchPad.Children.Clear(); try { BasicFeatureLayer layer = null; List <Inspector> inspList = new List <Inspector>(); Inspector inspector = null; await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { //find selected layer if (MapView.Active.GetSelectedLayers().Count == 0) { //MessageBox.Show("Select a feature class from the Content 'Table of Content' first."); return; } layer = MapView.Active.GetSelectedLayers()[0] as BasicFeatureLayer; // get selected features from the map var features = layer.GetSelection(); if (features.GetCount() == 0) { return; /*ToDo : add error msg: no feature selected*/ } // get ids of all the selected features var featOids = features.GetObjectIDs(); if (featOids.Count == 0) {/* ToDo : something is wrong*/ } // adding the inspectors to a list so that separate id values can be assigned later for (int i = 0; i < featOids.Count; i++) { var insp = new Inspector(); insp.Load(layer, featOids.ElementAt(i)); inspList.Add(insp); } inspector = new Inspector(); inspector.Load(layer, featOids); }); if (layer == null) { } //MessageBox.Show("Unable to find a feature class at the first layer of the active map"); else { //update the attributes of those features // make sure tha attribute exists ArcGIS.Desktop.Editing.Attributes.Attribute att = inspector.FirstOrDefault(a => a.FieldName == "UID"); if (att == null) { // if the attribute doesn't exist we create a new field var dataSource = await GetDataSource(layer); //MessageBox.Show($@"{dataSource} was found ... adding a new Field"); await ExecuteAddFieldTool(layer, new KeyValuePair <string, string>("UID", "uniqueId"), "Text", 50); } await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { // we add values of ids to the selected features for (int i = 0; i < inspList.Count; i++) { if (inspList.ElementAt(i)["UID"] == null || (String)inspList.ElementAt(i)["UID"] == String.Empty) { // putting a random string now, this should be replaced by the tag user puts in after the recognition part is done. inspList.ElementAt(i)["UID"] = "newAtr" + attributeIndex++; var op = new EditOperation(); op.Name = "Update"; op.SelectModifiedFeatures = true; op.SelectNewFeatures = false; op.Modify(inspList.ElementAt(i)); op.Execute(); } } /* var att2 = insp.Select(a => a.FieldName == "UID"); * var att3 = insp.GroupBy(a => a.FieldName == "UID"); * var att4 = insp.Any(a => a.FieldName == "UID"); * var att5 = insp.Where(a => a.FieldName == "UID")*/ //insp["UID"] = "newAtr"; }); } } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } }