예제 #1
0
        private Geometry CreatePolyline()
        {
            if (Point1 == null || Point2 == null)
            {
                return(null);
            }
            CurveType  curveType = DeriveCurveType(LineType);
            LinearUnit lu        = DeriveUnit(LineDistanceType);

            try
            {
                // create line
                var polyline = QueuedTask.Run(() =>
                {
                    var segment = LineBuilder.CreateLineSegment(Point1, Point2);
                    return(PolylineBuilder.CreatePolyline(segment));
                }).Result;
                Geometry newline = GeometryEngine.GeodeticDensifyByLength(polyline, 0, lu, curveType);
                AddGraphicToMap(newline);
                ResetPoints();

                return(newline as Geometry);
            }
            catch (Exception ex)
            {
                // do nothing
                return(null);
            }
        }
        /// <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();
            }));
        }
예제 #3
0
        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 = PolylineBuilder.CreatePolyline(conPoints);
                    op.Create(conTemplate, conPolyLine);
                }
                return op.Execute();
            }));
        }
        private static Polyline GetCutPolyLine(Geometry geometry)
        {
            IList <Coordinate> cutLine = new List <Coordinate>();

            cutLine.Add(new Coordinate(geometry.Extent.XMin, geometry.Extent.YMin, geometry.Extent.ZMin));
            cutLine.Add(new Coordinate(geometry.Extent.Center));
            cutLine.Add(new Coordinate(geometry.Extent.XMax, geometry.Extent.YMax, geometry.Extent.ZMin));
            var polyLine = PolylineBuilder.CreatePolyline(cutLine, geometry.SpatialReference);

            return(polyLine);
        }
예제 #5
0
 /// <summary>
 /// Create a line graphic.
 /// </summary>
 /// <param name="fieldOfJoy"></param>
 /// <param name="a"></param>
 /// <param name="b"></param>
 /// <param name="lineSymbol"></param>
 private static void CreateLine(GraphicsLayer fieldOfJoy, MapPoint a, MapPoint b, CIMLineSymbol lineSymbol)
 {
     fieldOfJoy.AddElement(new CIMLineGraphic()
     {
         Symbol = lineSymbol.MakeSymbolReference(),
         Line   = PolylineBuilder.CreatePolyline(new List <MapPoint>()
         {
             a, b
         }, fieldOfJoy.GetSpatialReference())
     });
 }
예제 #6
0
        private Task OnBeforeSketchCompletedEvent(BeforeSketchCompletedEventArgs arg)
        {
            //replace curved sketch segments with straight segments

            //return if sketch geometry is not polygon or polyline
            if (!(arg.Sketch.GeometryType == GeometryType.Polyline || arg.Sketch.GeometryType == GeometryType.Polygon))
            {
                return(Task.CompletedTask);
            }

            var sketchMP = arg.Sketch as Multipart;

            //if the sketch doesnt have curves then return
            if (!sketchMP.HasCurves)
            {
                return(Task.CompletedTask);
            }

            //itterate through each sketch part
            var newParts = new List <List <Segment> >();

            foreach (var sketchPart in sketchMP.Parts)
            {
                //itterate through each sketch segment
                var newSegments = new List <Segment>();
                foreach (var sketchSegment in sketchPart)
                {
                    if (sketchSegment.IsCurve)
                    {
                        newSegments.Add(LineBuilder.CreateLineSegment(sketchSegment.StartPoint, sketchSegment.EndPoint));
                    }
                    else
                    {
                        newSegments.Add(sketchSegment);
                    }
                }
                newParts.Add(newSegments);
            }

            //create the new sketch geometry based on sketch type and set back on the sketch
            if (arg.Sketch.GeometryType == GeometryType.Polyline)
            {
                var polyline = PolylineBuilder.CreatePolyline(newParts);
                arg.SetSketchGeometry(polyline);
            }
            else
            {
                var polygon = PolygonBuilder.CreatePolygon(newParts);
                arg.SetSketchGeometry(polygon);
            }

            return(Task.CompletedTask);
        }
예제 #7
0
        private Geometry CreatePolyline()
        {
            if (Point1 == null || Point2 == null)
            {
                return(null);
            }

            var nameConverter           = new EnumToFriendlyNameConverter();
            GeodeticCurveType curveType = DeriveCurveType(LineType);
            LinearUnit        lu        = DeriveUnit(LineDistanceType);

            try
            {
                // create line
                var polyline = QueuedTask.Run(() =>
                {
                    var point2Proj = GeometryEngine.Instance.Project(Point2, Point1.SpatialReference);
                    var segment    = LineBuilder.CreateLineSegment(Point1, (MapPoint)point2Proj);
                    return(PolylineBuilder.CreatePolyline(segment));
                }).Result;
                Geometry newline = GeometryEngine.Instance.GeodeticDensifyByLength(polyline, 0, lu, curveType);


                var displayValue = nameConverter.Convert(LineDistanceType, typeof(string), new object(), CultureInfo.CurrentCulture);
                // Hold onto the attributes in case user saves graphics to file later
                LineAttributes lineAttributes = new LineAttributes()
                {
                    mapPoint1    = Point1,
                    mapPoint2    = Point2,
                    distance     = distance,
                    angle        = (double)azimuth,
                    angleunit    = LineAzimuthType.ToString(),
                    distanceunit = displayValue.ToString(),
                    originx      = Point1.X,
                    originy      = Point1.Y,
                    destinationx = Point2.X,
                    destinationy = Point2.Y
                };

                CreateLineFeature(newline, lineAttributes);

                ResetPoints();

                return((Geometry)newline);
            }
            catch (Exception ex)
            {
                // do nothing
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return(null);
            }
        }
 internal Task <Polyline> CreatePolylineFromPointAsync(MapPoint pt, double tolerance)
 {
     return(QueuedTask.Run(() =>
     {
         // create a polyline from a starting point
         //use a tolerance to construct the second point
         MapPoint pt2 = MapPointBuilder.CreateMapPoint(pt.X + tolerance, pt.Y, pt.SpatialReference);
         return PolylineBuilder.CreatePolyline(new List <MapPoint>()
         {
             pt, pt2
         });
     }));
 }
예제 #9
0
        public async Task RedrawObservationAsync()
        {
            await QueuedTask.Run(() =>
            {
                _disposeInnerLine?.Dispose();
                _disposeOuterLine?.Dispose();

                if (_measurementPoint?.IsObservationVisible() ?? false)
                {
                    MapView thisView   = MapView.Active;
                    MapPoint measPoint = _measurementPoint?.Point;
                    MapPoint mapPointObsLine;

                    if ((measPoint != null) && (!double.IsNaN(measPoint.X)) && (!double.IsNaN(measPoint.Y)))
                    {
                        Point winMeasPoint = thisView.MapToScreen(measPoint);
                        Point winObsPoint  = thisView.MapToScreen(Point);

                        double xdir           = ((winMeasPoint.X - winObsPoint.X) * 3) / 2;
                        double ydir           = ((winMeasPoint.Y - winObsPoint.Y) * 3) / 2;
                        Point winPointObsLine = new Point(winObsPoint.X + xdir, winObsPoint.Y + ydir);
                        mapPointObsLine       = thisView.ScreenToMap(winPointObsLine);
                    }
                    else
                    {
                        mapPointObsLine = MapPointBuilder.CreateMapPoint((Point.X + (XDir * DistLine)), (Point.Y + (YDir * DistLine)));
                    }

                    IList <MapPoint> linePointList = new List <MapPoint>();
                    linePointList.Add(mapPointObsLine);
                    linePointList.Add(Point);
                    Polyline polyline = PolylineBuilder.CreatePolyline(linePointList);

                    Color outerColorLine             = Viewer?.Color ?? Color.DarkGray;
                    CIMColor cimOuterColorLine       = ColorFactory.Instance.CreateColor(Color.FromArgb(255, outerColorLine));
                    CIMLineSymbol cimOuterLineSymbol = SymbolFactory.Instance.DefaultLineSymbol;
                    cimOuterLineSymbol.SetColor(cimOuterColorLine);
                    cimOuterLineSymbol.SetSize(OuterLineSize);
                    CIMSymbolReference cimOuterLineSymbolRef = cimOuterLineSymbol.MakeSymbolReference();
                    _disposeOuterLine = thisView.AddOverlay(polyline, cimOuterLineSymbolRef);

                    Color innerColorLine             = Color.LightGray;
                    CIMColor cimInnerColorLine       = ColorFactory.Instance.CreateColor(innerColorLine);
                    CIMLineSymbol cimInnerLineSymbol = SymbolFactory.Instance.DefaultLineSymbol;
                    cimInnerLineSymbol.SetColor(cimInnerColorLine);
                    cimInnerLineSymbol.SetSize(InnerLineSize);
                    CIMSymbolReference cimInnerLineSymbolRef = cimInnerLineSymbol.MakeSymbolReference();
                    _disposeInnerLine = thisView.AddOverlay(polyline, cimInnerLineSymbolRef);
                }
            });
        }
        /// <summary>
        /// When the active map view changes, update the graphic overlay on the map control
        /// </summary>
        /// <param name="args"></param>
        private void OnMapViewCameraChanged(MapViewCameraChangedEventArgs args)
        {
            if (MapView.Active == null)
            {
                return;
            }
            if (MapView.Active.Extent == null)
            {
                return;
            }
            if (MapView.Active.ViewingMode != ArcGIS.Core.CIM.MapViewingMode.Map)
            {
                return;
            }

            //get the Map view's extent
            var viewExtent = MapView.Active.Extent.Clone() as Envelope;

            QueuedTask.Run(() =>
            {
                //Line symbol to be used to draw the overview rectangle.
                if (_lineSymbol == null)
                {
                    _lineSymbol =
                        SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 2.0, SimpleLineStyle.Solid);
                }

                _graphic?.Dispose();            //Clear out the old overlay

                _overviewEnvelope = viewExtent; //overview envelope based on active map view

                if (_overviewEnvelope == null)
                {
                    return;
                }
                //Creating the overview rectangle
                IList <MapPoint> segments = new List <MapPoint>
                {
                    MapPointBuilder.CreateMapPoint(_overviewEnvelope.XMin, _overviewEnvelope.YMin, _overviewEnvelope.SpatialReference),
                    MapPointBuilder.CreateMapPoint(_overviewEnvelope.XMax, _overviewEnvelope.YMin, _overviewEnvelope.SpatialReference),
                    MapPointBuilder.CreateMapPoint(_overviewEnvelope.XMax, _overviewEnvelope.YMax, _overviewEnvelope.SpatialReference),
                    MapPointBuilder.CreateMapPoint(_overviewEnvelope.XMin, _overviewEnvelope.YMax, _overviewEnvelope.SpatialReference),
                    MapPointBuilder.CreateMapPoint(_overviewEnvelope.XMin, _overviewEnvelope.YMin, _overviewEnvelope.SpatialReference)
                };
                _polyLine = PolylineBuilder.CreatePolyline(segments, _overviewEnvelope.SpatialReference);

                _graphic = _mapControl.AddOverlay(_polyLine, _lineSymbol.MakeSymbolReference());
            });
        }
        private async void OnUndoButtonClicked(object sender, RoutedEventArgs e)
        {
            MeasurementPoint measurementPoint = GetMeasurementPoint();
            Measurement      measurement      = measurementPoint.Measurement;

            if (measurement.IsPointMeasurement)
            {
                measurementPoint.RemoveMe();

                if (measurement.ObjectId == null)
                {
                    measurement.AddMeasurementPoint();
                }
                else
                {
                    measurement.CreateMeasurementPoint(measurementPoint.LastPoint);
                }
            }
            else
            {
                MapView  mapView  = MapView.Active;
                Geometry geometry = await mapView.GetCurrentSketchAsync();

                List <MapPoint> points = await measurement.ToPointCollectionAsync(geometry);

                int removePoints = measurement.IsGeometryType(GeometryType.Polygon) && points.Count == 2 &&
                                   measurement.PointNr == 1 ? 2 : 1;

                for (int i = 0; i < removePoints; i++)
                {
                    int substract = (measurement.IsGeometryType(GeometryType.Polygon) && (removePoints == 1)) ? 2 : 1;
                    points.RemoveAt(points.Count - substract);
                }

                await QueuedTask.Run(() =>
                {
                    if (measurement.IsGeometryType(GeometryType.Polygon))
                    {
                        geometry = PolygonBuilder.CreatePolygon(points);
                    }
                    else if (measurement.IsGeometryType(GeometryType.Polyline))
                    {
                        geometry = PolylineBuilder.CreatePolyline(points);
                    }
                });

                await mapView.SetCurrentSketchAsync(geometry);
            }
        }
        internal void UpdateFeedbackWithGeoLine(LineSegment segment)
        {
            if (Point1 == null || segment == null)
            {
                return;
            }

            var polyline = QueuedTask.Run(() =>
            {
                return(PolylineBuilder.CreatePolyline(segment));
            }).Result;

            ClearTempGraphics();
            AddGraphicToMap(Point1, ColorFactory.Green, true, 5.0);
            AddGraphicToMap(polyline, ColorFactory.Grey, true);
        }
예제 #13
0
        /// <summary>
        /// Creates a new camera offset from the provided camera around an ellipse.
        /// </summary>
        /// <param name="camera">The starting camera.</param>
        /// <param name="ellipse">The ellipse around which the camera will rotate.</param>
        /// <param name="centerPoint">The center point of the ellipse.</param>
        /// <param name="percentAlong">The percentage around the ellipse to create the camera.</param>
        private Camera OffsetCamera(Camera camera, Polyline ellipse, MapPoint centerPoint, double percentAlong)
        {
            camera = CloneCamera(camera);

            var fromPoint = GeometryEngine.MovePointAlongLine(ellipse, percentAlong, true, 0);

            var segment = LineBuilder.CreateLineSegment(new Coordinate2D(centerPoint.X, centerPoint.Y), new Coordinate2D(fromPoint.X, centerPoint.Y), centerPoint.SpatialReference);
            var difX    = GeometryEngine.GeodesicLength(PolylineBuilder.CreatePolyline(segment, segment.SpatialReference));

            if (centerPoint.X - fromPoint.X < 0)
            {
                difX *= -1;
            }

            segment = LineBuilder.CreateLineSegment(new Coordinate2D(centerPoint.X, centerPoint.Y), new Coordinate2D(centerPoint.X, fromPoint.Y), centerPoint.SpatialReference);
            var difY = GeometryEngine.GeodesicLength(PolylineBuilder.CreatePolyline(segment, segment.SpatialReference));

            if (centerPoint.Y - fromPoint.Y < 0)
            {
                difY *= -1;
            }

            var radian  = Math.Atan2(difX, difY);
            var heading = radian * -180 / Math.PI;

            camera.Heading = heading;

            var difZ       = centerPoint.Z - (camera.Z * ((camera.SpatialReference.IsGeographic) ? 1.0 : camera.SpatialReference.Unit.ConversionFactor));
            var hypotenuse = GeometryEngine.GeodesicDistance(fromPoint, centerPoint);

            radian = Math.Atan2(difZ, hypotenuse);
            var pitch = radian * 180 / Math.PI;

            camera.Pitch = pitch;

            if (fromPoint.SpatialReference.Wkid != camera.SpatialReference.Wkid)
            {
                var transformation = ProjectionTransformation.Create(fromPoint.SpatialReference, camera.SpatialReference);
                fromPoint = GeometryEngine.ProjectEx(fromPoint, transformation) as MapPoint;
            }

            camera.X = fromPoint.X;
            camera.Y = fromPoint.Y;
            return(camera);
        }
예제 #14
0
        internal async Task UpdateFeedbackWithGeoLine(LineSegment segment, GeodeticCurveType type, LinearUnit lu)
        {
            if (Point1 == null || segment == null)
            {
                return;
            }

            var polyline = await QueuedTask.Run(() =>
            {
                return(PolylineBuilder.CreatePolyline(segment));
            });

            ClearTempGraphics();
            Geometry newline = GeometryEngine.Instance.GeodeticDensifyByLength(polyline, 0, lu, type);

            await AddGraphicToMap(Point1, ColorFactory.Instance.GreenRGB, null, true, 5.0);
            await AddGraphicToMap(newline, ColorFactory.Instance.GreyRGB, null, true);
        }
예제 #15
0
        private Task <ArcGIS.Core.Geometry.Geometry> createGeometryFromJson(string json)
        {
            return(QueuedTask.Run(() =>
            {
                ArcGIS.Core.Geometry.Geometry retGeom = null;
                //{"xmin":1,"ymin":2,"xmax":3,"ymax":4,"spatialReference":{"wkid":4326}}
                try
                {
                    retGeom = GeometryEngine.Instance.ImportFromJSON(JSONImportFlags.jsonImportDefaults, json);

                    switch (retGeom.GeometryType)
                    {
                    case GeometryType.Polygon:
                        break;

                    case GeometryType.Envelope:
                        retGeom = PolygonBuilder.CreatePolygon(retGeom as Envelope);
                        break;

                    case GeometryType.Point:
                        retGeom = MapPointBuilder.CreateMapPoint(retGeom as MapPoint);
                        break;

                    case GeometryType.Multipoint:
                        retGeom = MultipointBuilder.CreateMultipoint(retGeom as Multipoint);
                        break;

                    case GeometryType.Polyline:
                        retGeom = PolylineBuilder.CreatePolyline(retGeom as Polyline);
                        break;

                    default:
                        retGeom = null;
                        break;
                    }
                }
                catch
                {
                    this.message = "I can't create a geometry...";
                }

                return retGeom;
            }));
        }
예제 #16
0
        public void CreateLineGraphic()
        {
            var graphicsLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ArcGIS.Desktop.Mapping.GraphicsLayer>().FirstOrDefault();

            if (graphicsLayer == null)
            {
                return;
            }
            QueuedTask.Run(() =>
            {
                #region Line Graphic Element using CIMGraphic
                //On the QueuedTask
                //Place a line symbol using the extent's lower left and upper right corner.
                var extent = MapView.Active.Extent;
                //get the lower left corner of the extent
                var pointFromCoordinates = new Coordinate2D(extent.XMin, extent.YMin);
                //get the upper right corner of the extent
                var pointToCoordinates     = new Coordinate2D(extent.XMax, extent.YMax);
                List <Coordinate2D> points = new List <Coordinate2D> {
                    pointFromCoordinates, pointToCoordinates
                };
                //create the polyline
                var lineSegment = PolylineBuilder.CreatePolyline(points);

                //specify a symbol
                var line_symbol = SymbolFactory.Instance.ConstructLineSymbol(
                    ColorFactory.Instance.GreenRGB);

                //create a CIMGraphic
                var graphic = new CIMLineGraphic()
                {
                    Symbol = line_symbol.MakeSymbolReference(),
                    Line   = lineSegment,
                };
                graphicsLayer.AddElement(graphic);
                #endregion
            });
        }
예제 #17
0
        /// <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(() =>
            {
                //build a circular arc
                var cent = new Coordinate2D(geometry as MapPoint);
                var circleEAB = EllipticArcBuilder.CreateEllipticArcSegment(cent, Radius, esriArcOrientation.esriArcClockwise, MapView.Active.Map.SpatialReference);

                // find the source layer and determine whether polyline/polygon.  Create the appropriate shape
                var lyr = CurrentTemplate.Layer as BasicFeatureLayer;
                Geometry circleGeom = null;
                if (lyr.ShapeType == esriGeometryType.esriGeometryPolygon)
                {
                    circleGeom = PolygonBuilder.CreatePolygon(new[] { circleEAB });
                }
                else
                {
                    circleGeom = PolylineBuilder.CreatePolyline(circleEAB);
                }

                // Create an edit operation
                var createOperation = new EditOperation();
                createOperation.Name = string.Format("Create circular {0}", CurrentTemplate.Layer.Name);
                createOperation.SelectNewFeatures = true;

                // Queue feature creation
                createOperation.Create(CurrentTemplate, circleGeom);

                // Execute the operation
                return createOperation.ExecuteAsync();
            }));
        }
예제 #18
0
        private Geometry CreatePolyline()
        {
            if (Point1 == null || Point2 == null)
            {
                return(null);
            }
            GeodeticCurveType curveType = DeriveCurveType(LineType);
            LinearUnit        lu        = DeriveUnit(LineDistanceType);

            try
            {
                // create line
                var polyline = QueuedTask.Run(() =>
                {
                    var point2Proj = GeometryEngine.Instance.Project(Point2, Point1.SpatialReference);
                    var segment    = LineBuilder.CreateLineSegment(Point1, (MapPoint)point2Proj);
                    return(PolylineBuilder.CreatePolyline(segment));
                }).Result;
                Geometry newline = GeometryEngine.Instance.GeodeticDensifyByLength(polyline, 0, lu, curveType);

                // Hold onto the attributes in case user saves graphics to file later
                LineAttributes lineAttributes = new LineAttributes()
                {
                    mapPoint1 = Point1, mapPoint2 = Point2, _distance = distance, angle = (double)azimuth, angleunit = LineAzimuthType.ToString(), distanceunit = LineDistanceType.ToString(), originx = Point1.X, originy = Point1.Y, destinationx = Point2.X, destinationy = Point2.Y
                };

                AddGraphicToMap(newline, (ProGraphicAttributes)lineAttributes);
                ResetPoints();

                return(newline as Geometry);
            }
            catch (Exception ex)
            {
                // do nothing
                return(null);
            }
        }
예제 #19
0
        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();
            }));
        }
        private void CreatePolyline()
        {
            if (Point1 == null || Point2 == null)
            {
                return;
            }

            try
            {
                // create line
                var polyline = QueuedTask.Run(() =>
                {
                    var segment = LineBuilder.CreateLineSegment(Point1, Point2);
                    return(PolylineBuilder.CreatePolyline(segment));
                }).Result;

                AddGraphicToMap(polyline);
                ResetPoints();
            }
            catch (Exception ex)
            {
                // do nothing
            }
        }
        /// <summary>
        /// This method takes an input multi part geometry and breaks the parts into individual standalone geometries.
        /// This method must be called on the MCT. Use QueuedTask.Run.
        /// </summary>
        /// <param name="inputGeometry">The geometry to be exploded into the individual parts.</param>
        /// <returns>An enumeration of individual parts as standalone geometries. The type of geometry is maintained, i.e.
        /// if the input geometry is of type Polyline then each geometry in the return is of type Polyline as well.
        /// If the input geometry is of type Unknown then an empty list is returned.</returns>
        /// <remarks>This method must be called on the MCT. Use QueuedTask.Run.</remarks>
        public IEnumerable <Geometry> MultipartToSinglePart(Geometry inputGeometry)
        {
            // list holding the part(s) of the input geometry
            List <Geometry> singleParts = new List <Geometry>();

            // check if the input is a null pointer or if the geometry is empty
            if (inputGeometry == null || inputGeometry.IsEmpty)
            {
                return(singleParts);
            }

            // based on the type of geometry, take the parts/points and add them individually into a list
            switch (inputGeometry.GeometryType)
            {
            case GeometryType.Envelope:
                singleParts.Add(inputGeometry.Clone() as Envelope);
                break;

            case GeometryType.Multipatch:
                singleParts.Add(inputGeometry.Clone() as Multipatch);
                break;

            case GeometryType.Multipoint:
                var multiPoint = inputGeometry as Multipoint;

                foreach (var point in multiPoint.Points)
                {
                    // add each point of collection as a standalone point into the list
                    singleParts.Add(point);
                }
                break;

            case GeometryType.Point:
                singleParts.Add(inputGeometry.Clone() as MapPoint);
                break;

            case GeometryType.Polygon:
                var polygon = inputGeometry as Polygon;

                foreach (var polygonPart in polygon.Parts)
                {
                    // use the PolygonBuilder turning the segments into a standalone
                    // polygon instance
                    singleParts.Add(PolygonBuilder.CreatePolygon(polygonPart));
                }
                break;

            case GeometryType.Polyline:
                var polyline = inputGeometry as Polyline;

                foreach (var polylinePart in polyline.Parts)
                {
                    // use the PolylineBuilder turning the segments into a standalone
                    // polyline instance
                    singleParts.Add(PolylineBuilder.CreatePolyline(polylinePart));
                }
                break;

            case GeometryType.Unknown:
                break;

            default:
                break;
            }

            return(singleParts);
        }
        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");
            }
        }
예제 #23
0
        /// <summary>
        /// Creates keyframes along the path using the user defined settings.
        /// </summary>
        /// <param name="line">The geometry of the line to fly along.</param>
        /// <param name="verticalUnit">The elevation unit of the 3D layer</param>
        internal Task CreateKeyframesAlongPath(Polyline line, Unit verticalUnit)
        {
            return(QueuedTask.Run(() =>
            {
                var mapView = MapView.Active;
                if (mapView == null)
                {
                    return;
                }

                //Get the camera track from the active map's animation.
                //There will always be only one camera track in the animation.
                var cameraTrack = mapView.Map.Animation.Tracks.OfType <CameraTrack>().First();

                //Get some of the user settings for constructing the keyframes alone the path.
                var densifyDistance = Animation.Settings.KeyEvery;
                var verticalOffset = Animation.Settings.HeightAbove / ((mapView.Map.SpatialReference.IsGeographic) ? 1.0 : mapView.Map.SpatialReference.Unit.ConversionFactor); //1 meter
                double currentTimeSeconds = GetInsertTime(mapView.Map.Animation);

                //We need to project the line to a projected coordinate system to calculate the line's length in 3D
                //as well as more accurately calculated heading and pitch along the path.
                if (line.SpatialReference.IsGeographic)
                {
                    if (mapView.Map.SpatialReference.IsGeographic)
                    {
                        var transformation = ProjectionTransformation.Create(line.SpatialReference, SpatialReferences.WebMercator, line.Extent);
                        line = GeometryEngine.ProjectEx(line, transformation) as Polyline;
                    }
                    else
                    {
                        var transformation = ProjectionTransformation.Create(line.SpatialReference, mapView.Map.SpatialReference, line.Extent);
                        line = GeometryEngine.ProjectEx(line, transformation) as Polyline;
                    }
                }

                //If the user has specified to create keyframes at additional locations than just the vertices
                //we will densify the line by the distance the user specified.
                if (!Animation.Settings.VerticesOnly)
                {
                    line = GeometryEngine.DensifyByLength(line, densifyDistance / line.SpatialReference.Unit.ConversionFactor) as Polyline;
                }

                //To maintain a constant speed we need to divide the total time we want the animation to take by the length of the line.
                var duration = Animation.Settings.Duration;
                var secondsPerUnit = duration / line.Length3D;
                Camera prevCamera = null;

                //Loop over each vertex in the line and create a new keyframe at each.
                for (int i = 0; i < line.PointCount; i++)
                {
                    #region Camera

                    MapPoint cameraPoint = line.Points[i];

                    //If the point is not in the same spatial reference of the map we need to project it.
                    if (cameraPoint.SpatialReference.Wkid != mapView.Map.SpatialReference.Wkid)
                    {
                        var transformation = ProjectionTransformation.Create(cameraPoint.SpatialReference, mapView.Map.SpatialReference);
                        cameraPoint = GeometryEngine.Project(cameraPoint, mapView.Map.SpatialReference) as MapPoint;
                    }

                    //Construct a new camera from the point.
                    var camera = new Camera(cameraPoint.X, cameraPoint.Y, cameraPoint.Z,
                                            Animation.Settings.Pitch, 0.0, cameraPoint.SpatialReference, CameraViewpoint.LookFrom);

                    //Convert the Z unit to meters if the camera is not in a geographic coordinate system.
                    if (!camera.SpatialReference.IsGeographic)
                    {
                        camera.Z /= camera.SpatialReference.Unit.ConversionFactor;
                    }

                    //Convert the Z to the unit of the layer's elevation unit and then add the user defined offset from the line.
                    camera.Z *= verticalUnit.ConversionFactor;
                    camera.Z += verticalOffset;

                    //If this is the last point in the collection use the same heading and pitch from the previous camera.
                    if (i + 1 == line.Points.Count)
                    {
                        camera.Heading = prevCamera.Heading;
                        camera.Pitch = prevCamera.Pitch;
                    }
                    else
                    {
                        var currentPoint = line.Points[i];
                        var nextPoint = line.Points[i + 1];

                        #region Heading

                        //Calculate the heading from the current point to the next point in the path.
                        var difX = nextPoint.X - currentPoint.X;
                        var difY = nextPoint.Y - currentPoint.Y;
                        var radian = Math.Atan2(difX, difY);
                        var heading = radian * -180 / Math.PI;
                        camera.Heading = heading;

                        #endregion

                        #region Pitch

                        //If the user doesn't want to hardcode the pitch, calculate the pitch based on the current point to the next point.
                        if (Animation.Settings.UseLinePitch)
                        {
                            var hypotenuse = Math.Sqrt(Math.Pow(difX, 2) + Math.Pow(difY, 2));
                            var difZ = nextPoint.Z - currentPoint.Z;
                            //If the line's unit is not the same as the elevation unit of the layer we need to convert the Z so they are in the same unit.
                            if (line.SpatialReference.Unit.ConversionFactor != verticalUnit.ConversionFactor)
                            {
                                difZ *= (verticalUnit.ConversionFactor / line.SpatialReference.Unit.ConversionFactor);
                            }
                            radian = Math.Atan2(difZ, hypotenuse);
                            var pitch = radian * 180 / Math.PI;
                            camera.Pitch = pitch;
                        }
                        else
                        {
                            camera.Pitch = Animation.Settings.Pitch;
                        }

                        #endregion
                    }

                    #endregion

                    #region Time

                    //The first point will have a time of 0 seconds, after that we need to set the time based on the 3D distance between the points.
                    if (i > 0)
                    {
                        var lineSegment = PolylineBuilder.CreatePolyline(new List <MapPoint>()
                        {
                            line.Points[i - 1], line.Points[i]
                        },
                                                                         line.SpatialReference);
                        var length = lineSegment.Length3D;
                        currentTimeSeconds += length * secondsPerUnit;
                    }

                    #endregion

                    //Create a new keyframe using the camera and the time.
                    cameraTrack.CreateKeyframe(camera, TimeSpan.FromSeconds(currentTimeSeconds), AnimationTransition.Linear);
                    prevCamera = camera;
                }
            }));
        }
예제 #24
0
        /// <summary>
        /// Write rhino object to ArcGIS feature layer
        /// </summary>
        /// <param name="mapLayer"></param>
        /// <param name="ro"></param>
        public static async void ThrowItOverTheFence(BasicFeatureLayer mapLayer, RhinoObject ro, RhinoDoc rhinoDoc)
        {
            Mesh mesh = null;

            var createOperation = new EditOperation();

            var projection = mapLayer.GetSpatialReference();
            var origin     = getOrigin(rhinoDoc);

            switch (ro.Geometry.ObjectType)
            {
            case ObjectType.Point:
            {
                Point    pt = ro.Geometry as Point;
                MapPoint mp = ptToGis(pt.Location, origin);
                createOperation.Create(mapLayer, mp);
                await createOperation.ExecuteAsync();

                break;
            }

            case ObjectType.Surface:
            {
                Surface srf = ro.Geometry as Surface;
                if (!srf.IsPlanar())
                {
                    Console.Out.WriteLine($"Unable to send non-planar surfaces: Guid: ${ro.Id}");
                    break;
                }
                goto case ObjectType.Brep;
            }

            case ObjectType.Curve:
            {
                Curve c      = ro.Geometry as Curve;
                var   ptList = getPointsFromCurves(new List <Curve>()
                    {
                        c
                    });
                var gisPts   = ptList.Select(p => ptToGis(p, origin)).ToList();
                var polyline = PolylineBuilder.CreatePolyline(gisPts, projection);
                createOperation.Create(mapLayer, polyline);
                await createOperation.ExecuteAsync();

                break;
            }

            case ObjectType.Brep:
            {
                Brep brep = ro.Geometry as Brep;
                if (brep.IsSolid)
                {
                    mesh = Mesh.CreateFromBrep(brep, MeshingParameters.Default)[0];
                    goto case ObjectType.Mesh;
                }
                else
                {
                    var crvs = new List <Curve>();
                    foreach (BrepEdge ed in brep.Edges)
                    {
                        crvs.Add(ed.EdgeCurve);
                    }
                    var pts     = getPointsFromCurves(crvs);
                    var gisPts  = pts.Select(p => ptToGis(p, origin)).ToList();
                    var polygon = new PolygonBuilder(gisPts).ToGeometry();
                    createOperation.Create(mapLayer, polygon);
                    await createOperation.ExecuteAsync();

                    break;
                }
            }

            case ObjectType.Extrusion:
            {
                mesh = (ro.Geometry as Extrusion).GetMesh(MeshType.Default);
                goto case ObjectType.Mesh;
            }

            case ObjectType.Mesh:
            {
                mesh = mesh ?? ro.Geometry as Mesh;
                break;
            }

            default:
            {
                Console.Out.WriteLine($"Unable to send geometry type: ${ro.Geometry.ObjectType}");
                break;
            }
            }
        }
        /// <summary>
        /// Method to draw the radials inside the range rings
        /// Must have at least 1 radial
        /// All radials are drawn from the center point to the farthest ring
        /// </summary>
        private void DrawRadials()
        {
            // must have at least 1
            if (NumberOfRadials < 1)
            {
                return;
            }

            double azimuth      = 0.0;
            double interval     = 360.0 / NumberOfRadials;
            double radialLength = 0.0;

            if (IsInteractive)
            {
                radialLength = maxDistance;
            }
            else
            {
                radialLength = Distance * NumberOfRings;
            }

            try
            {
                // for each radial, draw from center point
                for (int x = 0; x < NumberOfRadials; x++)
                {
                    var polyline = QueuedTask.Run(() =>
                    {
                        MapPoint movedMP = null;
                        var mpList       = new List <MapPoint>()
                        {
                            Point1
                        };
                        // get point 2

                        var results = GeometryEngine.GeodeticMove(mpList, MapView.Active.Map.SpatialReference, radialLength, GetLinearUnit(LineDistanceType), GetAzimuthAsRadians(azimuth), GetCurveType());
                        // update feedback
                        //UpdateFeedback();
                        foreach (var mp in results)
                        {
                            movedMP = mp;
                        }
                        if (movedMP != null)
                        {
                            var segment = LineBuilder.CreateLineSegment(Point1, movedMP);
                            return(PolylineBuilder.CreatePolyline(segment));
                        }
                        else
                        {
                            return(null);
                        }
                    }).Result;
                    Geometry newline = GeometryEngine.GeodeticDensifyByLength(polyline, 0, LinearUnit.Meters, CurveType.Loxodrome);
                    if (newline != null)
                    {
                        AddGraphicToMap(newline);
                    }


                    azimuth += interval;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        private void CreateTable(string tableName, string filePath)
        {
            _dataTable.TableName = tableName;
            var oidCol = new DataColumn(ObjectIdFieldName, typeof(Int32))
            {
                AutoIncrement     = true,
                AutoIncrementSeed = 1
            };

            _dataTable.Columns.Add(oidCol);
            _dataTable.PrimaryKey = new DataColumn[] { oidCol };
            _dataTable.Columns.Add(new DataColumn(GeometryFieldName, typeof(ArcGIS.Core.Geometry.Geometry)));
            _dataTable.Columns.Add(new DataColumn(LongFieldName, typeof(Double)));
            _dataTable.Columns.Add(new DataColumn(LatFieldName, typeof(Double)));
            _dataTable.Columns.Add(new DataColumn(AltFieldName, typeof(Double)));
            _dataTable.Columns.Add(new DataColumn(TypeFieldName, typeof(string)));
            _dataTable.Columns.Add(new DataColumn(DateTimeFieldName, typeof(DateTime)));
            _dataTable.Columns.Add(new DataColumn(NameFieldName, typeof(string)));
            _dataTable.Columns.Add(new DataColumn(CreatorFieldName, typeof(string)));
            _dataTable.Columns.Add(new DataColumn(CreatorVersionFieldName, typeof(string)));

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filePath);
            string xmlns             = xmlDoc.DocumentElement.NamespaceURI;
            XmlNamespaceManager nmsp = new XmlNamespaceManager(xmlDoc.NameTable);

            nmsp.AddNamespace("x", xmlns);
            DateTime    dateValue = DateTime.Now;
            XmlNodeList nodeList  = xmlDoc.DocumentElement.SelectNodes(@"//x:gpx/x:metadata/x:time", nmsp);

            if (nodeList.Count > 0)
            {
                var dateStr = nodeList[0].InnerText;
                try
                {
                    dateValue = DateTime.Parse(dateStr);
                    Console.WriteLine("'{0}' converted to {1}.", dateStr, dateValue);
                }
                catch (FormatException)
                {
                    Console.WriteLine("Unable to convert '{0}'.", dateStr);
                }
            }
            var creator        = string.Empty;
            var creatorVersion = string.Empty;

            nodeList = xmlDoc.DocumentElement.SelectNodes(@"//x:gpx", nmsp);
            if (nodeList.Count > 0)
            {
                var node = nodeList[0];
                foreach (XmlAttribute attr in node.Attributes)
                {
                    switch (attr.Name)
                    {
                    case "creator":
                        creator = attr.Value;
                        break;

                    case "version":
                        creatorVersion = attr.Value;
                        break;
                    }
                }
            }
            var activityName = string.Empty;
            var activityType = string.Empty;

            nodeList = xmlDoc.DocumentElement.SelectNodes("/x:gpx/x:trk/x:name", nmsp);
            if (nodeList.Count > 0)
            {
                activityName = nodeList[0].InnerText;
            }
            nodeList = xmlDoc.DocumentElement.SelectNodes("/x:gpx/x:trk/x:type", nmsp);
            if (nodeList.Count > 0)
            {
                activityType = nodeList[0].InnerText;
            }

            var newRow = _dataTable.NewRow();

            newRow[ObjectIdFieldName] = 1;
            // let's make a 3d line shape
            List <Coordinate3D> lst3DCoords = new List <Coordinate3D>();
            double lng = 0.0, lat = 0.0, ele = 0.0;

            nodeList = xmlDoc.DocumentElement.SelectNodes("/x:gpx/x:trk/x:trkseg/x:trkpt", nmsp);
            foreach (XmlNode node in nodeList)
            {
                lng = double.Parse(node.Attributes["lon"].Value);
                lat = double.Parse(node.Attributes["lat"].Value);
                foreach (XmlNode childNode in node.ChildNodes)
                {
                    if (childNode.Name.Equals("ele"))
                    {
                        ele = double.Parse(childNode.InnerText);
                    }
                }
                lst3DCoords.Add(new Coordinate3D(lng, lat, ele));
            }
            var pl = PolylineBuilder.CreatePolyline(lst3DCoords, _spatialReference);

            newRow[GeometryFieldName]       = pl;
            newRow[LongFieldName]           = lng;
            newRow[LatFieldName]            = lat;
            newRow[AltFieldName]            = ele;
            newRow[DateTimeFieldName]       = dateValue;
            newRow[TypeFieldName]           = activityType;
            newRow[NameFieldName]           = activityName;
            newRow[CreatorFieldName]        = creator;
            newRow[CreatorVersionFieldName] = creatorVersion;
            _dataTable.Rows.Add(newRow);
            _gisExtent = _gisExtent == null
                                ? pl.Extent : _gisExtent.Union(pl.Extent);
        }
        /// <summary>
        /// Method to draw the radials inside the range rings
        /// Must have at least 1 radial
        /// All radials are drawn from the center point to the farthest ring
        /// </summary>
        private void DrawRadials()
        {
            // must have at least 1
            if (NumberOfRadials < 1)
            {
                return;
            }

            double azimuth      = 0.0;
            double interval     = 360.0 / NumberOfRadials;
            double radialLength = 0.0;

            if (IsInteractive)
            {
                radialLength = maxDistance;
            }
            else
            {
                radialLength = Distance * NumberOfRings;
            }

            try
            {
                // for each radial, draw from center point
                for (int x = 0; x < NumberOfRadials; x++)
                {
                    var polyline = QueuedTask.Run(() =>
                    {
                        MapPoint movedMP = null;
                        var mpList       = new List <MapPoint>()
                        {
                            Point1
                        };
                        // get point 2

                        var results = GeometryEngine.Instance.GeodeticMove(mpList,
                                                                           MapView.Active.Map.SpatialReference, radialLength, GetLinearUnit(LineDistanceType), GetAzimuthAsRadians(azimuth), GetCurveType());

                        // update feedback
                        //UpdateFeedback();
                        foreach (var mp in results)
                        {
                            movedMP = mp;
                        }

                        if (movedMP != null)
                        {
                            var movedMPproj = GeometryEngine.Instance.Project(movedMP, Point1.SpatialReference);
                            var segment     = LineBuilder.CreateLineSegment(Point1, (MapPoint)movedMPproj);
                            return(PolylineBuilder.CreatePolyline(segment));
                        }
                        else
                        {
                            return(null);
                        }
                    }).Result;

                    Geometry newline = GeometryEngine.Instance.GeodeticDensifyByLength(polyline, 0, LinearUnit.Meters, GeodeticCurveType.Loxodrome);
                    if (newline != null)
                    {
                        // Hold onto the attributes in case user saves graphics to file later
                        RangeAttributes rangeAttributes = new RangeAttributes()
                        {
                            mapPoint     = Point1, numRings = NumberOfRings,
                            distance     = radialLength,
                            centerx      = Point1.X, centery = Point1.Y,
                            distanceunit = LineDistanceType.ToString(), ringorradial = "Radial"
                        };

                        // AddGraphicToMap(newline, rangeAttributes);
                        CreateRangeRingOrRadialFeature(newline, rangeAttributes);
                    }

                    azimuth += interval;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
        private async Task AddHeightToMeasurementAsync(Geometry geometry, MapView mapView)
        {
            const double e = 0.1;

            switch (geometry.GeometryType)
            {
            case GeometryType.Point:
                if (!_updateHeight)
                {
                    _updateHeight = true;
                    await UpdateHeightAsync(mapView);

                    _updateHeight = false;
                }

                break;

            case GeometryType.Polyline:
                if (!_updateHeight)
                {
                    _updateHeight = true;
                    await UpdateHeightAsync(mapView);

                    Polyline        polyline      = geometry as Polyline;
                    List <MapPoint> mapLinePoints = new List <MapPoint>();
                    bool            changesLine   = false;

                    if (polyline != null)
                    {
                        foreach (MapPoint point in polyline.Points)
                        {
                            if (Math.Abs(point.Z) < e)
                            {
                                changesLine = true;
                                MapPoint srcLinePoint = await AddHeightToMapPointAsync(point);

                                mapLinePoints.Add(MapPointBuilder.CreateMapPoint(srcLinePoint, polyline.SpatialReference));
                            }
                            else
                            {
                                mapLinePoints.Add(point);
                            }
                        }

                        if (changesLine)
                        {
                            await QueuedTask.Run(() =>
                            {
                                polyline = PolylineBuilder.CreatePolyline(mapLinePoints, polyline.SpatialReference);
                            });

                            await mapView.SetCurrentSketchAsync(polyline);
                        }
                    }

                    _updateHeight = false;
                }

                break;

            case GeometryType.Polygon:
                if (!_updateHeight)
                {
                    _updateHeight = true;
                    await UpdateHeightAsync(mapView);

                    Polygon         polygon          = geometry as Polygon;
                    List <MapPoint> mapPolygonPoints = new List <MapPoint>();
                    bool            changesPolygon   = false;

                    if (polygon != null)
                    {
                        for (int j = 0; j < polygon.Points.Count; j++)
                        {
                            MapPoint mapPoint = polygon.Points[j];

                            if ((Math.Abs(mapPoint.Z) < e) && (j <= (polygon.Points.Count - 2)))
                            {
                                changesPolygon = true;
                                MapPoint srcPolygonPoint = await AddHeightToMapPointAsync(mapPoint);

                                mapPolygonPoints.Add(srcPolygonPoint);
                            }
                            else if (changesPolygon && (j == (polygon.Points.Count - 1)))
                            {
                                mapPolygonPoints.Add(mapPolygonPoints[0]);
                            }
                            else
                            {
                                mapPolygonPoints.Add(mapPoint);
                            }
                        }

                        if (changesPolygon)
                        {
                            await QueuedTask.Run(() =>
                            {
                                polygon = PolygonBuilder.CreatePolygon(mapPolygonPoints, polygon.SpatialReference);
                            });

                            await mapView.SetCurrentSketchAsync(polygon);
                        }
                    }

                    _updateHeight = false;
                }

                break;
            }
        }
예제 #29
0
        public void snippets_CreateLayoutElements()
        {
            LayoutView layoutView = LayoutView.Active;
            Layout     layout     = layoutView.Layout;

            #region Create point graphic with symbology

            //Create a simple 2D point graphic and apply an existing point style item as the symbology.
            //An alternative simple symbol is also provided below.  This would completely elminate the 4 lines of code that reference a style.

            QueuedTask.Run(() =>
            {
                //Build 2D point geometry
                Coordinate2D coord2D = new Coordinate2D(2.0, 10.0);

                //Reference a point symbol in a style
                StyleProjectItem ptStylePrjItm = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
                SymbolStyleItem ptSymStyleItm  = ptStylePrjItm.SearchSymbols(StyleItemType.PointSymbol, "City Hall")[0];
                CIMPointSymbol pointSym        = ptSymStyleItm.Symbol as CIMPointSymbol;
                pointSym.SetSize(50);

                //Set symbolology, create and add element to layout
                //CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 25.0, SimpleMarkerStyle.Star);  //Alternative simple symbol
                GraphicElement ptElm = LayoutElementFactory.Instance.CreatePointGraphicElement(layout, coord2D, pointSym);
                ptElm.SetName("New Point");
            });
            #endregion

            #region Create line graphic with symbology

            //Create a simple 2D line graphic and apply an existing line style item as the symbology.
            //An alternative simple symbol is also provided below.  This would completely elminate the 4 lines of code that reference a style.

            QueuedTask.Run(() =>
            {
                //Build 2d line geometry
                List <Coordinate2D> plCoords = new List <Coordinate2D>();
                plCoords.Add(new Coordinate2D(1, 8.5));
                plCoords.Add(new Coordinate2D(1.66, 9));
                plCoords.Add(new Coordinate2D(2.33, 8.1));
                plCoords.Add(new Coordinate2D(3, 8.5));
                Polyline linePl = PolylineBuilder.CreatePolyline(plCoords);

                //Reference a line symbol in a style
                StyleProjectItem lnStylePrjItm = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
                SymbolStyleItem lnSymStyleItm  = lnStylePrjItm.SearchSymbols(StyleItemType.LineSymbol, "Line with 2 Markers")[0];
                CIMLineSymbol lineSym          = lnSymStyleItm.Symbol as CIMLineSymbol;
                lineSym.SetSize(20);

                //Set symbolology, create and add element to layout
                //CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid);  //Alternative simple symbol
                GraphicElement lineElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, linePl, lineSym);
                lineElm.SetName("New Line");
            });
            #endregion

            #region Create rectangle graphic with simple symbology

            //Create a simple 2D rectangle graphic and apply simple fill and outline symbols.

            QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D rec_ll = new Coordinate2D(1.0, 4.75);
                Coordinate2D rec_ur = new Coordinate2D(3.0, 5.75);
                Envelope rec_env    = EnvelopeBuilder.CreateEnvelope(rec_ll, rec_ur);

                //Set symbolology, create and add element to layout
                CIMStroke outline        = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 5.0, SimpleLineStyle.Solid);
                CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB, SimpleFillStyle.DiagonalCross, outline);
                GraphicElement recElm    = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, rec_env, polySym);
                recElm.SetName("New Rectangle");
            });
            #endregion

            #region Create text element with basic font properties

            //Create a simple point text element and assign basic symbology as well as basic text settings.

            QueuedTask.Run(() =>
            {
                //Build 2D point geometry
                Coordinate2D coord2D = new Coordinate2D(3.5, 10);

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym       = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.RedRGB, 32, "Arial", "Regular");
                string textString       = "Point text";
                GraphicElement ptTxtElm = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, coord2D, textString, sym);
                ptTxtElm.SetName("New Point Text");

                //Change additional text properties
                ptTxtElm.SetAnchor(Anchor.CenterPoint);
                ptTxtElm.SetX(4.5);
                ptTxtElm.SetY(9.5);
                ptTxtElm.SetRotation(45);
            });
            #endregion

            #region Create rectangle text with more advanced symbol settings

            //Create rectangle text with background and border symbology.  Also notice how formatting tags are using within the text string.

            QueuedTask.Run(() =>
            {
                //Build 2D polygon geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(3.5, 7));
                plyCoords.Add(new Coordinate2D(4.5, 7));
                plyCoords.Add(new Coordinate2D(4.5, 6.7));
                plyCoords.Add(new Coordinate2D(5.5, 6.7));
                plyCoords.Add(new Coordinate2D(5.5, 6.1));
                plyCoords.Add(new Coordinate2D(3.5, 6.1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym         = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB, 10, "Arial", "Regular");
                string text               = "Some Text String that is really long and is <BOL>forced to wrap to other lines</BOL> so that we can see the effects." as String;
                GraphicElement polyTxtElm = LayoutElementFactory.Instance.CreatePolygonParagraphGraphicElement(layout, poly, text, sym);
                polyTxtElm.SetName("New Polygon Text");

                //(Optionally) Modify paragraph border
                CIMGraphic polyTxtGra = polyTxtElm.Graphic;
                CIMParagraphTextGraphic cimPolyTxtGra   = polyTxtGra as CIMParagraphTextGraphic;
                cimPolyTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimPolyTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                polyTxtElm.SetGraphic(polyTxtGra);
            });
            #endregion

            #region Create a new picture element with advanced symbol settings

            //Create a picture element and also set background and border symbology.

            QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D pic_ll = new Coordinate2D(6, 1);
                Coordinate2D pic_ur = new Coordinate2D(8, 2);
                Envelope env        = EnvelopeBuilder.CreateEnvelope(pic_ll, pic_ur);

                //Create and add element to layout
                string picPath        = @"C:\Temp\WhitePass.jpg";
                GraphicElement picElm = LayoutElementFactory.Instance.CreatePictureGraphicElement(layout, env, picPath);
                picElm.SetName("New Picture");

                //(Optionally) Modify the border and shadow
                CIMGraphic picGra                   = picElm.Graphic;
                CIMPictureGraphic cimPicGra         = picGra as CIMPictureGraphic;
                cimPicGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimPicGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid);

                cimPicGra.Frame.ShadowSymbol        = new CIMSymbolReference();
                cimPicGra.Frame.ShadowSymbol.Symbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.BlackRGB, SimpleFillStyle.Solid);

                picElm.SetGraphic(picGra);
            });
            #endregion

            #region Create a map frame and zoom to a bookmark

            //Create a map frame and also sets its extent by zooming the the extent of an existing bookmark.

            QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D mf_ll = new Coordinate2D(6.0, 8.5);
                Coordinate2D mf_ur = new Coordinate2D(8.0, 10.5);
                Envelope mf_env    = EnvelopeBuilder.CreateEnvelope(mf_ll, mf_ur);

                //Reference map, create MF and add to layout
                MapProjectItem mapPrjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map"));
                Map mfMap      = mapPrjItem.GetMap();
                MapFrame mfElm = LayoutElementFactory.Instance.CreateMapFrame(layout, mf_env, mfMap);
                mfElm.SetName("New Map Frame");

                //Zoom to bookmark
                Bookmark bookmark = mfElm.Map.GetBookmarks().FirstOrDefault(b => b.Name == "Great Lakes");
                mfElm.SetCamera(bookmark);
            });
            #endregion

            #region Create a legend for a specifc map frame

            //Create a legend for an associated map frame.

            QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D leg_ll = new Coordinate2D(6, 2.5);
                Coordinate2D leg_ur = new Coordinate2D(8, 4.5);
                Envelope leg_env    = EnvelopeBuilder.CreateEnvelope(leg_ll, leg_ur);

                //Reference MF, create legend and add to layout
                MapFrame mapFrame = layout.FindElement("New Map Frame") as MapFrame;
                if (mapFrame == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
                    return;
                }
                Legend legendElm = LayoutElementFactory.Instance.CreateLegend(layout, leg_env, mapFrame);
                legendElm.SetName("New Legend");
            });
            #endregion

            #region Creating group elements
            //Create an empty group element at the root level of the contents pane
            //Note: call within QueuedTask.Run()
            GroupElement grp1 = LayoutElementFactory.Instance.CreateGroupElement(layout);
            grp1.SetName("Group");

            //Create a group element inside another group element
            //Note: call within QueuedTask.Run()
            GroupElement grp2 = LayoutElementFactory.Instance.CreateGroupElement(grp1);
            grp2.SetName("Group in Group");
            #endregion Creating group elements

            {
                #region Create scale bar
                Coordinate2D llScalebar = new Coordinate2D(6, 2.5);
                MapFrame     mapframe   = layout.FindElement("New Map Frame") as MapFrame;
                //Note: call within QueuedTask.Run()
                LayoutElementFactory.Instance.CreateScaleBar(layout, llScalebar, mapframe);
                #endregion
            }
            #region How to search for scale bars in a style
            var arcgis_2d = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D");
            QueuedTask.Run(() => {
                var scaleBarItems = arcgis_2d.SearchScaleBars("Double Alternating Scale Bar");
            });

            #endregion

            #region How to add a scale bar from a style to a layout
            var arcgis_2dStyle = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D");
            QueuedTask.Run(() =>
            {
                //Imperial Double Alternating Scale Bar
                //Metric Double Alternating Scale Bar
                //or just use empty string to list them all...
                var scaleBarItem     = arcgis_2d.SearchScaleBars("Double Alternating Scale Bar").FirstOrDefault();
                Coordinate2D coord2D = new Coordinate2D(10.0, 7.0);
                MapFrame myMapFrame  = layout.FindElement("Map Frame") as MapFrame;
                LayoutElementFactory.Instance.CreateScaleBar(layout, coord2D, myMapFrame, scaleBarItem);
            });
            #endregion

            #region Create NorthArrow
            Coordinate2D llNorthArrow = new Coordinate2D(6, 2.5);
            MapFrame     mf           = layout.FindElement("New Map Frame") as MapFrame;
            //Note: call within QueuedTask.Run()
            var northArrow = LayoutElementFactory.Instance.CreateNorthArrow(layout, llNorthArrow, mf);
            #endregion

            #region How to search for North Arrows in a style
            var arcgis_2dStyles = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D");
            QueuedTask.Run(() => {
                var scaleBarItems = arcgis_2dStyles.SearchNorthArrows("ArcGIS North 13");
            });
            #endregion

            #region How to add a North Arrow from a style to a layout
            var arcgis2dStyles = Project.Current.GetItems <StyleProjectItem>().First(si => si.Name == "ArcGIS 2D");
            QueuedTask.Run(() => {
                var northArrowStyleItem = arcgis2dStyles.SearchNorthArrows("ArcGIS North 13").FirstOrDefault();
                Coordinate2D nArrow     = new Coordinate2D(6, 2.5);
                MapFrame newFrame       = layout.FindElement("New Map Frame") as MapFrame;
                //Note: call within QueuedTask.Run()
                var newNorthArrow = LayoutElementFactory.Instance.CreateNorthArrow(layout, nArrow, newFrame, northArrowStyleItem);
            });

            #endregion

            #region Create dynamic text
            var          title   = @"<dyn type = ""page"" property = ""name"" />";
            Coordinate2D llTitle = new Coordinate2D(6, 2.5);
            //Note: call within QueuedTask.Run()
            var titleGraphics = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, llTitle, null) as TextElement;
            titleGraphics.SetTextProperties(new TextProperties(title, "Arial", 24, "Bold"));
            #endregion


            #region Create dynamic table

            QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D tab_ll = new Coordinate2D(6, 2.5);
                Coordinate2D tab_ur = new Coordinate2D(12, 6.5);
                Envelope tab_env    = EnvelopeBuilder.CreateEnvelope(tab_ll, tab_ur);
                MapFrame mapFrame   = layout.FindElement("New Map Frame") as MapFrame;
                // get the layer
                MapProjectItem mapPrjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map"));
                Map theMap = mapPrjItem?.GetMap();
                var lyrs   = theMap?.FindLayers("Inspection Point Layer", true);
                if (lyrs?.Count > 0)
                {
                    Layer lyr  = lyrs[0];
                    var table1 = LayoutElementFactory.Instance.CreateTableFrame(layout, tab_env, mapFrame, lyr, new string[] { "No", "Type", "Description" });
                }
            });
            #endregion
        }
예제 #30
0
        async public static void CreateElementSnippets()
        {
            //There are already many Create element snippets in the PRO snippets section.  This section will only contain examples that are NOT in the Pro snippets section
            //Pro snippets region names includes:
            //    Create point graphic with symbology
            //    Create line graphic with symbology
            //    Create rectangle graphic with simple symbology
            //    Create text element with basic font properties
            //    Create rectangle text with more advanced symbol settings
            //    Create a new picture element with advanced symbol settings
            //    Create a map frame and zoom to a bookmark
            //    Create a legend for a specifc map frame
            //    Creating group elements

            LayoutView lytView = LayoutView.Active;
            Layout     layout  = lytView.Layout;

            #region Create_BeizierCurve
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D pt1          = new Coordinate2D(1, 7.5);
                Coordinate2D pt2          = new Coordinate2D(1.66, 8);
                Coordinate2D pt3          = new Coordinate2D(2.33, 7.1);
                Coordinate2D pt4          = new Coordinate2D(3, 7.5);
                CubicBezierBuilder bez    = new CubicBezierBuilder(pt1, pt2, pt3, pt4);
                CubicBezierSegment bezSeg = bez.ToSegment();
                Polyline bezPl            = PolylineBuilder.CreatePolyline(bezSeg);

                //Set symbology, create and add element to layout
                CIMLineSymbol lineSym = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.RedRGB, 4.0, SimpleLineStyle.DashDot);
                GraphicElement bezElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, bezPl, lineSym);
                bezElm.SetName("New Bezier Curve");
            });

            #endregion Create_BeizierCurve

            #region Create_freehand
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plCoords = new List <Coordinate2D>();
                plCoords.Add(new Coordinate2D(1.5, 10.5));
                plCoords.Add(new Coordinate2D(1.25, 9.5));
                plCoords.Add(new Coordinate2D(1, 10.5));
                plCoords.Add(new Coordinate2D(0.75, 9.5));
                plCoords.Add(new Coordinate2D(0.5, 10.5));
                plCoords.Add(new Coordinate2D(0.5, 1));
                plCoords.Add(new Coordinate2D(0.75, 2));
                plCoords.Add(new Coordinate2D(1, 1));
                Polyline linePl = PolylineBuilder.CreatePolyline(plCoords);

                //Set symbolology, create and add element to layout
                CIMLineSymbol lineSym  = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid);
                GraphicElement lineElm = LayoutElementFactory.Instance.CreateLineGraphicElement(layout, linePl, lineSym);
                lineElm.SetName("New Freehand");
            });

            #endregion Create_freehand

            #region Create_polygon
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(1, 7));
                plyCoords.Add(new Coordinate2D(2, 7));
                plyCoords.Add(new Coordinate2D(2, 6.7));
                plyCoords.Add(new Coordinate2D(3, 6.7));
                plyCoords.Add(new Coordinate2D(3, 6.1));
                plyCoords.Add(new Coordinate2D(1, 6.1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMStroke outline        = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.DashDotDot);
                CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
                GraphicElement polyElm   = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, poly, polySym);
                polyElm.SetName("New Polygon");
            });

            #endregion Create_polygon

            #region Create_circle
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center       = new Coordinate2D(2, 4);
                EllipticArcBuilder eabCir = new EllipticArcBuilder(center, 0.5, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment cir    = eabCir.ToSegment();

                //Set symbolology, create and add element to layout
                CIMStroke outline          = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Dash);
                CIMPolygonSymbol circleSym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, outline);
                GraphicElement cirElm      = LayoutElementFactory.Instance.CreateCircleGraphicElement(layout, cir, circleSym);
                cirElm.SetName("New Circle");
            });

            #endregion Create_circle

            #region Create_ellipse
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center        = new Coordinate2D(2, 2.75);
                EllipticArcBuilder eabElp  = new EllipticArcBuilder(center, 0, 1, 0.45, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment ellipse = eabElp.ToSegment();

                //Set symbolology, create and add element to layout
                CIMStroke outline           = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB, 2.0, SimpleLineStyle.Dot);
                CIMPolygonSymbol ellipseSym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreyRGB, SimpleFillStyle.Vertical, outline);
                GraphicElement elpElm       = LayoutElementFactory.Instance.CreateEllipseGraphicElement(layout, ellipse, ellipseSym);
                elpElm.SetName("New Ellipse");
            });

            #endregion Create_ellipse

            #region Create_lasso
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(1, 1));
                plyCoords.Add(new Coordinate2D(1.25, 2));
                plyCoords.Add(new Coordinate2D(1.5, 1.1));
                plyCoords.Add(new Coordinate2D(1.75, 2));
                plyCoords.Add(new Coordinate2D(2, 1.1));
                plyCoords.Add(new Coordinate2D(2.25, 2));
                plyCoords.Add(new Coordinate2D(2.5, 1.1));
                plyCoords.Add(new Coordinate2D(2.75, 2));
                plyCoords.Add(new Coordinate2D(3, 1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMStroke outline        = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0, SimpleLineStyle.Solid);
                CIMPolygonSymbol polySym = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.ForwardDiagonal, outline);
                GraphicElement polyElm   = LayoutElementFactory.Instance.CreatePolygonGraphicElement(layout, poly, polySym);
                polyElm.SetName("New Lasso");
            });

            #endregion Create_lasso

            #region Create_CurveText
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D pt1          = new Coordinate2D(3.6, 7.5);
                Coordinate2D pt2          = new Coordinate2D(4.26, 8);
                Coordinate2D pt3          = new Coordinate2D(4.93, 7.1);
                Coordinate2D pt4          = new Coordinate2D(5.6, 7.5);
                CubicBezierBuilder bez    = new CubicBezierBuilder(pt1, pt2, pt3, pt4);
                CubicBezierSegment bezSeg = bez.ToSegment();
                Polyline bezPl            = PolylineBuilder.CreatePolyline(bezSeg);

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym        = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 24, "Comic Sans MS", "Regular");
                GraphicElement bezTxtElm = LayoutElementFactory.Instance.CreateCurvedTextGraphicElement(layout, bezPl, "Curved Text", sym);
                bezTxtElm.SetName("New Splinned Text");
            });

            #endregion Create_CurveText

            #region Create_PolygonText
            await QueuedTask.Run(() =>
            {
                //Build geometry
                List <Coordinate2D> plyCoords = new List <Coordinate2D>();
                plyCoords.Add(new Coordinate2D(3.5, 7));
                plyCoords.Add(new Coordinate2D(4.5, 7));
                plyCoords.Add(new Coordinate2D(4.5, 6.7));
                plyCoords.Add(new Coordinate2D(5.5, 6.7));
                plyCoords.Add(new Coordinate2D(5.5, 6.1));
                plyCoords.Add(new Coordinate2D(3.5, 6.1));
                Polygon poly = PolygonBuilder.CreatePolygon(plyCoords);

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym         = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB, 10, "Arial", "Regular");
                string text               = "Some Text String that is really long and is <BOL>forced to wrap to other lines</BOL> so that we can see the effects." as String;
                GraphicElement polyTxtElm = LayoutElementFactory.Instance.CreatePolygonParagraphGraphicElement(layout, poly, text, sym);
                polyTxtElm.SetName("New Polygon Text");

                //(Optionally) Modify paragraph border
                CIMGraphic polyTxtGra = polyTxtElm.Graphic;
                CIMParagraphTextGraphic cimPolyTxtGra   = polyTxtGra as CIMParagraphTextGraphic;
                cimPolyTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimPolyTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                polyTxtElm.SetGraphic(polyTxtGra);
            });

            #endregion Create_PolygonText

            #region Create_CircleText
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center       = new Coordinate2D(4.5, 4);
                EllipticArcBuilder eabCir = new EllipticArcBuilder(center, 0.5, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment cir    = eabCir.ToSegment();

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym        = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreenRGB, 10, "Arial", "Regular");
                string text              = "Circle, circle, circle, circle, circle, circle, circle, circle, circle, circle, circle";
                GraphicElement cirTxtElm = LayoutElementFactory.Instance.CreateCircleParagraphGraphicElement(layout, cir, text, sym);
                cirTxtElm.SetName("New Circle Text");

                //(Optionally) Modify paragraph border
                CIMGraphic cirTxtGra = cirTxtElm.Graphic;
                CIMParagraphTextGraphic cimCirTxtGra   = cirTxtGra as CIMParagraphTextGraphic;
                cimCirTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimCirTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                cirTxtElm.SetGraphic(cirTxtGra);
            });

            #endregion Create_CircleText

            #region Create_EllipseText
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D center        = new Coordinate2D(4.5, 2.75);
                EllipticArcBuilder eabElp  = new EllipticArcBuilder(center, 0, 1, 0.45, esriArcOrientation.esriArcClockwise);
                EllipticArcSegment ellipse = eabElp.ToSegment();

                //Set symbolology, create and add element to layout
                CIMTextSymbol sym        = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB, 10, "Arial", "Regular");
                string text              = "Ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse, ellipse";
                GraphicElement elpTxtElm = LayoutElementFactory.Instance.CreateEllipseParagraphGraphicElement(layout, ellipse, text, sym);
                elpTxtElm.SetName("New Ellipse Text");

                //(Optionally) Modify paragraph border
                CIMGraphic elpTxtGra = elpTxtElm.Graphic;
                CIMParagraphTextGraphic cimElpTxtGra   = elpTxtGra as CIMParagraphTextGraphic;
                cimElpTxtGra.Frame.BorderSymbol        = new CIMSymbolReference();
                cimElpTxtGra.Frame.BorderSymbol.Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1.0, SimpleLineStyle.Solid);
                elpTxtElm.SetGraphic(elpTxtGra);
            });

            #endregion Create_EllipseText

            MapFrame mfElm = null;
            #region Create_MapFrame
            //This example creates a new map frame and changes the camera scale.
            await QueuedTask.Run(() =>
            {
                //Build geometry
                Coordinate2D ll = new Coordinate2D(6.0, 8.5);
                Coordinate2D ur = new Coordinate2D(8.0, 10.5);
                Envelope env    = EnvelopeBuilder.CreateEnvelope(ll, ur);

                //Reference map, create MF and add to layout
                MapProjectItem mapPrjItem = Project.Current.GetItems <MapProjectItem>().FirstOrDefault(item => item.Name.Equals("Map"));
                Map mfMap = mapPrjItem.GetMap();
                mfElm     = LayoutElementFactory.Instance.CreateMapFrame(layout, env, mfMap);
                mfElm.SetName("New Map Frame");

                //Set the camera
                Camera camera = mfElm.Camera;
                camera.Scale  = 24000;
                mfElm.SetCamera(camera);
            });

            #endregion Create_MapFrame


            #region Create_ScaleBar
            await QueuedTask.Run(() =>
            {
                //Reference a North Arrow in a style
                StyleProjectItem stylePrjItm = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
                ScaleBarStyleItem sbStyleItm = stylePrjItm.SearchScaleBars("Double Alternating Scale Bar 1")[0];

                //Build geometry
                Coordinate2D center = new Coordinate2D(7, 8);

                //Reference MF, create north arrow and add to layout
                MapFrame mf = layout.FindElement("New Map Frame") as MapFrame;
                if (mf == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
                    return;
                }
                ScaleBar sbElm = LayoutElementFactory.Instance.CreateScaleBar(layout, center, mf, sbStyleItm);
                sbElm.SetName("New Scale Bar");
                sbElm.SetWidth(2);
                sbElm.SetX(6);
                sbElm.SetY(7.5);
            });

            #endregion Create_ScaleBar

            #region Create_NorthArrow
            await QueuedTask.Run(() =>
            {
                //Reference a North Arrow in a style
                StyleProjectItem stylePrjItm   = Project.Current.GetItems <StyleProjectItem>().FirstOrDefault(item => item.Name == "ArcGIS 2D");
                NorthArrowStyleItem naStyleItm = stylePrjItm.SearchNorthArrows("ArcGIS North 10")[0];

                //Build geometry
                Coordinate2D center = new Coordinate2D(7, 5.5);

                //Reference MF, create north arrow and add to layout
                MapFrame mf = layout.FindElement("New Map Frame") as MapFrame;
                if (mf == null)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Map frame not found", "WARNING");
                    return;
                }
                NorthArrow arrowElm = LayoutElementFactory.Instance.CreateNorthArrow(layout, center, mf, naStyleItm);
                arrowElm.SetName("New North Arrow");
                arrowElm.SetHeight(1.75);
                arrowElm.SetX(7);
                arrowElm.SetY(6);
            });

            #endregion Create_NorthArrow
        }