示例#1
0
        public void CreateMultiPointGraphics()
        {
            var graphicsLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <ArcGIS.Desktop.Mapping.GraphicsLayer>().FirstOrDefault();

            if (graphicsLayer == null)
            {
                return;
            }
            QueuedTask.Run(() =>
            {
                #region Multi-point Graphic Element using CIMGraphic
                //On the QueuedTask
                //Place a multipoint graphic using the mapview extent geometry
                var extent = MapView.Active.Extent;
                //Contract the extent
                var polygonEnv = extent.Expand(-100000, -90000, false);
                //create a polygon using the envelope
                var polygon = PolygonBuilder.CreatePolygon(polygonEnv);
                //Create MultipPoints from the polygon
                var multiPoints = MultipointBuilder.CreateMultipoint(polygon);
                //specify a symbol
                var point_symbol = SymbolFactory.Instance.ConstructPointSymbol(
                    ColorFactory.Instance.GreenRGB);

                //create a CIMGraphic
                var graphic = new CIMMultipointGraphic
                {
                    Symbol     = point_symbol.MakeSymbolReference(),
                    Multipoint = multiPoints
                };
                graphicsLayer.AddElement(graphic);
                #endregion
            });
        }
示例#2
0
        public static ArcGIS.Core.Geometry.Geometry ToScreenGeometry(
            MapView mapView, Polygon mapGeometry)
        {
            // TODO: ensure single-part, linear segments

            var screenPoints = new List <Coordinate2D>();

            if (mapGeometry.Extent.Width > 0 || mapGeometry.Extent.Height > 0)
            {
                foreach (var mapPoint in mapGeometry.Points)
                {
                    var screenVertex = mapView.MapToScreen(mapPoint);

                    screenPoints.Add(new Coordinate2D(screenVertex.X, screenVertex.Y));
                }

                return(PolygonBuilder.CreatePolygon(screenPoints, mapView.Camera.SpatialReference));
            }

            // The screen is probably the entire screen
            var screenPoint = mapView.MapToScreen(mapGeometry.Extent.Center);

            // The client is probably the relevant map canvas, these coords seem to correspond
            // with the tool's mouse coordinates in SketchOutputMode.Screen!?!
            var clientPoint = mapView.ScreenToClient(screenPoint);

            return(MapPointBuilder.CreateMapPoint(new Coordinate2D(clientPoint.X, clientPoint.Y)));
        }
示例#3
0
        public void MoveGraphicElements()
        {
            var graphicsLayer = MapView.Active.Map.GetLayersAsFlattenedList()
                                .OfType <ArcGIS.Desktop.Mapping.GraphicsLayer>().FirstOrDefault();

            QueuedTask.Run(() => {
                #region Move Graphic Elements
                //Each selected element will move to a set distance to the upper right.
                var selElements = graphicsLayer.GetSelectedElements();
                if (selElements.Count == 0)
                {
                    return;
                }
                //Move the element up
                foreach (var selElement in selElements)
                {
                    //Get the element's bounds
                    var elementPoly = PolygonBuilder.CreatePolygon(selElement.GetBounds());
                    //get the coordinates of the element bounding envelope.
                    var pointsList = elementPoly.Copy2DCoordinatesToList();
                    //Move the element's Anchor point to the upper right.
                    selElement.SetAnchorPoint(pointsList[1]);
                }
                #endregion
            });
        }
 public void setPolygon()
 {
     QueuedTask.Run(() =>
     {
         var sr  = SpatialReferenceBuilder.CreateSpatialReference(4326);
         polygon = PolygonBuilder.CreatePolygon(footprintVertices, sr).Clone();
     });
 }
示例#5
0
 public static Polygon CreatePolygon(Envelope envelope, SpatialReference sref = null)
 {
     if (envelope == null)
     {
         return(null);
     }
     return(PolygonBuilder.CreatePolygon(envelope, sref));
 }
示例#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);
        }
        public Polygon ClosePolygon()
        {
            Polygon polygon = PolygonBuilder.CreatePolygon(_points);

            // todo daro: remove when equality is assured
            // CreatePolygon() should close the polygon. Simplify it to check equality
            Geometry simplifiedGeometry = GeometryEngine.Instance.SimplifyAsFeature(polygon);

            Assert.True(simplifiedGeometry.IsEqual(polygon));

            return(polygon);
        }
示例#8
0
        protected async void CreateNewRecord()
        {
            #region Create a new record
            await QueuedTask.Run(async() =>
            {
                Dictionary <string, object> RecordAttributes = new Dictionary <string, object>();
                var layers              = MapView.Active.Map.GetLayersAsFlattenedList();
                var recordsLayer        = layers.FirstOrDefault(l => l.Name == "Records" && l is FeatureLayer);
                var myParcelFabricLayer = layers.FirstOrDefault(l => l is ParcelLayer) as ParcelLayer;
                var spatRef             = recordsLayer.Map.SpatialReference;

                var editOper = new EditOperation()
                {
                    Name            = "Create Parcel Fabric Record",
                    ProgressMessage = "Create Parcel Fabric Record...",
                    ShowModalMessageAfterFailure = true,
                    SelectNewFeatures            = false,
                    SelectModifiedFeatures       = false
                };

                string sNewRecordName = "myNewRecord";
                Polygon newPolygon    = null;
                newPolygon            = PolygonBuilder.CreatePolygon(spatRef);
                if (newPolygon != null)
                {
                    RecordAttributes.Add("Name", sNewRecordName);
                    var editRowToken = editOper.CreateEx(recordsLayer, newPolygon, RecordAttributes);
                    RecordAttributes.Clear();
                    if (!await editOper.ExecuteAsync())
                    {
                        return;
                    }

                    //Default Guid
                    var defGuid = new Guid("dddddddd-dddd-dddd-dddd-dddddddddddd");
                    var defOID  = -1;
                    var guid    = editRowToken.GlobalID.HasValue ? editRowToken.GlobalID.Value : defGuid;
                    var lOid    = editRowToken.ObjectID.HasValue ? editRowToken.ObjectID.Value : defOID;

                    if (guid == defGuid | lOid == defOID)
                    {
                        return;
                    }

                    ParcelRecord parcelRecord = new ParcelRecord(myParcelFabricLayer.Map, sNewRecordName, guid, lOid);
                    await myParcelFabricLayer.SetActiveRecord(parcelRecord);
                }
            });

            #endregion
        }
        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);
            }
        }
 protected override void OnClick()
 {
     QueuedTask.Run(() => {
         //Get all the graphics layers in the map
         var allGraphicsLayers = MapView.Active?.Map?.GetLayersAsFlattenedList().OfType <GraphicsLayer>();
         if (allGraphicsLayers.Count() == 0)
         {
             return;
         }
         //Get the geometry of the map's extent
         var geometry = PolygonBuilder.CreatePolygon(MapView.Active.Extent);
         //Keep adding the elements to the selection
         MapView.Active.SelectElements(geometry, SelectionCombinationMethod.Add);
     });
 }
示例#11
0
        public static Polygon GetShipPolygon()
        {
            MapPoint pt1 = MapPointBuilder.CreateMapPoint(0, 2.0);
            MapPoint pt2 = MapPointBuilder.CreateMapPoint(1.0, 1.0);
            MapPoint pt3 = MapPointBuilder.CreateMapPoint(1.0, -2.0);
            MapPoint pt4 = MapPointBuilder.CreateMapPoint(-1.0, -2.0);
            MapPoint pt5 = MapPointBuilder.CreateMapPoint(-1.0, 1.0);

            List <MapPoint> list = new List <MapPoint>()
            {
                pt1, pt2, pt3, pt4, pt5
            };
            Polygon polygon = PolygonBuilder.CreatePolygon(list);

            return(polygon);
        }
示例#12
0
        /// <summary>
        /// Copy the elements to an offset location
        /// </summary>
        /// <param name="graphicsLayer"></param>
        /// <param name="elements"></param>
        internal static void CustomCopyElements(this GraphicsLayer graphicsLayer, IEnumerable <Element> elements)
        {
            if (elements.Count() == 0)
            {
                return;
            }
            //Copy the elements.
            var copyElements = graphicsLayer.CopyElements(elements);

            //Iterate through the elements to move the anchor point for the copy.
            foreach (var element in copyElements)
            {
                var elementPoly = PolygonBuilder.CreatePolygon(element.GetBounds());
                var pointsList  = elementPoly.Copy2DCoordinatesToList();
                element.SetAnchorPoint(pointsList[1]);
            }
        }
示例#13
0
        private Polygon CreatePolygon(IWorkItem item)
        {
            Envelope extent = item.Extent;

            if (UseExtent(item))
            {
                return(PolygonBuilder.CreatePolygon(extent, extent.SpatialReference));
            }

            item.QueryPoints(out double xmin, out double ymin,
                             out double xmax, out double ymax,
                             out double zmax);

            return(PolygonBuilder.CreatePolygon(EnvelopeBuilder.CreateEnvelope(
                                                    new Coordinate3D(xmin, ymin, zmax),
                                                    new Coordinate3D(xmax, ymax, zmax),
                                                    extent.SpatialReference)));
        }
示例#14
0
        private static IList <ArcGIS.Core.Geometry.Geometry> GetSearchGeometries(
            [NotNull] ICollection <Feature> features,
            [CanBeNull] Envelope clipExtent)
        {
            var result = new List <ArcGIS.Core.Geometry.Geometry>(features.Count);

            foreach (var geometry in GdbObjectUtils.GetGeometries(features))
            {
                if (clipExtent != null)
                {
                    clipExtent =
                        GeometryUtils.EnsureSpatialReference(clipExtent, geometry.SpatialReference);

                    if (GeometryUtils.Disjoint(geometry, clipExtent))
                    {
                        continue;
                    }
                }

                var multiPatch = geometry as Multipatch;

                // multipatches are not supported by ISpatialFilter (and neither are bags containing them)
                var polycurve = multiPatch != null
                                                        ? PolygonBuilder.CreatePolygon(
                    multiPatch
                    .Extent)                                                     // GeometryFactory.CreatePolygon(multiPatch)
                                                        : geometry as Multipart;

                if (polycurve != null)
                {
                    // clipping is an optimization to pull less features from the db
                    result.Add(clipExtent == null
                                                           ? polycurve
                                                           : GetClippedGeometry(polycurve, clipExtent));
                }
                else
                {
                    // don't clip points etc.
                    result.Add(geometry);
                }
            }

            return(result);
        }
示例#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;
            }));
        }
        //public int AreaCoverage { get; set; }
        public async Task setAreaCoverageAsync(Geometry queryGeom)
        {
            var vertices = new List <Coordinate2D>();

            object[][][] geom   = geometry.coordinates;
            object[][]   coords = geom[0];
            try
            {
                // Create a list of coordinates describing the polygon vertices.
                for (int i = 0; i < coords.Length; i++)
                {
                    object[] xy = coords[i];
                    object   x  = xy[0];
                    object   y  = xy[1];
                    double   _x = Convert.ToDouble(x);
                    double   _y = Convert.ToDouble(y);
                    vertices.Add(new Coordinate2D(_x, _y));
                }

                await QueuedTask.Run(() =>
                {
                    var sr = SpatialReferenceBuilder.CreateSpatialReference(4326);
                    Geometry spurcepolygon = PolygonBuilder.CreatePolygon(vertices, sr).Clone();
                    Polygon interse        = (Polygon)GeometryEngine.Instance.Intersection(queryGeom, spurcepolygon);
                    //if (interse.Parts.Count > 1)
                    //{

                    //    IDisposable _graphic = null;
                    //    IDisposable _graph2 = null;
                    //    CIMPolygonSymbol _polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.BlackRGB, SimpleFillStyle.Cross, SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 1.0, SimpleLineStyle.Solid));
                    //    _graphic = MapView.Active.AddOverlay(interse, _polygonSymbol.MakeSymbolReference());
                    //    _graphic = MapView.Active.AddOverlay(interse, _polygonSymbol.MakeSymbolReference());

                    //}
                    Polygon source = (Polygon)queryGeom;
                    AreaCover      = Math.Round((interse.Area / source.Area) * 100, 1, MidpointRounding.AwayFromZero);
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#17
0
        public static Polygon CreateBezierCircle(double radius = 1, MapPoint center = null)
        {
            // Approximate a full circle with Bezier curves. (We could use
            // EllipticArc segments, of course, but in the context of markers,
            // Béziers are more appropriate.) It is customary to use four cubic
            // Bézier curves, one for each quadrant. The control points must be
            // on tangential lines to ensure continuity, their distance from
            // the axes is chosen for minimal deviation from a true circle.
            // See: https://spencermortensen.com/articles/bezier-circle/

            const double magic = 0.551915;             // for best circle approximation

            double cx = 0, cy = 0;

            if (center != null)
            {
                cx = center.X;
                cy = center.Y;
            }

            var p0  = new Coordinate2D(radius, 0).Shifted(cx, cy);
            var p01 = new Coordinate2D(radius, magic * radius).Shifted(cx, cy);
            var p10 = new Coordinate2D(magic * radius, radius).Shifted(cx, cy);
            var p1  = new Coordinate2D(0, radius).Shifted(cx, cy);
            var p12 = new Coordinate2D(-magic * radius, radius).Shifted(cx, cy);
            var p21 = new Coordinate2D(-radius, magic * radius).Shifted(cx, cy);
            var p2  = new Coordinate2D(-radius, 0).Shifted(cx, cy);
            var p23 = new Coordinate2D(-radius, -magic * radius).Shifted(cx, cy);
            var p32 = new Coordinate2D(-magic * radius, -radius).Shifted(cx, cy);
            var p3  = new Coordinate2D(0, -radius).Shifted(cx, cy);
            var p30 = new Coordinate2D(magic * radius, -radius).Shifted(cx, cy);
            var p03 = new Coordinate2D(radius, -magic * radius).Shifted(cx, cy);

            // segments for each quadrant
            var q1       = CubicBezierBuilder.CreateCubicBezierSegment(p0, p01, p10, p1);
            var q2       = CubicBezierBuilder.CreateCubicBezierSegment(p1, p12, p21, p2);
            var q3       = CubicBezierBuilder.CreateCubicBezierSegment(p2, p23, p32, p3);
            var q4       = CubicBezierBuilder.CreateCubicBezierSegment(p3, p30, p03, p0);
            var segments = new[] { q1, q2, q3, q4 };

            return(PolygonBuilder.CreatePolygon(segments));
        }
        private Geometry Buffer(Geometry geom, esriGeometryType shapeType, double margin,
                                MaskKind maskKind, bool isAnno = false)
        {
            var poly_outline = geom as Polygon;

            if (poly_outline.HasCurves)
            {
                poly_outline =
                    GeometryEngine.Instance.DensifyByDeviation(geom, 0.1 * margin) as Polygon;
            }

            if (margin > 0.0)
            {
                if (maskKind == MaskKind.Box || maskKind == MaskKind.ConvexHull)
                {
                    //strip out interior polygons
                    var ext_poly = PolygonBuilder.CreatePolygon(poly_outline.GetExteriorRings(true));

                    var joins = maskKind == MaskKind.Box ?
                                LineJoinType.Miter : LineJoinType.Bevel;
                    var buff_out = GeometryEngine.Instance.GraphicBuffer(ext_poly, margin, joins,
                                                                         LineCapType.Butt, 4, 0.05 * margin, 64);
                    poly_outline = GeometryEngine.Instance.Generalize(buff_out, 0.01 * margin) as Polygon;
                }
                else
                {
                    var buff_out = GeometryEngine.Instance.Buffer(poly_outline, margin);
                    if (maskKind == MaskKind.ExactSimplified)
                    {
                        poly_outline = GeometryEngine.Instance.Generalize(buff_out, 0.05 * margin) as Polygon;
                    }
                    else
                    {
                        poly_outline = buff_out as Polygon;
                    }
                }
            }
            //simplify if needed
            //return GeometryEngine.Instance.SimplifyAsFeature(poly_outline);
            return(poly_outline);
        }
示例#19
0
        public static ArcGIS.Core.Geometry.Geometry ToMapGeometry(MapView mapView,
                                                                  Polygon screenGeometry)
        {
            // TODO: ensure single-part, linear segments

            if (screenGeometry.Extent.Width > 0 || screenGeometry.Extent.Height > 0)
            {
                var mapPoints = new List <MapPoint>();
                foreach (var screenPoint in screenGeometry.Points)
                {
                    var mapPoint = mapView.ScreenToMap(new Point(screenPoint.X, screenPoint.Y));

                    mapPoints.Add(mapPoint);
                }

                return(PolygonBuilder.CreatePolygon(mapPoints, mapView.Camera.SpatialReference));
            }

            return(mapView.ScreenToMap(new Point(screenGeometry.Extent.XMin,
                                                 screenGeometry.Extent.YMin)));
        }
示例#20
0
        public void CodeExamples()
        {
            #region Example1

            // methods need to run on the MCT
            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                List <MapPoint> list = new List <MapPoint>();
                MapPoint minPt       = MapPointBuilder.CreateMapPoint(1.0, 1.0);
                MapPoint maxPt       = MapPointBuilder.CreateMapPoint(2.0, 2.0);

                // create an envelope
                Envelope env = EnvelopeBuilder.CreateEnvelope(minPt, maxPt);

                // create a polygon from the envelope
                using (PolygonBuilder polygonBuilder = new PolygonBuilder(env))
                {
                    Polygon poly = polygonBuilder.ToGeometry();
                }
            });

            #endregion Example1

            #region Example2

            // methods need to run on the MCT
            ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                List <MapPoint> list3D = new List <MapPoint>();
                list3D.Add(MapPointBuilder.CreateMapPoint(1.0, 1.0, 1.0, 2.0));
                list3D.Add(MapPointBuilder.CreateMapPoint(1.0, 2.0, 1.0, 2.0));
                list3D.Add(MapPointBuilder.CreateMapPoint(2.0, 2.0, 1.0, 2.0));
                list3D.Add(MapPointBuilder.CreateMapPoint(2.0, 1.0, 1.0, 2.0));

                var polygon = PolygonBuilder.CreatePolygon(list3D);
            });


            #endregion Example2
        }
示例#21
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();
            }));
        }
示例#22
0
        public Task <bool> Select(MapView mapView, Envelope box)
        {
            if (mapView == null)
            {
                return(Task.FromResult(false));
            }

            _overlay?.Dispose();
            if (box == null)
            {
                return(Task.FromResult(false));
            }
            ;

            return(QueuedTask.Run(() =>
            {
                var boxColor = ColorFactory.Instance.CreateRGBColor(Color.R, Color.G, Color.B);
                var polygon = PolygonBuilder.CreatePolygon(box);
                var symbol = SymbolFactory.Instance.ConstructPolygonSymbol(boxColor, SimpleFillStyle.Null, SymbolFactory.Instance.ConstructStroke(boxColor, LineWidth, SimpleLineStyle.Solid));

                _overlay = mapView.AddOverlay(polygon, symbol.MakeSymbolReference());
                return true;
            }));
        }
示例#23
0
        protected override void OnClick()
        {
            QueuedTask.Run(() =>
            {
                var allGraphicLayers = MapView.Active.Map.GetLayersAsFlattenedList().OfType <GraphicsLayer>();
                foreach (var gl in allGraphicLayers)
                {
                    var selElements = gl.GetSelectedElements();
                    if (selElements.Count == 0)
                    {
                        continue;
                    }
                    //Move the element up
                    foreach (var selElement in selElements)
                    {
                        var elementPoly = PolygonBuilder.CreatePolygon(selElement.GetBounds());
                        var pointsList  = elementPoly.Copy2DCoordinatesToList();
                        selElement.SetAnchorPoint(pointsList[1]);
                    }
                }

                return(true);
            });
        }
        /// <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);
        }
示例#25
0
        private Task <bool> createFunnyGarden(Geometry geometry)
        {
            if (geometry == null)
            {
                return(Task.FromResult(false));
            }

            // get the point layer from the active map
            var pointLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>()
                             .Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPoint).FirstOrDefault();

            if (pointLayer == null)
            {
                return(Task.FromResult(false));
            }

            // get the polygon layer from the active map
            var polygonLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>()
                               .Where(lyr => lyr.ShapeType == ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolygon).FirstOrDefault();

            if (polygonLayer == null)
            {
                return(Task.FromResult(false));
            }

            // Create an edit operation
            var createOperation = new EditOperation();

            createOperation.Name = string.Format("Create green");

            // we'll use the sketch geometry to create a spatial filter
            SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter();

            spatialQueryFilter.FilterGeometry      = geometry;
            spatialQueryFilter.SpatialRelationship = SpatialRelationship.Contains;

            // retrieve the point features that are inside the sketch geometry
            var searchCursor = pointLayer.Search(spatialQueryFilter);

            // Construct a polygon placeholder for the point buffers
            var treeBuffers = PolygonBuilder.CreatePolygon(geometry.SpatialReference);

            // TODO
            // 1. for each point geometry
            //     2. buffer the geometry  (Hint : use the MapView.Active.Extent.Width/50 as the buffer distance)
            //     3. union this result with the existing treeBuffers
            // 4. subtract the collection of buffers from the sketch geometry
            // HINT: use the GeometryEngine to buffer, union and subtract (difference) the geometries
            // Polygon greenGeometry = null;

            // for each found feature
            while (searchCursor.MoveNext())
            {
                // retrieve the geometry
                var treeFeature = searchCursor.Current as Feature;
                var treePoint   = treeFeature.GetShape() as MapPoint;

                // buffer the the location
                var treeBuffer = GeometryEngine.Buffer(treePoint, MapView.Active.Extent.Width / 50);

                // and union the new buffer to the existing buffer polygons
                treeBuffers = GeometryEngine.Union(treeBuffer, treeBuffers) as Polygon;
            }

            // ensure the sketch geometry is simple
            if (!GeometryEngine.IsSimpleAsFeature(geometry, true))
            {
                geometry = GeometryEngine.SimplifyAsFeature(geometry);
            }

            // construct the difference geometry between the sketch geometry and the buffered point polygons
            var greenGeometry = GeometryEngine.Difference(geometry, treeBuffers);

            // cue the create
            createOperation.Create(polygonLayer, greenGeometry);

            // execute the operation
            return(createOperation.ExecuteAsync());
        }
示例#26
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
        }
示例#27
0
        private async static void Visualize(BasicFeatureLayer dam3dLayer, BasicFeatureLayer reservoirVisLayer, BasicFeatureLayer reservoirSurfacesLayer, BasicFeatureLayer damLayer)
        {
            SharedFunctions.DeleteAllFeatures(reservoirVisLayer);
            SharedFunctions.DeleteAllFeatures(dam3dLayer);

            List <long> damIDs = new List <long>();
            var         reservoirPairsLayer = MapView.Active.Map.FindLayers("ReservoirPairs").FirstOrDefault();

            if (reservoirPairsLayer != null && ((BasicFeatureLayer)reservoirPairsLayer).SelectionCount > 0)
            {
                var reservoirPairsCursor = ((BasicFeatureLayer)reservoirPairsLayer).GetSelection().Search();
                while (reservoirPairsCursor.MoveNext())
                {
                    using (Row row = reservoirPairsCursor.Current)
                    {
                        int damId = (int)row["LowerDamId"];
                        if (!damIDs.Contains(damId))
                        {
                            damIDs.Add(damId);
                        }
                        damId = (int)row["UpperDamId"];
                        if (!damIDs.Contains(damId))
                        {
                            damIDs.Add(damId);
                        }
                    }
                }
            }
            if (damLayer.SelectionCount > 0)
            {
                var damCursor = damLayer.GetSelection().Search();
                while (damCursor.MoveNext())
                {
                    using (Row row = damCursor.Current)
                    {
                        int damId = (int)row["ObjectID"];
                        if (!damIDs.Contains(damId))
                        {
                            damIDs.Add(damId);
                        }
                    }
                }
            }
            List <CandidateDam> candidates = new List <CandidateDam>();

            SharedFunctions.LoadDamCandidatesFromLayer(candidates, damLayer);
            foreach (var dam in candidates.Where(c => damIDs.Contains(c.ObjectID)).ToList())
            {
                double contourHeight = dam.ContourHeight;

                try
                {
                    MapPoint startPoint = dam.StartPoint;
                    MapPoint endPoint   = dam.EndPoint;
                    double   damHeight  = (double)dam.DamHeight;
                    double   damLength  = (double)dam.Length;

                    Coordinate3D coord1 = startPoint.Coordinate3D;
                    int          factor = ((startPoint.Y <endPoint.Y && startPoint.X> endPoint.X) ||
                                           (startPoint.Y > endPoint.Y && startPoint.X < endPoint.X)
                                           ) ? 1 : -1;
                    Coordinate3D coord2 = new Coordinate3D(coord1.X + factor * damHeight / damLength * Math.Abs(startPoint.Y - endPoint.Y) //X
                                                           , coord1.Y + damHeight / damLength * Math.Abs(startPoint.X - endPoint.X)        //Y
                                                           , coord1.Z - damHeight);                                                        //Z
                    Coordinate3D coord3 = new Coordinate3D(coord1.X - factor * damHeight / damLength * Math.Abs(startPoint.Y - endPoint.Y) //X
                                                           , coord1.Y - damHeight / damLength * Math.Abs(startPoint.X - endPoint.X)        //Y
                                                           , coord1.Z - damHeight);                                                        //Z

                    //Workaround for Bug in ArcGIS Pro 2.4.1: if values are equal, extrusion will fail
                    coord2.X += 0.1;
                    coord2.Y += 0.1;
                    coord3.X += 0.1;
                    coord3.Y += 0.1;
                    List <Coordinate3D> coords = new List <Coordinate3D>();
                    coords.Add(coord1);
                    coords.Add(coord2);
                    coords.Add(coord3);

                    var          newPolygon3D = PolygonBuilder.CreatePolygon(coords, SpatialReference);
                    Coordinate3D coord        = new Coordinate3D(endPoint.X - startPoint.X, endPoint.Y - startPoint.Y, 0.1);
                    var          multipatch   = GeometryEngine.Instance.ConstructMultipatchExtrudeAlongVector3D(newPolygon3D, coord);
                    var          attributes2  = new Dictionary <string, object>
                    {
                        { "Shape", multipatch },
                        { "DamID", (long)dam.ObjectID }
                    };
                    var createOperation2 = new EditOperation()
                    {
                        Name = "Create multipatch", SelectNewFeatures = false
                    };
                    createOperation2.Create(dam3dLayer, attributes2);
                    await createOperation2.ExecuteAsync();

                    //add SurfacePolygon to Visualization:
                    var queryFilter = new QueryFilter {
                        WhereClause = string.Format("DamID = {0}", dam.ObjectID)
                    };
                    var surfaceCursor = reservoirSurfacesLayer.Select(queryFilter).Search();
                    if (surfaceCursor.MoveNext())
                    {
                        using (Row row = surfaceCursor.Current)
                        {
                            var polygon = (row as Feature).GetShape() as Polygon;
                            attributes2 = new Dictionary <string, object>
                            {
                                { "Shape", polygon },
                                { "DamID", (long)dam.ObjectID }
                            };
                            var createOperationSurface = new EditOperation()
                            {
                                Name = "Create surface", SelectNewFeatures = false
                            };
                            createOperationSurface.Create(reservoirVisLayer, attributes2);
                            await createOperationSurface.ExecuteAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                    SharedFunctions.Log("Error for 3D Dam with DamID " + dam.ObjectID + ": " + ex.Message);
                }

                SharedFunctions.Log("3D Dam created for Dam " + dam.ObjectID);
            }
            await Project.Current.SaveEditsAsync();
        }
示例#28
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
        }
示例#29
0
        internal async Task PerformAnalysis(MapPoint ptStartLoc, MapView mapView, ProgressorSource ps)
        {
            ps.Progressor.Message = "Running the analysis...";
            ps.Progressor.Status  = "Gathering and verifying parameter data";
            string sReqUrl = Properties.Settings.Default.QryPointToState;
            string sReq    = String.Format("{0}?returnGeometry=false&returnDistinctValues=false&geometry={1}&geometryType=esriGeometryPoint&f=json&outFields=*&spatialRel=esriSpatialRelIntersects",
                                           sReqUrl, ptStartLoc.ToJson());
            // Find out what state the user clicked; or report an error if outside the U.S.
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sReq);
            string         sResp;

            try {
                using (StreamReader sread = new StreamReader(req.GetResponse().GetResponseStream()))
                    sResp = sread.ReadToEnd();
            } catch (Exception e) {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error mapping the chosen spot to a petroleum area district in the U.S.A.: " + e.Message);
                return;
            }
            dynamic respPADDState = JsonConvert.DeserializeObject(sResp);

            try {
                string sState = respPADDState.features[0].attributes.STATE.ToString();
                // Find out what PADD zone the state is in
                SelectedPADDZone = PaddStateToZone[sState];
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine("Exception getting PADD for chosen spot: " + e.Message);
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Please choose a spot within the U.S.A.");
                return /*null*/;
            }

            // Find out the gallons/$1.00 in that PADD zone
            double nFuelCost = PADDZoneToFuelCost[SelectedPADDZone];

            // Find out the miles per dollar each vehicle: (mi / gal) / (dollars / gal)
            // Map is in meters, so convert miles to meters
            Vehicle[]            orderedVehicles        = SelectedVehicles.OrderBy(vehicle => vehicle.Mpg).ToArray <Vehicle>();
            IEnumerable <double> vehicleMetersPerDollar =
                orderedVehicles.Select(vehicle => (vehicle.MetersPerGallon) / nFuelCost);

            string   sDistsParam   = String.Join(" ", vehicleMetersPerDollar.ToArray());
            MapPoint ptStartLocNoZ = await QueuedTask.Run(() => {
                MapPoint ptNoZ = MapPointBuilder.CreateMapPoint(ptStartLoc.X, ptStartLoc.Y, ptStartLoc.SpatialReference);
                return(ptNoZ);
            });

            // No corresponding type for the needed GPFeatureRecordSetLayer parameter
            string sStartGeom     = ptStartLocNoZ.ToJson();
            string sStartLocParam = "{\"geometryType\":\"esriGeometryPoint\",\"features\":[{\"geometry\":" + sStartGeom + "}]}";


            // Run the query
            ps.Progressor.Status = "Executing the analysis";
            string sGPUrl = Properties.Settings.Default.GPFindSA;

            sGPUrl += String.Format("?Distances={0}&Start_Location={1}&f=json", sDistsParam, sStartLocParam);
            HttpWebRequest  reqSA = (HttpWebRequest)WebRequest.Create(sGPUrl);
            HttpWebResponse wr;

            try {
                wr = (HttpWebResponse)reqSA.GetResponse();
                if (wr.StatusCode != HttpStatusCode.OK)
                {
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error running analysis: " + wr.StatusDescription);
                    return;
                }
            } catch (WebException e) {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Error running analysis: " + e.Message);
                return;
            }

            // Show the results
            ps.Progressor.Status = "Processing the results";

            using (StreamReader sread = new StreamReader(wr.GetResponseStream()))
                sResp = sread.ReadToEnd();

            JObject respAnalysis = JObject.Parse(sResp);

            JArray feats = respAnalysis["results"][0]["value"]["features"] as JArray;

            // Rectify results and order so that largest polygon can be added to the map first
            List <JToken> aryResFeats = RectifyResults(feats, orderedVehicles);

            int iSR             = respAnalysis["results"][0]["value"]["spatialReference"]["wkid"].ToObject <Int32>();
            SpatialReference sr = await QueuedTask.Run <SpatialReference>(() => {
                SpatialReference srTemp = SpatialReferenceBuilder.CreateSpatialReference(iSR);
                return(srTemp);
            });

            /*lock (_lockResults)*/
            Results.ClearResults();

            // Iterate backwards to add larger polygons behind smaller ones

            for (int iVeh = orderedVehicles.Count() - 1; iVeh >= 0; iVeh--)
            {
                Result      result  = new Result(orderedVehicles[iVeh]);
                Polygon     poly    = null;
                IDisposable graphic = null;

                // Compute color for this result
                float multiplier = aryResFeats.Count > 1 ? ((float)iVeh) / ((float)(aryResFeats.Count - 1)) : 0;
                byte  red        = (byte)(255 - (255 * multiplier));
                byte  green      = (byte)(255 * multiplier);
                Color color      = Color.FromRgb(red, green, 0);
                result.Color = color.ToString();

                result.PaddZone         = SelectedPADDZone;
                result.DollarsPerGallon = nFuelCost;

                string sGeom = aryResFeats[iVeh]["geometry"].ToString();
                poly = await QueuedTask.Run(() => {
                    Polygon polyNoSR = PolygonBuilder.FromJson(sGeom);
                    return(PolygonBuilder.CreatePolygon(polyNoSR, sr));
                });

                CIMStroke        outline = SymbolFactory.ConstructStroke(ColorFactory.BlackRGB, 1.0, SimpleLineStyle.Solid);
                CIMPolygonSymbol symPoly = SymbolFactory.ConstructPolygonSymbol(
                    ColorFactory.CreateRGBColor(color.R, color.G, color.B, RESULT_OPACITY_PCT),
                    SimpleFillStyle.Solid, outline);
                CIMSymbolReference sym    = symPoly.MakeSymbolReference();
                CIMSymbolReference symDef = SymbolFactory.DefaultPolygonSymbol.MakeSymbolReference();
                graphic = await QueuedTask.Run(() => {
                    return(mapView.AddOverlay(poly, sym));
                });

                result.DriveServiceArea        = poly;
                result.DriveServiceAreaGraphic = graphic;
                result.DriveDistM = aryResFeats[iVeh]["attributes"]["ToBreak"].Value <double>();
                /*lock (_lockResults)*/
                Results.Add(result);
            }
        }
        public async Task <string> GenerateGmlAsync()
        {
            MapView            mapView       = MapView.Active;
            Map                map           = mapView?.Map;
            SpatialReference   mapSpatRef    = map?.SpatialReference;
            MySpatialReference myCyclSpatRef = _settings.CycloramaViewerCoordinateSystem;

            SpatialReference cyclSpatRef = (myCyclSpatRef == null)
        ? mapSpatRef
        : (myCyclSpatRef.ArcGisSpatialReference ?? (await myCyclSpatRef.CreateArcGisSpatialReferenceAsync()));

            Unit   unit   = cyclSpatRef?.Unit;
            double factor = unit?.ConversionFactor ?? 1;
            Color  color  = Color.White;
            string result =
                "<wfs:FeatureCollection xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:wfs=\"http://www.opengis.net/wfs\" xmlns:gml=\"http://www.opengis.net/gml\">";

            await QueuedTask.Run(async() =>
            {
                SpatialReference layerSpatRef       = Layer.GetSpatialReference();
                IList <IList <Segment> > geometries = new List <IList <Segment> >();
                ICollection <Viewer> viewers        = _viewerList.Viewers;

                foreach (var viewer in viewers)
                {
                    double distance = viewer.OverlayDrawDistance;
                    RecordingLocation recordingLocation = viewer.Location;

                    if (recordingLocation != null)
                    {
                        if (cyclSpatRef?.IsGeographic ?? true)
                        {
                            distance = distance * factor;
                        }
                        else
                        {
                            distance = distance / factor;
                        }

                        double x    = recordingLocation.X;
                        double y    = recordingLocation.Y;
                        double xMin = x - distance;
                        double xMax = x + distance;
                        double yMin = y - distance;
                        double yMax = y + distance;

                        Envelope envelope     = EnvelopeBuilder.CreateEnvelope(xMin, yMin, xMax, yMax, cyclSpatRef);
                        Envelope copyEnvelope = envelope;

                        if (layerSpatRef.Wkid != 0)
                        {
                            ProjectionTransformation projection = ProjectionTransformation.Create(cyclSpatRef, layerSpatRef);
                            copyEnvelope = GeometryEngine.Instance.ProjectEx(envelope, projection) as Envelope;
                        }

                        Polygon copyPolygon = PolygonBuilder.CreatePolygon(copyEnvelope, layerSpatRef);
                        ReadOnlyPartCollection polygonParts = copyPolygon.Parts;
                        IEnumerator <ReadOnlySegmentCollection> polygonSegments = polygonParts.GetEnumerator();
                        IList <Segment> segments = new List <Segment>();

                        while (polygonSegments.MoveNext())
                        {
                            ReadOnlySegmentCollection polygonSegment = polygonSegments.Current;

                            foreach (Segment segment in polygonSegment)
                            {
                                segments.Add(segment);
                            }
                        }

                        geometries.Add(segments);
                    }
                }

                GC.Collect();
                Polygon polygon = PolygonBuilder.CreatePolygon(geometries, layerSpatRef);

                using (FeatureClass featureClass = Layer?.GetFeatureClass())
                {
                    string uri = Layer?.URI;

                    SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                    {
                        FilterGeometry      = polygon,
                        SpatialRelationship = SpatialRelationship.Intersects,
                        SubFields           = "*"
                    };

                    using (RowCursor existsResult = featureClass?.Search(spatialFilter, false))
                    {
                        while (existsResult?.MoveNext() ?? false)
                        {
                            Row row       = existsResult.Current;
                            long objectId = row.GetObjectID();

                            if ((_selection == null) || (!_selection.Contains(objectId)))
                            {
                                Feature feature = row as Feature;
                                var fieldvalues = new Dictionary <string, string> {
                                    { FieldUri, uri }, { FieldObjectId, objectId.ToString() }
                                };

                                Geometry geometry         = feature?.GetShape();
                                GeometryType geometryType = geometry?.GeometryType ?? GeometryType.Unknown;
                                Geometry copyGeometry     = geometry;

                                if ((geometry != null) && (layerSpatRef.Wkid != 0))
                                {
                                    ProjectionTransformation projection = ProjectionTransformation.Create(layerSpatRef, cyclSpatRef);
                                    copyGeometry = GeometryEngine.Instance.ProjectEx(geometry, projection);
                                }

                                if (copyGeometry != null)
                                {
                                    string gml = string.Empty;

                                    switch (geometryType)
                                    {
                                    case GeometryType.Envelope:
                                        break;

                                    case GeometryType.Multipatch:
                                        break;

                                    case GeometryType.Multipoint:
                                        break;

                                    case GeometryType.Point:
                                        MapPoint point = copyGeometry as MapPoint;

                                        if (point != null)
                                        {
                                            gml =
                                                $"<gml:Point {GmlDimension(copyGeometry)}><gml:coordinates>{await GmlPointAsync(point)}</gml:coordinates></gml:Point>";
                                        }

                                        break;

                                    case GeometryType.Polygon:
                                        Polygon polygonGml = copyGeometry as Polygon;

                                        if (polygonGml != null)
                                        {
                                            ReadOnlyPartCollection polygonParts = polygonGml.Parts;
                                            IEnumerator <ReadOnlySegmentCollection> polygonSegments = polygonParts.GetEnumerator();

                                            while (polygonSegments.MoveNext())
                                            {
                                                ReadOnlySegmentCollection segments = polygonSegments.Current;

                                                gml =
                                                    $"{gml}<gml:MultiPolygon><gml:PolygonMember><gml:Polygon {GmlDimension(copyGeometry)}><gml:outerBoundaryIs><gml:LinearRing><gml:coordinates>";

                                                for (int i = 0; i < segments.Count; i++)
                                                {
                                                    if (segments[i].SegmentType == SegmentType.Line)
                                                    {
                                                        MapPoint polygonPoint = segments[i].StartPoint;
                                                        gml = $"{gml}{((i == 0) ? string.Empty : " ")}{await GmlPointAsync(polygonPoint)}";

                                                        if (i == (segments.Count - 1))
                                                        {
                                                            polygonPoint = segments[i].EndPoint;
                                                            gml          = $"{gml} {await GmlPointAsync(polygonPoint)}";
                                                        }
                                                    }
                                                }

                                                gml =
                                                    $"{gml}</gml:coordinates></gml:LinearRing></gml:outerBoundaryIs></gml:Polygon></gml:PolygonMember></gml:MultiPolygon>";
                                            }
                                        }
                                        break;

                                    case GeometryType.Polyline:
                                        Polyline polylineGml = copyGeometry as Polyline;

                                        if (polylineGml != null)
                                        {
                                            ReadOnlyPartCollection polylineParts = polylineGml.Parts;
                                            IEnumerator <ReadOnlySegmentCollection> polylineSegments = polylineParts.GetEnumerator();

                                            while (polylineSegments.MoveNext())
                                            {
                                                ReadOnlySegmentCollection segments = polylineSegments.Current;
                                                gml =
                                                    $"{gml}<gml:MultiLineString><gml:LineStringMember><gml:LineString {GmlDimension(copyGeometry)}><gml:coordinates>";

                                                for (int i = 0; i < segments.Count; i++)
                                                {
                                                    if (segments[i].SegmentType == SegmentType.Line)
                                                    {
                                                        MapPoint linePoint = segments[i].StartPoint;
                                                        gml = $"{gml}{((i == 0) ? string.Empty : " ")}{await GmlPointAsync(linePoint)}";

                                                        if (i == (segments.Count - 1))
                                                        {
                                                            linePoint = segments[i].EndPoint;
                                                            gml       = $"{gml} {await GmlPointAsync(linePoint)}";
                                                        }
                                                    }
                                                }

                                                gml = $"{gml}</gml:coordinates></gml:LineString></gml:LineStringMember></gml:MultiLineString>";
                                            }
                                        }

                                        break;

                                    case GeometryType.Unknown:
                                        break;
                                    }

                                    string fieldValueStr = fieldvalues.Aggregate(string.Empty,
                                                                                 (current, fieldvalue) =>
                                                                                 string.Format("{0}<{1}>{2}</{1}>", current, fieldvalue.Key, fieldvalue.Value));
                                    result =
                                        $"{result}<gml:featureMember><xs:Geometry>{fieldValueStr}{gml}</xs:Geometry></gml:featureMember>";
                                }
                            }
                        }
                    }
                }

                CIMRenderer renderer             = Layer.GetRenderer();
                CIMSimpleRenderer simpleRenderer = renderer as CIMSimpleRenderer;
                CIMUniqueValueRenderer uniqueValueRendererRenderer = renderer as CIMUniqueValueRenderer;
                CIMSymbolReference symbolRef = simpleRenderer?.Symbol ?? uniqueValueRendererRenderer?.DefaultSymbol;
                CIMSymbol symbol             = symbolRef?.Symbol;
                CIMColor cimColor            = symbol?.GetColor();
                double[] colorValues         = cimColor?.Values;

                int red   = ((colorValues != null) && (colorValues.Length >= 1)) ? ((int)colorValues[0]) : 255;
                int green = ((colorValues != null) && (colorValues.Length >= 2)) ? ((int)colorValues[1]) : 255;
                int blue  = ((colorValues != null) && (colorValues.Length >= 3)) ? ((int)colorValues[2]) : 255;
                int alpha = ((colorValues != null) && (colorValues.Length >= 4)) ? ((int)colorValues[3]) : 255;
                color     = Color.FromArgb(alpha, red, green, blue);
            });

            GmlChanged = (Color != color);
            Color      = color;
            string newGml = $"{result}</wfs:FeatureCollection>";

            GmlChanged = ((newGml != Gml) || GmlChanged);
            return(Gml = newGml);
        }