/// <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 override Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (CurrentTemplate == null || geometry == null) { return(Task.FromResult(false)); } // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name); createOperation.SelectNewFeatures = true; // Queue feature creation createOperation.Create(CurrentTemplate, geometry); //this is the centerpoint var anglebetweenpoints_degrees = 360 / CircelNumberOfPoints; var anglebetweenpoints_radians = Math.PI * anglebetweenpoints_degrees / 180.0; var radius = Circle; for (int i = 0; i < CircelNumberOfPoints; i++) { var xoffset = radius * Math.Cos((i * anglebetweenpoints_radians)); var yoffset = radius * Math.Sin((i * anglebetweenpoints_radians)); Geometry geom = GeometryEngine.Instance.Move(geometry, xoffset, yoffset); var attributes = new Dictionary <string, object>(); attributes.Add("SHAPE", geom); attributes.Add("Name", (i * anglebetweenpoints_degrees).ToString()); createOperation.Create(CurrentTemplate.Layer, attributes); } // Execute the operation return(createOperation.ExecuteAsync()); }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { //Run on MCT return(QueuedTask.Run(() => { //get the templates var map = MapView.Active.Map; IEnumerable <Layer> layers = map.GetLayersAsFlattenedList().AsEnumerable(); Layer mainLayer = layers.FirstOrDefault(l => l.Name == "main"); Layer mhLayer = layers.FirstOrDefault(l => l.Name == "manhole"); Layer conLayer = layers.FirstOrDefault(l => l.Name == "connector"); if ((mainLayer == null) || (mhLayer == null) || (conLayer == null)) { return false; } var mainTemplate = mainLayer.GetTemplate("main"); var mhTemplate = mhLayer.GetTemplate("manhole"); var conTemplate = conLayer.GetTemplate("connector"); if ((mainTemplate == null) || (mhTemplate == null) || (conTemplate == null)) { return false; } var op = new EditOperation() { Name = "Create main-connector-manhole", SelectModifiedFeatures = false, SelectNewFeatures = false }; //create the main geom var mainGeom = GeometryEngine.Instance.Move(geometry, 0, 0, -20); op.Create(mainTemplate, mainGeom); //create manhole points and connector foreach (var pnt in ((Polyline)geometry).Points) { //manhole point at sketch vertex op.Create(mhTemplate, pnt); //vertical connector between mahole and main var conPoints = new List <MapPoint> { pnt, //top of vertical connector GeometryEngine.Instance.Move(pnt, 0, 0, -20) as MapPoint //bottom of vertical connector }; var conPolyLine = PolylineBuilderEx.CreatePolyline(conPoints); op.Create(conTemplate, conPolyLine); } return op.Execute(); })); }
private void MoveWalls(MapViewMouseButtonEventArgs e) { QueuedTask.Run(() => { Dictionary <MapMember, List <long> > selectedItems = GetSelectedItems(e); EditOperation editOperation = new EditOperation(); foreach (KeyValuePair <MapMember, List <long> > item in selectedItems) { BasicFeatureLayer layer = item.Key as BasicFeatureLayer; if (layer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon) { continue; } foreach (long oid in item.Value) { var feature = layer.Inspect(oid); double hoogte = double.Parse(feature["PandHoogte"].ToString()); int verdieping = int.Parse(feature["Verdieping"].ToString()); Geometry geom = feature.Shape.Clone(); Geometry removeGeometry = GeometryEngine.Scale(geom, geom.Extent.Center, 1.2, 1.2); Geometry wallGeometry = GeometryEngine.Scale(geom, geom.Extent.Center, 1.3, 1.3); editOperation.Scale(selectedItems, feature.Shape.Extent.Center, 0.9, 0.9); editOperation.Create(layer, wallGeometry, new Action <long>(x => OnExtractWalls(x, layer, removeGeometry, hoogte, verdieping))); } editOperation.Execute(); } MapView.Active.Map.SetSelection(null); }); }
/// <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 override Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (CurrentTemplate == null || geometry == null) { return(Task.FromResult(false)); } return(QueuedTask.Run(() => { //apply overrides if (UseSubtypeChoiceOverride) { var choice = Module1.Current.SelectedSubtypeChoice; this.CurrentTemplate.Inspector["SUBTYPEFIELD"] = choice.SubtypefieldValue; this.CurrentTemplate.Inspector["FEATURECODE"] = choice.FeatureCodeValue; } else { this.CurrentTemplate.Inspector.Cancel(); } // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name); createOperation.SelectNewFeatures = true; // Queue feature creation createOperation.Create(CurrentTemplate, geometry); return createOperation.Execute(); })); }
/// <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); }
public void EditOperation(UtilityNetwork utilityNetwork, AssetType poleAssetType, Guid poleGlobalID, AssetType transformerBankAssetType, Guid transformerBankGlobalID) { #region Create a utility network association // Create edit operation EditOperation editOperation = new EditOperation(); editOperation.Name = "Create structural attachment association"; // Create a RowHandle for the pole Element poleElement = utilityNetwork.CreateElement(poleAssetType, poleGlobalID); RowHandle poleRowHandle = new RowHandle(poleElement, utilityNetwork); // Create a RowHandle for the transformer bank Element transformerBankElement = utilityNetwork.CreateElement(transformerBankAssetType, transformerBankGlobalID); RowHandle transformerBankRowHandle = new RowHandle(transformerBankElement, utilityNetwork); // Attach the transformer bank to the pole StructuralAttachmentAssociationDescription structuralAttachmentAssociationDescription = new StructuralAttachmentAssociationDescription(poleRowHandle, transformerBankRowHandle); editOperation.Create(structuralAttachmentAssociationDescription); editOperation.Execute(); #endregion }
protected override void OnClick() { var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().First(); QueuedTask.Run(() => { var fc = polyLayer.GetTable() as FeatureClass; var fcDefinition = fc.GetDefinition(); Polygon outerRings = null; var editOperation = new EditOperation(); editOperation.Name = "Create outer ring"; using (var cursor = fc.Search()) { while (cursor.MoveNext()) { Feature feature = cursor.Current as Feature; outerRings = Module1.Current.GetOutermostRings(feature.GetShape() as Polygon); editOperation.Create(polyLayer, outerRings); } } editOperation.Execute(); }); }
/// <summary> /// Called when the "Create" button is clicked. This is where we will create the edit operation and then execute it. /// </summary> /// <param name="geometry">The geometry created by the sketch - will be null because SketchType = SketchGeometryType.None</param> /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns> protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (CurrentTemplate == null) { return(Task.FromResult(false)); } // geometry will be null // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", CurrentTemplate.StandaloneTable.Name); createOperation.SelectNewFeatures = false; // determine the number of rows to add var numRows = this.CurrentTemplateRows; for (int idx = 0; idx < numRows; idx++) { // Queue feature creation createOperation.Create(CurrentTemplate, null); } // Execute the operation var returnVal = createOperation.ExecuteAsync(); ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($"{numRows} records added to {CurrentTemplate.StandaloneTable.Name} table."); return(returnVal); }
protected override void OnClick() { var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(); QueuedTask.Run(() => { var fc = polyLayer.GetTable() as FeatureClass; var fcDefinition = fc.GetDefinition(); Polygon outerRings = null; var editOperation = new EditOperation(); editOperation.Name = "Create outer ring"; using (var cursor = fc.Search()) { while (cursor.MoveNext()) { Feature feature = cursor.Current as Feature; outerRings = Module1.Current.GetOutermostRings(feature.GetShape() as Polygon); editOperation.Create(polyLayer, outerRings); } } editOperation.Execute(); }); }
private Task <bool> CreateLocations(FeatureLayer pointFeatureLayer, IReadOnlyList <Location> locations) { return(QueuedTask.Run(() => { var createOperation = new EditOperation() { Name = "Generate points", SelectNewFeatures = false }; foreach (var location in locations) { var firstfeature = location.Feature; var jfeature = firstfeature as JObject; var token = jfeature.GetValue("type").ToString(); if (token == "Point") { var p = jfeature.ToObject <GeoJSON.Net.Geometry.Point>(); var mapView = MapView.Active; var newMapPoint = MapPointBuilder.CreateMapPoint(p.Coordinates.Longitude, p.Coordinates.Latitude, SpatialReferences.WGS84); var atts = new Dictionary <string, object>(); atts.Add("id", location.Id); atts.Add("Shape", newMapPoint); atts.Add("description", location.Description); createOperation.Create(pointFeatureLayer, atts); } } return createOperation.ExecuteAsync(); })); }
/// <summary> /// Place curve on feature layer /// </summary> /// <param name="operation"></param> /// <param name="curve"></param> private static void showCurve(EditOperation operation, Curve curve, Point3d origin) { try { // TODO: come up with way of determining whether to make a curve // into a polyline or polygon depending on context/user preferences // var layer = getFeatureLayer(FeatureLayerType.GH_Preview_Polyline); var layer = getFeatureLayer(FeatureLayerType.GH_Preview_Polygon); if (layer == null) { return; } var projection = layer.GetSpatialReference(); var ptList = RhinoUtil.getPointsFromCurves(new List <Curve>() { curve }); var gisPts = ptList.Select(p => RhinoUtil.ptToGis(p, origin)).ToList(); var polyline = new PolygonBuilder(gisPts).ToGeometry(); // var polyline = PolylineBuilder.CreatePolyline(gisPts, projection); operation.Create(layer, polyline); operation.ExecuteAsync(); } catch { } }
protected override void OnClick() { if (Module1.Current.SelectedItems == null) { return; } int aantalVerdiepingen; double verdiepingsHoogte; QueuedTask.Run(() => { var editOperation = new EditOperation(); foreach (KeyValuePair <MapMember, List <long> > item in Module1.Current.SelectedItems) { var layer = item.Key as BasicFeatureLayer; foreach (long oid in item.Value) { var feature = layer.Inspect(oid); aantalVerdiepingen = new Random().Next(3, 10); verdiepingsHoogte = double.Parse(feature["PandHoogte"].ToString()) / aantalVerdiepingen; feature["PandHoogte"] = verdiepingsHoogte; editOperation.Modify(feature); for (int i = 1; i < aantalVerdiepingen; i++) { editOperation.Create(layer, GeometryEngine.Move(feature.Shape, 0, 0, (i * (verdiepingsHoogte * 2))), new Action <long>(x => newFloorCreated(x, layer, verdiepingsHoogte, feature.Shape.Extent.ZMin))); } } } bool succeded = editOperation.Execute(); }); }
protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry) { if (CurrentTemplate == null || geometry == null) { return(await Task.FromResult(false)); } Polyline polyline = geometry as ArcGIS.Core.Geometry.Polyline; //create the buffered geometry. change this to an async method that we can await //Geometry bufferedGeometry = GeometryEngine.Instance.Buffer(pts, BufferDistance); Geometry bufferedGeometry = await ConstructBuffers(polyline, BufferDistance, BufferRatio); // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", CurrentTemplate.Layer.Name); createOperation.SelectNewFeatures = true; // Queue feature creation createOperation.Create(CurrentTemplate, bufferedGeometry); // Execute the operation return(await createOperation.ExecuteAsync()); }
private void CutBuilding(MapViewMouseButtonEventArgs e) { QueuedTask.Run(() => { Dictionary <MapMember, List <long> > selectedItems = GetSelectedItems(e); EditOperation editOperation = new EditOperation(); foreach (KeyValuePair <MapMember, List <long> > item in selectedItems) { BasicFeatureLayer layer = item.Key as BasicFeatureLayer; if (layer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon) { continue; } foreach (long oid in item.Value) { var feature = layer.Inspect(oid); Geometry geometry = feature.Shape.Clone(); Polyline polyLine = GetCutPolyLine(geometry); var splitItems = GeometryEngine.Cut(geometry, polyLine); feature.Shape = splitItems.First(); editOperation.Modify(feature); Layer pointLayer = MapView.Active.Map.Layers[0]; editOperation.Create(pointLayer, geometry.Extent.Center); } editOperation.Execute(); } MapView.Active.Map.SetSelection(null); }); }
public void EditOperation2(FeatureLayer transformerBankLayer, Dictionary <string, object> transformerBankAttributes, FeatureLayer poleLayer, Dictionary <string, object> poleAttributes) { #region Create utility network features and associations in a single edit operation // Create an EditOperation EditOperation editOperation = new EditOperation(); editOperation.Name = "Create pole; create transformer bank; attach transformer bank to pole"; // Create the transformer bank RowToken transformerBankToken = editOperation.CreateEx(transformerBankLayer, transformerBankAttributes); // Create a pole RowToken poleToken = editOperation.CreateEx(poleLayer, poleAttributes); // Create a structural attachment association between the pole and the transformer bank RowHandle poleHandle = new RowHandle(poleToken); RowHandle transformerBankHandle = new RowHandle(transformerBankToken); StructuralAttachmentAssociationDescription poleAttachment = new StructuralAttachmentAssociationDescription(poleHandle, transformerBankHandle); editOperation.Create(poleAttachment); // Execute the EditOperation editOperation.Execute(); #endregion }
/// <summary> /// Create a single multi-point feature that is comprised of 20 points. /// </summary> /// <param name="multiPointLayer">Multi-point geometry feature layer used to add the multi-point feature.</param> /// <returns></returns> private Task ConstructSampleMultiPoints(FeatureLayer multiPointLayer) { // create a random number generator var randomGenerator = new Random(); // the database and geometry interactions are considered fine-grained and need to be executed on // a separate thread return(QueuedTask.Run(() => { // get the feature class associated with the layer var featureClass = multiPointLayer.GetTable() as FeatureClass; var featureClassDefinition = featureClass.GetDefinition() as FeatureClassDefinition; // store the spatial reference as its own variable var spatialReference = featureClassDefinition.GetSpatialReference(); // define an area of interest. Random points are generated in the allowed // confines of the allow extent range var areaOfInterest = MapView.Active.Extent; // start an edit operation to create new (random) multi-point feature var createOperation = new EditOperation() { Name = "Generate multipoints" }; // retrieve the class definition of the point feature class var classDefinition = featureClass.GetDefinition() as FeatureClassDefinition; Multipoint newPoints = null; // generate either 2D or 3D geometries if (classDefinition.HasZ()) { // 3D // create a list to hold the 20 coordinates of the multi-point feature IList <Coordinate3D> coordinateList = new List <Coordinate3D>(20); for (int i = 0; i < 20; i++) { coordinateList.Add(randomGenerator.NextCoordinate3D(areaOfInterest)); } newPoints = MultipointBuilder.CreateMultipoint(coordinateList, classDefinition.GetSpatialReference()); } else { // 2D // create a list to hold the 20 coordinates of the multi-point feature IList <Coordinate2D> coordinateList = new List <Coordinate2D>(20); for (int i = 0; i < 20; i++) { coordinateList.Add(randomGenerator.NextCoordinate2D(areaOfInterest)); } newPoints = MultipointBuilder.CreateMultipoint(coordinateList, classDefinition.GetSpatialReference()); } // create and execute the feature creation operation createOperation.Create(multiPointLayer, newPoints); return createOperation.ExecuteAsync(); })); }
/// <summary> /// Create sample polyline feature using the geometries from the point feature layer. /// </summary> /// <param name="polylineLayer">Polyline geometry feature layer used to add the new features.</param> /// <param name="pointLayer">The geometries from the point layer are used as vertices for the new line features.</param> /// <returns></returns> private Task <bool> constructSamplePolylines(FeatureLayer polylineLayer, FeatureLayer pointLayer) { // execute the fine grained API calls on the CIM main thread return(QueuedTask.Run(() => { // get the underlying feature class for each layer var polylineFeatureClass = polylineLayer.GetTable() as FeatureClass; var pointFeatureClass = pointLayer.GetTable() as FeatureClass; // retrieve the feature class schema information for the feature classes var polylineDefinition = polylineFeatureClass.GetDefinition() as FeatureClassDefinition; var pointDefinition = pointFeatureClass.GetDefinition() as FeatureClassDefinition; // construct a cursor for all point features, since we want all feature there is no // QueryFilter required var pointCursor = pointFeatureClass.Search(null, false); // initialize a counter variable int pointCounter = 0; // initialize a list to hold 5 coordinates that are used as vertices for the polyline var lineCoordinates = new List <Coordinate>(5); // set up the edit operation for the feature creation var createOperation = new EditOperation(); createOperation.Name = "Create polylines"; createOperation.SelectNewFeatures = false; // set up the datum transformation to be used in the projection ProjectionTransformation transformation = ProjectionTransformation.CreateFromEnvironment(pointDefinition.GetSpatialReference(), polylineDefinition.GetSpatialReference()); // loop through the point features while (pointCursor.MoveNext()) { pointCounter++; var pointFeature = pointCursor.Current as Feature; // add the feature point geometry as a coordinate into the vertex list of the line // - ensure that the projection of the point geometry is converted to match the spatial reference of the line // with a datum transformation considering the different spheroids lineCoordinates.Add(((MapPoint)GeometryEngine.ProjectEx(pointFeature.GetShape(), transformation)).Coordinate); // for every 5 geometries, construct a new polyline and queue a feature create if (pointCounter % 5 == 0) { // construct a new polyline by using the 5 point coordinate in the current list var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, polylineDefinition.GetSpatialReference()); // queue the create operation as part of the edit operation createOperation.Create(polylineLayer, newPolyline); // reset the list of coordinates lineCoordinates = new List <Coordinate>(5); } } // execute the edit (create) operation return createOperation.ExecuteAsync(); })); }
private void createFeature(PolutionGeom polutionGeom) { var attributes = new Dictionary <string, object>(); var cpm3 = polutionGeom.objects.Sum(v => v.cityPolutionM3); var vpm3 = polutionGeom.objects.Sum(v => v.vilagePolutionM3); var cpt = polutionGeom.objects.Sum(v => v.cityPolutionT); var vpt = polutionGeom.objects.Sum(v => v.vilagePolutionT); attributes.Add("SHAPE", polutionGeom.geometry); attributes.Add("LineLength", GeometryEngine.Instance.Length(polutionGeom.geometry) / 1000); attributes.Add("CityPolutionM3", cpm3); attributes.Add("VilagePolutionM3", vpm3); attributes.Add("CityPolutionT", cpt); attributes.Add("VilagePolutionT", vpt); attributes.Add("AllPolutionM3", cpm3 + vpm3); attributes.Add("AllPolutionT", cpt + vpt); //attributes.Add("IDs", polutionGeom.objects); editOperation.Create(routesNewLayer, attributes); }
internal void CopyRowValues(Row originRow, int partNumber, EditOperation operation) { var attributes = new Dictionary <string, object>(); attributes["SHAPE"] = originRow["SHAPE"]; attributes[USNG_SEG] = GetUSNGID_Line(originRow); attributes[RoutePart] = partNumber; operation.Create(TempSegmentsLayer, attributes); }
public async Task AddFeatureAsync(Geometry geometry) { var editOperation = new EditOperation { Name = $"Add feature to layer: {Name}", SelectNewFeatures = true, ShowModalMessageAfterFailure = false }; editOperation.Create(Layer, geometry); await editOperation.ExecuteAsync(); }
private static Task ConstructPoints(bool IsNumberOfPoints, double value) { //Run on MCT return(QueuedTask.Run(() => { //calc distance between points double dbp = 0; if (IsNumberOfPoints) { dbp = _3DLength / (_value + 1); } else { dbp = _value; } var editOp = new EditOperation(); editOp.Name = "Construct points along a 3D line"; var currTemp = EditingModuleInternal.TemplateManager.CurrentTemplate; //create points at distance between points up to total length for (double d = dbp; d < _3DLength; d += dbp) { //get subcurve from 3D line and endpoint var subCurve3D = GeometryEngine.Instance.GetSubCurve3D(_selLineGeom, 0, d, AsRatioOrLength.AsLength); var scEndPoint = subCurve3D.Points.Last(); editOp.Create(currTemp, scEndPoint); } //create points at start and end of line? if (_isEndsChecked) { editOp.Create(currTemp, _selLineGeom.Points.First()); editOp.Create(currTemp, _selLineGeom.Points.Last()); } return editOp.Execute(); })); }
/// <summary> /// Create random sample points in the extent of the spatial reference /// </summary> /// <param name="pointFeatureLayer">Point geometry feature layer used to the generate the points.</param> /// <returns>Task of bool</returns> private Task <bool> constructSamplePoints(FeatureLayer pointFeatureLayer) { // create a random number generator var randomGenerator = new Random(); // the database and geometry interactions are considered fine-grained and must be executed on // the main CIM thread return(QueuedTask.Run(() => { // get the feature class associated with the layer var featureClass = pointFeatureLayer.GetTable() as FeatureClass; // define an area of interest. Random points are generated in the allowed // confines of the allow extent range var areaOfInterest = MapView.Active.Extent; // retrieve the class definition of the point feature class var classDefinition = featureClass.GetDefinition() as FeatureClassDefinition; // store the spatial reference as its own variable var spatialReference = classDefinition.GetSpatialReference(); // start an edit operation to create new (random) point features var createOperation = new EditOperation(); createOperation.Name = "Generate points"; createOperation.SelectNewFeatures = false; // create 20 new point geometries and queue them for creation for (int i = 0; i < 20; i++) { MapPoint newMapPoint = null; // generate either 2D or 3D geometries if (classDefinition.HasZ()) { newMapPoint = MapPointBuilder.CreateMapPoint(randomGenerator.NextCoordinate(areaOfInterest, true), spatialReference); } else { newMapPoint = MapPointBuilder.CreateMapPoint(randomGenerator.NextCoordinate(areaOfInterest, false), spatialReference); } // queue feature creation createOperation.Create(pointFeatureLayer, newMapPoint); } // execute the edit (feature creation) operation return createOperation.ExecuteAsync(); })); }
private void createFeature(Feature feature) { try { inspector.Load(routesNewLayer, feature.GetObjectID()); double l = 0; double cpm3 = 0; double vpm3 = 0; double cpt = 0; double vpt = 0; double apm3 = 0; double apt = 0; var attributes = new Dictionary <string, object>(); try { l = double.Parse(inspector["LineLength"].ToString()); cpm3 = double.Parse(inspector["CityPolutionM3"].ToString()); vpm3 = double.Parse(inspector["VilagePolutionM3"].ToString()); cpt = double.Parse(inspector["CityPolutionT"].ToString()); vpt = double.Parse(inspector["VilagePolutionT"].ToString()); apm3 = double.Parse(inspector["AllPolutionM3"].ToString()); apt = double.Parse(inspector["AllPolutionT"].ToString()); } catch (Exception e) { } attributes.Add("SHAPE", feature.GetShape()); attributes.Add("LineLength", l); attributes.Add("CityPolutionM3", cpm3); attributes.Add("VilagePolutionM3", vpm3); attributes.Add("CityPolutionT", cpt); attributes.Add("VilagePolutionT", vpt); attributes.Add("AllPolutionM3", apm3); attributes.Add("AllPolutionT", apt); attributes.Add("From_C10", cpm3); attributes.Add("From_C11", cpt); attributes.Add("From_C12", vpm3); attributes.Add("From_C13", vpt); //attributes.Add("IDs", polutionGeom.objects); editOperation.Create(routesLayer, attributes); } catch (Exception e) { } }
protected override async void OnClick() { //get the multipatch layer from the map var localSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>() .FirstOrDefault(l => l.Name == "Cube" && l.ShapeType == esriGeometryType.esriGeometryMultiPatch); if (localSceneLayer == null) { return; } // create the multipatch geometry var cubeMultipatch = CreateCubeMultipatch(); // add the multipatch geometry to the layer string msg = await QueuedTask.Run(() => { long newObjectID = -1; var op = new EditOperation(); op.Name = "Create multipatch feature"; op.SelectNewFeatures = false; // queue feature creation and track the newly created objectID op.Create(localSceneLayer, cubeMultipatch, oid => newObjectID = oid); // execute bool result = op.Execute(); // if successful if (result) { // save the objectID in the module for other commands to use Module1.CubeMultipatchObjectID = newObjectID; // zoom to it MapView.Active.ZoomTo(localSceneLayer); return(""); } // not successful, return any error message from the EditOperation return(op.ErrorMessage); }); // if there's an error, show it if (!string.IsNullOrEmpty(msg)) { MessageBox.Show($@"Multipatch creation failed: " + msg); } }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { //Run on MCT return(QueuedTask.Run(() => { var op = new EditOperation(); op.Name = "Create main-connector-manhole"; op.SelectModifiedFeatures = false; op.SelectNewFeatures = false; //get the templates var map = MapView.Active.Map; var mainTemplate = map.FindLayers("main").First().GetTemplate("main"); var mhTemplate = map.FindLayers("Manhole").First().GetTemplate("Manhole"); var conTemplate = map.FindLayers("Connector").First().GetTemplate("Connector"); //create the main geom var mainGeom = GeometryEngine.Move(geometry, 0, 0, -20); op.Create(mainTemplate, mainGeom); //create manhole points and connector foreach (var pnt in ((Polyline)geometry).Points) { //manhole point at sketch vertex op.Create(mhTemplate, pnt); //vertical connector between mahole and main var conPoints = new List <MapPoint>(); conPoints.Add(pnt); //top of vertical connector conPoints.Add(GeometryEngine.Move(pnt, 0, 0, -20)); //bottom of vertical connector var conPolyLine = PolylineBuilder.CreatePolyline(conPoints); op.Create(conTemplate, conPolyLine); } return op.Execute(); })); }
protected override Task<bool> OnSketchCompleteAsync(Geometry geometry) { //Run on MCT return QueuedTask.Run(() => { var op = new EditOperation(); op.Name = "Create main-connector-manhole"; op.SelectModifiedFeatures = false; op.SelectNewFeatures = false; //get the templates var map = MapView.Active.Map; var mainTemplate = map.FindLayers("main").First().GetTemplate("main"); var mhTemplate = map.FindLayers("Manhole").First().GetTemplate("Manhole"); var conTemplate = map.FindLayers("Connector").First().GetTemplate("Connector"); //create the main geom var mainGeom = GeometryEngine.Move(geometry, 0, 0, -20); op.Create(mainTemplate, mainGeom); //create manhole points and connector foreach (var pnt in ((Polyline)geometry).Points) { //manhole point at sketch vertex op.Create(mhTemplate, pnt); //vertical connector between mahole and main var conPoints = new List<MapPoint>(); conPoints.Add(pnt); //top of vertical connector conPoints.Add(GeometryEngine.Move(pnt, 0, 0, -20)); //bottom of vertical connector var conPolyLine = PolylineBuilder.CreatePolyline(conPoints); op.Create(conTemplate, conPolyLine); } return op.Execute(); }); }
protected override Task <bool> OnSketchCompleteAsync(Geometry geometry) { var myTemplate = EditingTemplate.Current; var myGeometry = geometry; //Create a new feature using a template and a geometry var op = new EditOperation() { Name = "Create my feature" }; op.Create(myTemplate, myGeometry); op.Execute(); return(Task.FromResult(true)); }
protected async override Task <bool> OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometry geometry) { await QueuedTask.Run(async() => { var polygonTemplate = MapView.Active.Map.FindLayers("Clip_Polygon_Asphalt").FirstOrDefault().GetTemplate("Clip_Polygon_Asphalt"); // Create an edit operation var createOperation = new EditOperation(); createOperation.Name = string.Format("Create {0}", "Volume Polygon"); createOperation.SelectNewFeatures = true; createOperation.Create(polygonTemplate, geometry); // Execute the operation await createOperation.ExecuteAsync(); }); return(true); }
protected override void OnClick() { QueuedTask.Run(() => { //creates a crowd planning zone var cpLayer = MapView.Active.Map.FindLayers("CrowdPlanning").FirstOrDefault() as FeatureLayer; var geom = MapView.Active.Extent.Expand(0.1, 0.1, true); var poly = new PolygonBuilder(geom).ToGeometry(); //create an edit operation and execute var editOp = new EditOperation(); editOp.Name = "Create crowd plan"; editOp.Create(cpLayer, poly); editOp.Execute(); }); }
protected override void OnClick() { var polyLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().FirstOrDefault(f => f.ShapeType == esriGeometryType.esriGeometryPolygon); if (polyLayer == null) { MessageBox.Show($@"To run this sample you need to have a polygon feature class layer."); return; } QueuedTask.Run(() => { using (var fc = polyLayer.GetTable() as FeatureClass) { if (fc == null) { return; } var fcDefinition = fc.GetDefinition(); var editOperation = new EditOperation(); editOperation.Name = "Create outer ring"; using (var cursor = fc.Search()) { while (cursor.MoveNext()) { using (var feature = cursor.Current as Feature) { if (feature == null) { continue; } var outerRings = Module1.Current.GetOutermostRings(feature.GetShape() as Polygon); if (outerRings != null) { editOperation.Create(polyLayer, outerRings); } } } } editOperation.Execute(); } }); }
/// <summary> /// Place point on feature layer /// </summary> /// <param name="operation">Edit operatio</param> /// <param name="point">Rhino Point3d</param> private static void showPoint(EditOperation operation, Point3d point, Point3d origin) { try { var layer = getFeatureLayer(FeatureLayerType.GH_Preview_Point); if (layer == null) { return; } MapPoint mp = RhinoUtil.ptToGis(point, origin); operation.Create(layer, mp); operation.ExecuteAsync(); } catch { } }
/// <summary> /// Create sample polygon feature using the point geometries from the multi-point feature using the /// ConvexHull method provided by the GeometryEngine. /// </summary> /// <param name="polygonLayer">Polygon geometry feature layer used to add the new feature.</param> /// <param name="lineLayer">The polyline feature layer containing the features used to construct the polygon.</param> /// <returns></returns> private Task <bool> ConstructSamplePolygon(FeatureLayer polygonLayer, FeatureLayer lineLayer) { // execute the fine grained API calls on the CIM main thread return(QueuedTask.Run(() => { // get the underlying feature class for each layer var polygonFeatureClass = polygonLayer.GetTable() as FeatureClass; var polygonDefinition = polygonFeatureClass.GetDefinition() as FeatureClassDefinition; var lineFeatureClass = lineLayer.GetTable() as FeatureClass; // construct a cursor to retrieve the line features var lineCursor = lineFeatureClass.Search(null, false); // set up the edit operation for the feature creation var createOperation = new EditOperation() { Name = "Create polygons", SelectNewFeatures = false }; PolylineBuilder polylineBuilder = new PolylineBuilder(polygonDefinition.GetSpatialReference()); while (lineCursor.MoveNext()) { // retrieve the first feature using (var lineFeature = lineCursor.Current as Feature) { // add the coordinate collection of the current geometry into our overall list of collections var polylineGeometry = lineFeature.GetShape() as Polyline; polylineBuilder.AddParts(polylineGeometry.Parts); } } // use the ConvexHull method from the GeometryEngine to construct the polygon geometry var newPolygon = GeometryEngine.Instance.ConvexHull(polylineBuilder.ToGeometry()) as Polygon; // queue the polygon creation createOperation.Create(polygonLayer, newPolygon); // execute the edit (polygon create) operation return createOperation.ExecuteAsync(); })); }
/// <summary> /// Fires once the user completes the onscreen sketch. In the context of a construction tool the sketch geometry /// is used for the shape of the feature. /// </summary> /// <param name="geometry">The sketch geometry the user digitized on the screen.</param> /// <returns></returns> protected override Task<bool> OnSketchCompleteAsync(Geometry geometry) { if (geometry == null) return Task.FromResult(false); return QueuedTask.Run(() => { // create an edit operation var editOperation = new EditOperation(); editOperation.Name = string.Format("Create point in '{0}'", CurrentTemplate.Layer.Name); editOperation.ProgressMessage = "Working..."; editOperation.CancelMessage = "Operation canceled"; editOperation.ErrorMessage = "Error creating point"; // queue the edit operation using the sketch geometry as the shape of the feature and any attribute // configurations from the editing template editOperation.Create(CurrentTemplate, geometry); //execute the operation return editOperation.ExecuteAsync(); }); }
/// <summary> /// Create sample polygon feature using the point geometries from the multi-point feature using the /// ConvexHull method provided by the GeometryEngine. /// </summary> /// <param name="polygonLayer">Polygon geometry feature layer used to add the new feature.</param> /// <param name="lineLayer">The polyline feature layer containing the features used to construct the polygon.</param> /// <returns></returns> private Task<bool> constructSamplePolygon(FeatureLayer polygonLayer, FeatureLayer lineLayer) { // execute the fine grained API calls on the CIM main thread return QueuedTask.Run(() => { // get the underlying feature class for each layer var polygonFeatureClass = polygonLayer.GetTable() as FeatureClass; var polygonDefinition = polygonFeatureClass.GetDefinition() as FeatureClassDefinition; var lineFeatureClass = lineLayer.GetTable() as FeatureClass; // construct a cursor to retrieve the line features var lineCursor = lineFeatureClass.Search(null, false); // set up the edit operation for the feature creation var createOperation = new EditOperation() { Name = "Create polygons", SelectNewFeatures = false }; PolylineBuilder polylineBuilder = new PolylineBuilder(polygonDefinition.GetSpatialReference()); while (lineCursor.MoveNext()) { // retrieve the first feature var lineFeature = lineCursor.Current as Feature; // add the coordinate collection of the current geometry into our overall list of collections var polylineGeometry = lineFeature.GetShape() as Polyline; polylineBuilder.AddParts(polylineGeometry.Parts); } // use the ConvexHull method from the GeometryEngine to construct the polygon geometry var newPolygon = GeometryEngine.ConvexHull(polylineBuilder.ToGeometry()) as Polygon; // queue the polygon creation createOperation.Create(polygonLayer, newPolygon); // execute the edit (polygon create) operation return createOperation.ExecuteAsync(); }); }
/// <summary> /// Create random sample points in the extent of the spatial reference /// </summary> /// <param name="pointFeatureLayer">Point geometry feature layer used to the generate the points.</param> /// <returns>Task{bool}</returns> private Task<bool> constructSamplePoints(FeatureLayer pointFeatureLayer) { // create a random number generator var randomGenerator = new Random(); // the database and geometry interactions are considered fine-grained and must be executed on // the main CIM thread return QueuedTask.Run(() => { // start an edit operation to create new (random) point features var createOperation = new EditOperation(); createOperation.Name = "Generate points"; createOperation.SelectNewFeatures = false; // get the feature class associated with the layer var featureClass = pointFeatureLayer.GetTable() as FeatureClass; // define an area of interest. Random points are generated in the allowed // confines of the allow extent range var areaOfInterest = MapView.Active.Extent; MapPoint newMapPoint = null; // retrieve the class definition of the point feature class var classDefinition = featureClass.GetDefinition() as FeatureClassDefinition; // store the spatial reference as its own variable var spatialReference = classDefinition.GetSpatialReference(); // create 20 new point geometries and queue them for creation for (int i = 0; i < 20; i++) { // generate either 2D or 3D geometries if (classDefinition.HasZ()) newMapPoint = MapPointBuilder.CreateMapPoint(randomGenerator.NextCoordinate(areaOfInterest, true), spatialReference); else newMapPoint = MapPointBuilder.CreateMapPoint(randomGenerator.NextCoordinate(areaOfInterest, false), spatialReference); // queue feature creation createOperation.Create(pointFeatureLayer, newMapPoint); } // execute the edit (feature creation) operation return createOperation.ExecuteAsync(); }); }
public static ArcGIS.Core.Geometry.Geometry GetGeometry(int featureClassID, int OID, out bool isLine, FeatureLayer lineFeatureLayer, FeatureLayer pointFeatureLayer) { isLine = true; IFeatureClass fc = null; if(_fcIDToFeatureClass.ContainsKey(featureClassID) == false) { IFeatureWorkspaceManage2 fwsm2 = (IFeatureWorkspaceManage2)_fws; string className = fwsm2.GetObjectClassNameByID(featureClassID); _fcIDToFeatureClass.Add(featureClassID,_fws.OpenFeatureClass(className) ); } fc = _fcIDToFeatureClass[featureClassID]; var shape = fc.GetFeature(OID).Shape; if (shape.GeometryType == ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint) { IPoint pnt = (IPoint)shape; //var coord = new Coordinate(xCoord, yCoord); //newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference); isLine = false; } else { isLine = true; } bool isLineForLambda = isLine; QueuedTask.Run(() => { EnvelopeBuilder envBuilder = new EnvelopeBuilder(); envBuilder.XMin = 0; envBuilder.XMax = 0; envBuilder.YMin = 0; envBuilder.YMax = 0; var env = envBuilder.ToGeometry().Extent; var pntFeatureClass = pointFeatureLayer.GetTable() as ArcGIS.Core.Data.FeatureClass; var pntClassDefinition = pntFeatureClass.GetDefinition() as FeatureClassDefinition; var spatialReference = pntClassDefinition.GetSpatialReference(); var createOperation = new EditOperation(); createOperation.Name = "Highlight Design Features"; createOperation.SelectNewFeatures = false; if (isLineForLambda == false) //point { IPoint pnt = (IPoint)shape; var coord = new Coordinate(pnt.X,pnt.Y); var newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference); // queue feature creation createOperation.Create(pointFeatureLayer, newMapPoint); Common.UnionEnvelopes(envBuilder, newMapPoint); } else { IPointCollection pc = (IPointCollection)shape; var lineCoordinates = new List<Coordinate>(pc.PointCount); for (int i = 0; i < pc.PointCount; i++) { var vertex = new Coordinate(pc.get_Point(i).X, pc.get_Point(i).Y); lineCoordinates.Add(vertex); var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, spatialReference); createOperation.Create(lineFeatureLayer, newPolyline); Common.UnionEnvelopes(envBuilder, newPolyline); } } }); return null; }
public static Task<bool> DrawTraceResults(JObject jo) { var traceResults = new List<TraceResult>(); FeatureLayer pointFeatureLayer; FeatureLayer lineFeatureLayer; GetLayers(out pointFeatureLayer, out lineFeatureLayer); // the database and geometry interactions are considered fine-grained and must be executed on // the main CIM thread return QueuedTask.Run(() => { bool bZoom = true; EnvelopeBuilder envBuilder = new EnvelopeBuilder(); envBuilder.XMin = 0; envBuilder.XMax = 0; envBuilder.YMin = 0; envBuilder.YMax = 0; var env = envBuilder.ToGeometry().Extent; // start an edit operation to create new (random) point features var createOperation = new EditOperation(); createOperation.Name = "Trace Results"; createOperation.SelectNewFeatures = false; // get the feature class associated with the layer var pntFeatureClass = pointFeatureLayer.GetTable() as FeatureClass; var lineFeatureClass = lineFeatureLayer.GetTable() as FeatureClass; lineFeatureClass.Truncate(); pntFeatureClass.Truncate(); MapPoint newMapPoint = null; // retrieve the class definition of the point feature class var pntClassDefinition = pntFeatureClass.GetDefinition() as FeatureClassDefinition; // store the spatial reference as its own variable var spatialReference = pntClassDefinition.GetSpatialReference(); for (int i = 0; i < jo["results"].Count(); i++) { var result = jo["results"][i]; var name = result["name"].ToString(); var geomType = result["geometryType"].ToString(); var features = result["features"]; if (geomType == "esriGeometryPoint") { for (int j = 0; j < features.Count(); j++) { var pntFeature = features[j]; var atts = pntFeature["attributes"]; List<string> attributes = new List<string>(); if (name == "ServicePoint" || name == "Transformer") { int cnt = atts.Count(); foreach (var att in atts) { JProperty jpo = (JProperty)att; attributes.Add(jpo.Name + ":" + jpo.Value); } } string attributesString = string.Join("~", attributes); string.Join("~", attributes); double xCoord = Convert.ToDouble(pntFeature["geometry"]["x"]); double yCoord = Convert.ToDouble(pntFeature["geometry"]["y"]); var coord = new Coordinate(xCoord, yCoord); newMapPoint = MapPointBuilder.CreateMapPoint(coord, spatialReference); // queue feature creation createOperation.Create(pointFeatureLayer, newMapPoint); UnionEnvelopes(envBuilder, newMapPoint); //string geomString = xCoord.ToString() + "," + yCoord.ToString(); if (name == "Service Point" || name == "Transformer") { var oid = Convert.ToInt32(atts["OBJECTID"]); traceResults.Add(new TraceResult { ClassName = name, OID = oid, Attributes = attributesString, Geom = newMapPoint.X.ToString() + newMapPoint.Y.ToString() }); } } } else if (geomType == "esriGeometryPolyline") { for (int j = 0; j < features.Count(); j++) { var lineFeature = features[j]; var pathCount = lineFeature["geometry"]["paths"].Count(); for (int k = 0; k < pathCount; k++) { var path = lineFeature["geometry"]["paths"][k]; var coordPairCount = path.Count(); var lineCoordinates = new List<Coordinate>(coordPairCount); for (int l = 0; l < coordPairCount; l++) { var coord = path[l]; var x = Convert.ToDouble(coord[0]); var y = Convert.ToDouble(coord[1]); var vertex = new Coordinate(x, y); lineCoordinates.Add(vertex); } var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, spatialReference); createOperation.Create(lineFeatureLayer, newPolyline); UnionEnvelopes(envBuilder, newPolyline); } } } } // execute the edit (feature creation) operation Map activeMap = MapView.Active.Map; var extent = envBuilder.ToGeometry().Extent; var expandedExtent = extent.Expand(1.2, 1.2, true); MapView.Active.ZoomTo(expandedExtent); return createOperation.ExecuteAsync(); }); }
/// <summary> /// Create a single multi-point feature that is comprised of 20 points. /// </summary> /// <param name="multiPointLayer">Multi-point geometry feature layer used to add the multi-point feature.</param> /// <returns></returns> private Task constructSampleMultiPoints(FeatureLayer multiPointLayer) { // create a random number generator var randomGenerator = new Random(); // the database and geometry interactions are considered fine-grained and need to be executed on // a separate thread return QueuedTask.Run(() => { // get the feature class associated with the layer var featureClass = multiPointLayer.GetTable() as FeatureClass; var featureClassDefinition = featureClass.GetDefinition() as FeatureClassDefinition; // store the spatial reference as its own variable var spatialReference = featureClassDefinition.GetSpatialReference(); // define an area of interest. Random points are generated in the allowed // confines of the allow extent range var areaOfInterest = MapView.Active.Extent; // start an edit operation to create new (random) multi-point feature var createOperation = new EditOperation(); createOperation.Name = "Generate multipoints"; // retrieve the class definition of the point feature class var classDefinition = featureClass.GetDefinition() as FeatureClassDefinition; // create a list to hold the 20 coordinates of the multi-point feature IList<Coordinate> coordinateList = new List<Coordinate>(20); for (int i = 0; i < 20; i++) { // generate either 2D or 3D geometries if (classDefinition.HasZ()) coordinateList.Add(randomGenerator.NextCoordinate(areaOfInterest, true)); else coordinateList.Add(randomGenerator.NextCoordinate(areaOfInterest, false)); } var newPoints = MultipointBuilder.CreateMultipoint(coordinateList, classDefinition.GetSpatialReference()); // create and execute the feature creation operation createOperation.Create(multiPointLayer, newPoints); return createOperation.ExecuteAsync(); }); }
/// <summary> /// Create sample polyline feature using the geometries from the point feature layer. /// </summary> /// <param name="polylineLayer">Polyline geometry feature layer used to add the new features.</param> /// <param name="pointLayer">The geometries from the point layer are used as vertices for the new line features.</param> /// <returns></returns> private Task<bool> constructSamplePolylines(FeatureLayer polylineLayer, FeatureLayer pointLayer) { // execute the fine grained API calls on the CIM main thread return QueuedTask.Run(() => { // get the underlying feature class for each layer var polylineFeatureClass = polylineLayer.GetTable() as FeatureClass; var pointFeatureClass = pointLayer.GetTable() as FeatureClass; // retrieve the feature class schema information for the feature classes var polylineDefinition = polylineFeatureClass.GetDefinition() as FeatureClassDefinition; var pointDefinition = pointFeatureClass.GetDefinition() as FeatureClassDefinition; // construct a cursor for all point features, since we want all feature there is no // QueryFilter required var pointCursor = pointFeatureClass.Search(null, false); // initialize a counter variable int pointCounter = 0; // initialize a list to hold 5 coordinates that are used as vertices for the polyline var lineCoordinates = new List<Coordinate>(5); // set up the edit operation for the feature creation var createOperation = new EditOperation(); createOperation.Name = "Create polylines"; createOperation.SelectNewFeatures = false; // loop through the point features while (pointCursor.MoveNext()) { pointCounter++; var pointFeature = pointCursor.Current as Feature; // add the feature point geometry as a coordinate into the vertex list of the line // - ensure that the projection of the point geometry is converted to match the spatial reference of the line lineCoordinates.Add(((MapPoint)GeometryEngine.Project(pointFeature.GetShape(), polylineDefinition.GetSpatialReference())).Coordinate); // for every 5 geometries, construct a new polyline and queue a feature create if (pointCounter % 5 == 0) { // construct a new polyline by using the 5 point coordinate in the current list var newPolyline = PolylineBuilder.CreatePolyline(lineCoordinates, polylineDefinition.GetSpatialReference()); // queue the create operation as part of the edit operation createOperation.Create(polylineLayer, newPolyline); // reset the list of coordinates lineCoordinates = new List<Coordinate>(5); } } // execute the edit (create) operation return createOperation.ExecuteAsync(); }); }
/// <summary> /// Separate a selected multipart feature into individual features. /// </summary> protected override void OnClick() { //check for one selected feature if (MapView.Active.Map.SelectionCount != 1) { MessageBox.Show("Please select one multipart feature to explode", "Explode Multipart Feature"); return; } //run on MCT QueuedTask.Run(() => { //get selected feature geometry var selectedFeatures = MapView.Active.Map.GetSelection(); var insp = new Inspector(); insp.Load(selectedFeatures.Keys.First(), selectedFeatures.Values.First()); var selGeom = insp.Shape; var selGeomType = selGeom.GeometryType; //early checks for geometry type and single point in a multipoint if ( !(selGeomType == GeometryType.Multipoint || selGeomType == GeometryType.Polygon || selGeomType == GeometryType.Polyline) || selGeom.PointCount == 1) { MessageBox.Show("Please select a multipart feature to explode", "Explode Multipart Feature"); return; } //check if selected feature has multiple parts var mpGeom = selGeom as Multipart; if (mpGeom != null) if (mpGeom.PartCount < 2) { MessageBox.Show("Please select a multipart feature to explode","Explode Multipart Feature"); return; } //setup the edit operation var op = new EditOperation(); op.Name = "Explode Multipart Feature"; //handle geometry types switch(selGeomType) { case GeometryType.Multipoint: //create a new feature for each pointcount var mpoint = selGeom as Multipoint; for (var i = 0; i < mpoint.PointCount; i++) { //copy the original feature into a dictionary and update the shape. var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue); newFeature[insp.GeometryAttribute.FieldName] = new MultipointBuilder(mpoint.Points[i]).ToGeometry(); op.Create(insp.MapMember, newFeature); } break; case GeometryType.Polyline: //create a new feature for each polyline part for (var i = 0; i < mpGeom.PartCount; i++) { //copy the original feature into a dictionary and update the shape. var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue); newFeature[insp.GeometryAttribute.FieldName] = new PolylineBuilder(mpGeom.Parts[i]).ToGeometry(); op.Create(insp.MapMember, newFeature); } break; case GeometryType.Polygon: //ignore donut features for now //check if any part area is negative for (var i = 0; i < mpGeom.PartCount; i++) { if ((new PolygonBuilder(mpGeom.Parts[i]).ToGeometry()).Area < 0) { MessageBox.Show("Please select a non-donut polygon to explode", "Explode Mutltpart Feature"); return; } } //create a new feature for each polygon part for (var i = 0; i < mpGeom.PartCount; i++) { //copy the original feature into a dictionary and update the shape. var newFeature = insp.ToDictionary(a => a.FieldName, a => a.CurrentValue); newFeature[insp.GeometryAttribute.FieldName] = new PolygonBuilder(mpGeom.Parts[i]).ToGeometry(); op.Create(insp.MapMember, newFeature); } break; } //switch //delete the original feature and execute the creates //op.Delete(insp.MapMember, insp.ObjectID); //double cast to workaround 1.1 bug op.Delete(insp.MapMember, (long)(int)insp.ObjectIDAttribute.CurrentValue); op.Execute(); }); }