示例#1
0
        protected Envelope CreateHitBox(MapView mapView, MapPoint location, double sizeInPoints, SpatialReference spatialRef)
        {
            var sizeInPixels = Drawing.PixelsFromPoints(sizeInPoints);
            var refPoint     = mapView.MapToClient(location);
            var minPoint     = mapView.ClientToMap(new System.Windows.Point(refPoint.X - sizeInPixels, refPoint.Y + sizeInPixels)); // remember, screen Y axis starts from top to bottom
            var maxPoint     = mapView.ClientToMap(new System.Windows.Point(refPoint.X + sizeInPixels, refPoint.Y - sizeInPixels));

            return(EnvelopeBuilder.CreateEnvelope(minPoint, maxPoint, spatialRef));
        }
示例#2
0
        protected override async Task <bool> OnSketchCompleteAsync(Geometry geometry)
        {
            var bottomRight = new Point();
            IList <Tuple <string, string, long> > tripleTuplePoints =
                new List <Tuple <string, string, long> >();
            var hasSelection = await QueuedTask.Run(() =>
            {
                // geometry is a point
                var clickedPnt = geometry as MapPoint;
                if (clickedPnt == null)
                {
                    System.Windows.MessageBox.Show("Clicked point is null");
                    return(false);
                }
                // pixel tolerance
                var tolerance = 10;
                //Get the client point edges
                var topLeft = new Point(clickedPnt.X - tolerance, clickedPnt.Y + tolerance);
                bottomRight = new Point(clickedPnt.X + tolerance, clickedPnt.Y - tolerance);
                //convert the client points to Map points
                var mapTopLeft     = MapView.Active.ClientToMap(topLeft);
                var mapBottomRight = MapView.Active.ClientToMap(bottomRight);
                //create a geometry using these points
                Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight);
                if (envelopeGeometry == null)
                {
                    System.Windows.MessageBox.Show("envleope is null");
                    return(false);
                }
                //Get the features that intersect the sketch geometry.
                var result = ActiveMapView.GetFeatures(geometry);
                foreach (var kvp in result)
                {
                    var bfl = kvp.Key;
                    // only look at points
                    if (kvp.Key.ShapeType != esriGeometryType.esriGeometryPoint)
                    {
                        continue;
                    }
                    var layerName = bfl.Name;
                    var oidName   = bfl.GetTable().GetDefinition().GetObjectIDField();
                    foreach (var oid in kvp.Value)
                    {
                        tripleTuplePoints.Add(new Tuple <string, string, long>(layerName, oidName, oid));
                    }
                }
                return(true);
            });

            if (hasSelection)
            {
                //System.Windows.MessageBox.Show("Has selection");
                ShowContextMenu(bottomRight, tripleTuplePoints);
            }

            return(true);
        }
示例#3
0
        public static Envelope CreateEnvelope(
            double x0, double y0, double x1, double y1,
            SpatialReference sref = null)
        {
            var p0 = new Coordinate2D(x0, y0);
            var p1 = new Coordinate2D(x1, y1);

            return(EnvelopeBuilder.CreateEnvelope(p0, p1, sref));
        }
        private static void CreateField(Report report)
        {
            #region Create a new field in the report
            //This is the gap between two fields.
            double fieldIncrement = 0.9388875113593206276389;
            //On the QueuedTask
            //New field to add.
            var newReportField = new CIMReportField
            {
                Name       = "POP1990",
                FieldOrder = 2,
            };
            //Get the "ReportSection element"
            var mainReportSection = report.Elements.OfType <ReportSection>().FirstOrDefault();
            if (mainReportSection == null)
            {
                return;
            }

            //Get the "ReportDetails" within the ReportSectionElement. ReportDetails is where "fields" are.
            var reportDetailsSection = mainReportSection?.Elements.OfType <ReportDetails>().FirstOrDefault();
            if (reportDetailsSection == null)
            {
                return;
            }

            //Within ReportDetails find the envelope that encloses a field.
            //We get the first CIMParagraphTextGraphic in the collection so that we can add the new field next to it.
            var lastFieldGraphic = reportDetailsSection.Elements.FirstOrDefault((r) =>
            {
                var gr = r as GraphicElement;
                if (gr == null)
                {
                    return(false);
                }
                return(gr.GetGraphic() is CIMParagraphTextGraphic ? true : false);
            });
            //Get the Envelope of the last field
            var graphicBounds = lastFieldGraphic.GetBounds();

            //Min and Max values of the envelope
            var xMinOfFieldEnvelope = graphicBounds.XMin;
            var yMinOfFieldEnvelope = graphicBounds.YMin;

            var xMaxOfFieldEnvelope = graphicBounds.XMax;
            var YMaxOfFieldEnvelope = graphicBounds.YMax;
            //create the new Envelope to be offset from the existing field
            MapPoint newMinPoint      = MapPointBuilder.CreateMapPoint(xMinOfFieldEnvelope + fieldIncrement, yMinOfFieldEnvelope);
            MapPoint newMaxPoint      = MapPointBuilder.CreateMapPoint(xMaxOfFieldEnvelope + fieldIncrement, YMaxOfFieldEnvelope);
            Envelope newFieldEnvelope = EnvelopeBuilder.CreateEnvelope(newMinPoint, newMaxPoint);

            //Create field
            GraphicElement fieldGraphic = ReportElementFactory.Instance.CreateFieldValueTextElement(reportDetailsSection, newFieldEnvelope, newReportField);
            #endregion
        }
        /// <summary>
        /// Zoom to the specified location
        /// </summary>
        /// <param name="extent">The extent of the geocoded candidate</param>
        /// <returns></returns>
        public static Task ZoomToLocation(CandidateExtent extent)
        {
            return(QueuedTask.Run(() =>
            {
                ArcGIS.Core.Geometry.SpatialReference spatialReference = SpatialReferenceBuilder.CreateSpatialReference(extent.WKID);
                ArcGIS.Core.Geometry.Envelope envelope = EnvelopeBuilder.CreateEnvelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax, spatialReference);

                //apply extent
                MapView.Active.ZoomTo(GeometryEngine.Expand(envelope, 3, 3, true));
            }));
        }
        internal static async Task <Multipatch> MakeFishnetRingMultiPatchAsync(Polygon inputPoly)
        {
            Envelope envPoly  = inputPoly.Extent;
            var      interval = GetFishnetIntervalDistance(envPoly);

            var mColor      = System.Windows.Media.Colors.LightCyan;
            var materialRed = new BasicMaterial
            {
                Color     = mColor,
                EdgeColor = mColor,
                EdgeWidth = 0
            };
            // create the multipatchBuilderEx object
            var mpb = new MultipatchBuilderEx();
            // create a list of patch objects
            var patches = new List <Patch>();
            var first   = true;

            for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval)
            {
                for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval)
                {
                    var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval,
                                                                envPoly.SpatialReference);
                    if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly))
                    {
                        var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv) as Polygon;
                        if (addPolygonPart.Area < 0)
                        {
                            System.Diagnostics.Debug.WriteLine($@"area: {addPolygonPart.Area}");
                        }
                        var result = await Module1.CurrentMapView.Map.GetZsFromSurfaceAsync(addPolygonPart);

                        if (result.Status == SurfaceZsResultStatus.Ok)
                        {
                            addPolygonPart = GeometryEngine.Instance.Move(result.Geometry, 0, 0, Module1.Elevation) as Polygon;
                        }
                        var patch = mpb.MakePatch(first ? esriPatchType.FirstRing : esriPatchType.Ring);
                        first = false;
                        patch.InsertPoints(0, addPolygonPart.Points);
                        patch.Material = materialRed;
                        patches.Add(patch);
                    }
                }
            }      // assign the patches to the multipatchBuilder
            mpb.Patches = patches;
            // call ToGeometry to get the multipatch
            return(mpb.ToGeometry() as Multipatch);
        }
示例#7
0
        public static async Task addLegendToLayout(Layout layout)
        {
            await QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D leg_ll = new Coordinate2D(1, 1);
                Coordinate2D leg_ur = new Coordinate2D(7.5, 3);
                Envelope leg_env    = EnvelopeBuilder.CreateEnvelope(leg_ll, leg_ur);

                //Reference MF, create legend and add to layout
                MapFrame mf      = layout.FindElement("My New Map Frame") as MapFrame;
                Legend legendElm = LayoutElementFactory.Instance.CreateLegend(layout, leg_env, mf);
                legendElm.SetName("New Legend");
            });
        }
示例#8
0
        private static Envelope FromEnvelopeMsg([CanBeNull] EnvelopeMsg envProto,
                                                [CanBeNull] SpatialReference spatialReference)
        {
            if (envProto == null)
            {
                return(null);
            }

            var result =
                EnvelopeBuilder.CreateEnvelope(new Coordinate2D(envProto.XMin, envProto.YMin),
                                               new Coordinate2D(envProto.XMax, envProto.YMax),
                                               spatialReference);

            return(result);
        }
示例#9
0
        public static async Task AddMapToNewLayout(Layout layout)
        {
            await QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D mf_ll = new Coordinate2D(1, 3.5);
                Coordinate2D mf_ur = new Coordinate2D(7.5, 9.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("My New Map Frame");
            });
        }
示例#10
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)));
        }
        private async Task <List <long> > GetFeaturesWithinGeometryAsync(FeatureLayer featureLayer)
        {
            return(await QueuedTask.Run(() =>
            {
                List <long> oids = new List <long>();
                //Get the client point edges
                Point topLeft = new Point(_toolClickedPoint.X - PixelTolerance, _toolClickedPoint.Y + PixelTolerance);
                Point bottomRight = new Point(_toolClickedPoint.X + PixelTolerance, _toolClickedPoint.Y - PixelTolerance);

                //convert the client points to Map points
                MapPoint mapTopLeft = MapView.Active.ClientToMap(topLeft);
                MapPoint mapBottomRight = MapView.Active.ClientToMap(bottomRight);

                //create a geometry using these points
                Geometry envelopeGeometry = EnvelopeBuilder.CreateEnvelope(mapTopLeft, mapBottomRight);


                if (envelopeGeometry == null)
                {
                    return null;
                }

                //Spatial query to gather the OIDs of the features within the geometry
                SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
                {
                    FilterGeometry = envelopeGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects,
                };

                using (RowCursor rowCursor = featureLayer.Search(spatialQueryFilter))
                {
                    while (rowCursor.MoveNext())
                    {
                        using (Row row = rowCursor.Current)
                        {
                            var id = row.GetObjectID();
                            oids.Add(id);
                        }
                    }
                }

                return oids;
            }));
        }
        internal static List <Geometry> MakeFishnetPolygons(Polygon inputPoly)
        {
            List <Geometry> polygons = new List <Geometry>();
            Envelope        envPoly  = inputPoly.Extent;
            var             interval = GetFishnetIntervalDistance(envPoly);

            for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval)
            {
                for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval)
                {
                    var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval, envPoly.SpatialReference);
                    if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly))
                    {
                        var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv);
                        polygons.Add(addPolygonPart);
                    }
                }
            }
            return(polygons);
        }
 /// <summary>
 /// Get the extent for the dataset (if it has one)
 /// </summary>
 /// <remarks>Ideally, your plugin table should return an extent even if it is
 /// empty</remarks>
 /// <returns><see cref="Envelope"/></returns>
 public override Envelope GetExtent()
 {
     if (_gisExtent == null)
     {
         var builder = new EnvelopeBuilder(EnvelopeBuilder.CreateEnvelope(
                                               _tableInfo.ExtentLeft,
                                               _tableInfo.ExtentBottom,
                                               _tableInfo.ExtentRight,
                                               _tableInfo.ExtentTop,
                                               _spatialReference));
         //Assume 0 for Z
         {
             builder.ZMin = 0;
             builder.ZMax = 0;
         }
         builder.HasZ = false;
         builder.HasM = false;
         return(builder.ToGeometry());
     }
     return(_gisExtent);
 }
示例#14
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
        }
示例#15
0
        public static async Task DisplayLegendAsync(Layout layout, string styleCategory, string styleName)
        {
            //Construct on the worker thread
            await QueuedTask.Run(() =>
            {
                //Build 2D envelope geometry
                Coordinate2D leg_ll = new Coordinate2D(0.5, 0.3);
                Coordinate2D leg_ur = new Coordinate2D(2.14, 2.57);
                Envelope leg_env    = EnvelopeBuilder.CreateEnvelope(leg_ll, leg_ur);

                //Reference MF, create legend and add to layout
                MapFrame mapFrame = layout.FindElement(Constants.MAPS_DEFAULT_MAP_FRAME_NAME) 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(Constants.MAPS_LEGEND);
                legendElm.SetAnchor(Anchor.BottomLeftCorner);

                // Turn off all of the layers to start
                CIMLegend cimLeg = legendElm.GetDefinition() as CIMLegend;
                foreach (CIMLegendItem legItem in cimLeg.Items)
                {
                    legItem.ShowHeading = false;
                    legItem.IsVisible   = false;
                }

                // Format other elements in the legend
                cimLeg.GraphicFrame.BorderSymbol = new CIMSymbolReference
                {
                    Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 1.5, SimpleLineStyle.Solid)
                };
                cimLeg.GraphicFrame.BorderGapX = 3;
                cimLeg.GraphicFrame.BorderGapY = 3;
                // Apply the changes
                legendElm.SetDefinition(cimLeg);
            });
        }
示例#16
0
        private Task <GeospatialBox> GetCurrentViewport()
        {
            Debug.Assert(MapView.Active != null);
            if (MapView.Active == null)
            {
                return(Task.FromResult(GeospatialBox.FullExtent));
            }

            return(QueuedTask.Run(() =>
            {
                var extent = MapView.Active.Extent;
                var extentEnvelope = EnvelopeBuilder.CreateEnvelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax, extent.SpatialReference);
                ProjectionTransformation pxForm = ProjectionTransformation.Create(extent.SpatialReference, SpatialReferences.WGS84);
                var wgsEnvelope = GeometryEngine.Instance.ProjectEx(extentEnvelope, pxForm) as Envelope;

                return new GeospatialBox()
                {
                    North = Math.Min(wgsEnvelope.YMax, 90.0),  // north up to +90 deg
                    South = Math.Max(wgsEnvelope.YMin, -90.0), // south up to -90 deg
                    West = Math.Max(wgsEnvelope.XMin, -180.0), // west up to -180 deg
                    East = Math.Min(wgsEnvelope.XMax, 180.0)   // east up to +180 deg
                };
            }));
        }
示例#17
0
 public static async Task SetDefaultMapFrameDimensionAsync(string mapFrameName, Layout oLayout, Map oMap, double xMin,
                                                           double yMin, double xMax, double yMax)
 {
     await QueuedTask.Run(() =>
     {
         //Finding the mapFrame with mapFrameName
         if (!(oLayout.FindElement(mapFrameName) is MapFrame mfElm))
         {
             //Build 2D envelope geometry
             Coordinate2D mf_ll = new Coordinate2D(xMin, yMin);
             Coordinate2D mf_ur = new Coordinate2D(xMax, yMax);
             Envelope mf_env    = EnvelopeBuilder.CreateEnvelope(mf_ll, mf_ur);
             mfElm = LayoutElementFactory.Instance.CreateMapFrame(oLayout, mf_env, oMap);
             mfElm.SetName(mapFrameName);
         }
         // Remove border from map frame
         var mapFrameDefn = mfElm.GetDefinition() as CIMMapFrame;
         mapFrameDefn.GraphicFrame.BorderSymbol = new CIMSymbolReference
         {
             Symbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlackRGB, 0, SimpleLineStyle.Null)
         };
         mfElm.SetDefinition(mapFrameDefn);
     });
 }
示例#18
0
        async protected override void OnClick()
        {
            LayoutView layoutView = LayoutView.Active;

            //Prevent tool from executing based on some conditions
            if (layoutView == null)
            {
                System.Windows.MessageBox.Show("Can't find layout view, try clicking New Game Board");
                return;
            }

            if (layoutView.Layout.Name != "Game Board")
            {
                System.Windows.MessageBox.Show("Wrong layout view: should be Game Board");
                return;
            }

            await QueuedTask.Run(() =>
            {
                //Reference the layout for moving map frames and adding new layout elements
                Layout layout = layoutView.Layout;

                //Check to see if elements were already scrambled
                MapFrame mfTest = layout.FindElement("MF1") as MapFrame;
                if (mfTest != null)
                {
                    System.Windows.MessageBox.Show("Game pieces already scrambled");
                    return;
                }

                //Build 6 envelopes to represent the locations of puzzle pieces along the outer edges
                Coordinate2D env1_ll = new Coordinate2D(0.5, 0.5);
                Coordinate2D env1_ur = new Coordinate2D(3.5, 3.5);
                Envelope env1        = EnvelopeBuilder.CreateEnvelope(env1_ll, env1_ur);

                Coordinate2D env2_ll = new Coordinate2D(0.5, 4);
                Coordinate2D env2_ur = new Coordinate2D(3.5, 7);
                Envelope env2        = EnvelopeBuilder.CreateEnvelope(env2_ll, env2_ur);

                Coordinate2D env3_ll = new Coordinate2D(0.5, 7.5);
                Coordinate2D env3_ur = new Coordinate2D(3.5, 10.5);
                Envelope env3        = EnvelopeBuilder.CreateEnvelope(env3_ll, env3_ur);

                Coordinate2D env4_ll = new Coordinate2D(13.5, 0.5);
                Coordinate2D env4_ur = new Coordinate2D(16.5, 3.5);
                Envelope env4        = EnvelopeBuilder.CreateEnvelope(env4_ll, env4_ur);

                Coordinate2D env5_ll = new Coordinate2D(13.5, 4);
                Coordinate2D env5_ur = new Coordinate2D(16.5, 7);
                Envelope env5        = EnvelopeBuilder.CreateEnvelope(env5_ll, env5_ur);

                Coordinate2D env6_ll = new Coordinate2D(13.5, 7.5);
                Coordinate2D env6_ur = new Coordinate2D(16.5, 10.5);
                Envelope env6        = EnvelopeBuilder.CreateEnvelope(env6_ll, env6_ur);

                //Randomize the envelopes by assigning new envelope variables used for map frame creation
                //Also remove the assigned env before selecting the next random env
                List <Envelope> envList = new List <Envelope> {
                    env1, env2, env3, env4, env5, env6
                };

                Random r1   = new Random();
                int i1      = r1.Next(envList.Count);
                Envelope e1 = envList[i1];
                envList.Remove(e1);

                Random r2   = new Random();
                int i2      = r2.Next(envList.Count);
                Envelope e2 = envList[i2];
                envList.Remove(e2);

                Random r3   = new Random();
                int i3      = r3.Next(envList.Count);
                Envelope e3 = envList[i3];
                envList.Remove(e3);

                Random r4   = new Random();
                int i4      = r4.Next(envList.Count);
                Envelope e4 = envList[i4];
                envList.Remove(e4);

                Random r5   = new Random();
                int i5      = r5.Next(envList.Count);
                Envelope e5 = envList[i5];
                envList.Remove(e5);

                Random r6   = new Random();
                int i6      = r6.Next(envList.Count);
                Envelope e6 = envList[i6];
                envList.Remove(e6);

                //Reference the active map view and gets its center location
                //MapView map = MapView.Active;
                MapFrame mapFrame = layout.FindElement("Main MF") as MapFrame;
                Camera cam        = mapFrame.Camera;
                double x          = cam.X;
                double y          = cam.Y;
                double scale      = cam.Scale;
                double delta      = scale * 1.5 / 12 / 3.28084; //scale * 1/2 of a 3" MF / 12" per foot / 3.28084 feet per meter

                //Insert Map Frame 1 at random location
                MapFrame mf1Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e1, mapFrame.Map);
                mf1Elm.SetName("MF1");
                Camera mf1cam = mf1Elm.Camera;
                mf1cam.X      = x - (delta * 2);
                mf1cam.Y      = y - delta;
                mf1cam.Scale  = scale;
                mf1Elm.SetCamera(mf1cam);

                //Insert Map Frame 2 at random location
                MapFrame mf2Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e2, mapFrame.Map);
                mf2Elm.SetName("MF2");
                Camera mf2cam = mf2Elm.Camera;
                mf2cam.X      = x;
                mf2cam.Y      = y - delta;
                mf2cam.Scale  = scale;
                mf2Elm.SetCamera(mf2cam);

                //Insert Map Frame 3 at random location
                MapFrame mf3Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e3, mapFrame.Map);
                mf3Elm.SetName("MF3");
                Camera mf3cam = mf3Elm.Camera;
                mf3cam.X      = x + (delta * 2);
                mf3cam.Y      = y - delta;
                mf3cam.Scale  = scale;
                mf3Elm.SetCamera(mf3cam);

                //Insert Map Frame 4 at random location

                MapFrame mf4Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e4, mapFrame.Map);
                mf4Elm.SetName("MF4");
                Camera mf4cam = mf4Elm.Camera;
                mf4cam.X      = x + (delta * 2);
                mf4cam.Y      = y + delta;
                mf4cam.Scale  = scale;
                mf4Elm.SetCamera(mf4cam);

                //Insert Map Frame 5 at random location
                MapFrame mf5Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e5, mapFrame.Map);
                mf5Elm.SetName("MF5");
                Camera mf5cam = mf5Elm.Camera;
                mf5cam.X      = x;
                mf5cam.Y      = y + delta;
                mf5cam.Scale  = scale;
                mf5Elm.SetCamera(mf5cam);

                //Insert Map Frame 6 at random location
                MapFrame mf6Elm = LayoutElementFactory.Instance.CreateMapFrame(layout, e6, mapFrame.Map);
                mf6Elm.SetName("MF6");
                Camera mf6cam = mf6Elm.Camera;
                mf6cam.X      = x - (delta * 2);
                mf6cam.Y      = y + delta;
                mf6cam.Scale  = scale;
                mf6Elm.SetCamera(mf6cam);

                //Create 6 polygon boxes that represent where the outer map frames need to be placed.
                Coordinate2D box1_ll = new Coordinate2D(4, 0.5);
                Coordinate2D box1_ur = new Coordinate2D(7, 3.5);
                Envelope box1_env    = EnvelopeBuilder.CreateEnvelope(box1_ll, box1_ur);
                GraphicElement box1  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box1_env);
                box1.SetName("Rectangle 1");

                Coordinate2D box2_ll = new Coordinate2D(7, 0.5);
                Coordinate2D box2_ur = new Coordinate2D(10, 3.5);
                Envelope box2_env    = EnvelopeBuilder.CreateEnvelope(box2_ll, box2_ur);
                GraphicElement box2  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box2_env);
                box2.SetName("Rectangle 2");

                Coordinate2D box3_ll = new Coordinate2D(10, 0.5);
                Coordinate2D box3_ur = new Coordinate2D(13, 3.5);
                Envelope box3_env    = EnvelopeBuilder.CreateEnvelope(box3_ll, box3_ur);
                GraphicElement box3  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box3_env);
                box3.SetName("Rectangle 3");

                Coordinate2D box4_ll = new Coordinate2D(10, 3.5);
                Coordinate2D box4_ur = new Coordinate2D(13, 6.5);
                Envelope box4_env    = EnvelopeBuilder.CreateEnvelope(box4_ll, box4_ur);
                GraphicElement box4  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box4_env);
                box4.SetName("Rectangle 4");

                Coordinate2D box5_ll = new Coordinate2D(7, 3.5);
                Coordinate2D box5_ur = new Coordinate2D(10, 6.5);
                Envelope box5_env    = EnvelopeBuilder.CreateEnvelope(box5_ll, box5_ur);
                GraphicElement box5  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box5_env);
                box5.SetName("Rectangle 5");

                Coordinate2D box6_ll = new Coordinate2D(4, 3.5);
                Coordinate2D box6_ur = new Coordinate2D(7, 6.5);
                Envelope box6_env    = EnvelopeBuilder.CreateEnvelope(box6_ll, box6_ur);
                GraphicElement box6  = LayoutElementFactory.Instance.CreateRectangleGraphicElement(layout, box6_env);
                box6.SetName("Rectangle 6");

                //Find MainMF and set invisible
                MapFrame mainMF = layout.FindElement("Main MF") as MapFrame;
                mainMF.SetVisible(false);

                //Update Instructions
                TextElement steps = layout.FindElement("Instructions") as TextElement;
                string text       = "<bol>Instructions: </bol>\n\n  - Click the 'Play Game' command" as String;
                var stepsProp     = steps.TextProperties;
                stepsProp.Text    = text;
                steps.SetTextProperties(stepsProp);
            });

            layoutView.ClearElementSelection();
        }
        public override Envelope GetExtent()
        {
            Envelope env = EnvelopeBuilder.CreateEnvelope(-180, -90, 180, 90, SpatialReferenceBuilder.CreateSpatialReference(4326));

            return(env);
        }
示例#20
0
        protected override void OnClick()
        {
            var project = Project.Current;

            if (project == null)
            {
                MessageBox.Show("There are no currently active projects.", "No active projects", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
                return;
            }

            double xmin = 541593.3869217434,
                   ymin = 75366.04199113384,
                   xmax = 2560080.6803334514,
                   ymax = 1383832.028539666;

            var sr         = SpatialReferenceBuilder.CreateSpatialReference(2927);
            var waEnvelope = EnvelopeBuilder.CreateEnvelope(xmin, ymin, xmax, ymax, sr);
            // Create polygon for clipping
            var waPolygon         = PolygonBuilder.CreatePolygon(waEnvelope);
            var lineSymbolForCrop = new CIMLineSymbol();


            var items = project.GetItems <MapProjectItem>();

            System.Windows.MessageBoxResult result = System.Windows.MessageBoxResult.Cancel;
            if (items.Any())
            {
                result = MessageBox.Show("Set all maps' extents to that of WA?", "Set all extents", System.Windows.MessageBoxButton.OKCancel, System.Windows.MessageBoxImage.Question);
            }

            if (result == System.Windows.MessageBoxResult.OK)
            {
                QueuedTask.Run(() =>
                {
                    var geometryEngine = GeometryEngine.Instance;
                    foreach (var item in items)
                    {
                        var map = item.GetMap();
                        // Get the current full extent of the map.
                        var currentFullExtent = map.CalculateFullExtent();
                        // Set the map's full extent to WA if WA is contained in the current full extent.
                        NotificationItem nItem;
                        bool extentWasChanged = false;
                        if (geometryEngine.Contains(currentFullExtent, waEnvelope))
                        {
                            map.SetCustomFullExtent(waEnvelope);
                            extentWasChanged = true;
                            nItem            = new NotificationItem($"{DateTime.Now.Ticks}", false, $"Extent of map \"{map.Name}\" set to WA.", NotificationType.Information);
                        }
                        else
                        {
                            nItem = new NotificationItem($"{DateTime.Now.Ticks}", false, $"Extent of map \"{map.Name}\" was not changed. Current full extent does not contain WA.", NotificationType.Information);
                        }
                        NotificationManager.AddNotification(nItem);

                        if (extentWasChanged)
                        {
                            var currentClipGeometry = map.GetClipGeometry();
                            if (currentClipGeometry == null)
                            {
                                map.SetClipGeometry(waPolygon, lineSymbolForCrop);
                            }
                        }
                    }
                });
            }
        }
        public static void ElementFactory()
        {
            #region Find the active report view
            Report report     = Project.Current.GetItems <ReportProjectItem>().FirstOrDefault().GetReport();
            var    reportPane = FrameworkApplication.Panes.FindReportPanes(report).Last();
            if (reportPane == null)
            {
                return;
            }

            ReportView reportView = reportPane.ReportView;
            #endregion

            #region Refresh the report view
            if (reportView == null)
            {
                return;
            }

            QueuedTask.Run(() =>
            {
                reportView.Refresh();
            });


            #endregion

            #region Select all elements
            var pageFooterSection = report.Elements.Where(elm => elm is ReportPageFooter).FirstOrDefault() as ReportPageFooter;

            pageFooterSection.SelectAllElements();
            #endregion

            #region Zoom to selected elements
            //Process on worker thread
            QueuedTask.Run(() =>
            {
                reportView.ZoomToSelectedElements();
            });
            #endregion Zoom to selected elements

            #region Clear element selection
            reportView.ClearElementSelection();
            #endregion

            #region Zoom to whole page
            //Process on worker thread
            QueuedTask.Run(() =>
            {
                reportView.ZoomToWholePage();
            });
            #endregion

            #region Select elements
            // Select text elements from the report footer
            var reportFooterSection = report.Elements.Where(elm => elm is ReportFooter).FirstOrDefault() as ReportFooter;
            var elements            = reportFooterSection.GetElementsAsFlattenedList();

            reportFooterSection.SelectElements(elements);
            #endregion

            #region Get selected elements
            IReadOnlyList <Element> selectedElements = reportFooterSection.GetSelectedElements();
            #endregion

            #region Refresh report view
            //Process on worker thread
            QueuedTask.Run(() =>
            {
                reportView.Refresh();
            });
            #endregion

            #region Zoom to
            var detailsSection = report.Elements.Where(elm => elm is ReportDetails).FirstOrDefault() as ReportDetails;
            var bounds         = detailsSection.GetBounds();

            Coordinate2D ll  = new Coordinate2D(bounds.XMin, bounds.YMin);
            Coordinate2D ur  = new Coordinate2D(bounds.XMax, bounds.YMax);
            Envelope     env = EnvelopeBuilder.CreateEnvelope(ll, ur);

            //Process on worker thread
            QueuedTask.Run(() =>
            {
                reportView.ZoomTo(env);
            });
            #endregion

            #region Zoom to page width
            //Process on worker thread
            QueuedTask.Run(() =>
            {
                reportView.ZoomToPageWidth();
            });
            #endregion
        }
示例#22
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
        }
        async protected override void OnClick()
        {
            //Check to see if the Game Board layout already exists
            LayoutProjectItem layoutItem = Project.Current.GetItems <LayoutProjectItem>().FirstOrDefault(item => item.Name.Equals("Game Board"));

            if (layoutItem != null)
            {
                Layout lyt = await QueuedTask.Run(() => layoutItem.GetLayout());

                //Next check to see if a layout view is already open that referencs the Game Board layout
                foreach (var pane in ProApp.Panes)
                {
                    var lytPane = pane as ILayoutPane;
                    if (lytPane == null) //if not a layout view, continue to the next pane
                    {
                        continue;
                    }
                    if (lytPane.LayoutView.Layout == lyt) //if there is a match, activate the view
                    {
                        (lytPane as Pane).Activate();
                        System.Windows.MessageBox.Show("Activating existing pane");
                        return;
                    }
                }

                //If panes don't exist, then open a new pane
                await ProApp.Panes.CreateLayoutPaneAsync(lyt);

                System.Windows.MessageBox.Show("Opening already existing layout");
                return;
            }

            //The layout does not exist so create a new one
            Layout layout = await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run <Layout>(() =>
            {
                //*** CREATE A NEW LAYOUT ***

                //Set up a page
                CIMPage newPage = new CIMPage();
                //required properties
                newPage.Width  = 17;
                newPage.Height = 11;
                newPage.Units  = LinearUnit.Inches;

                //optional rulers
                newPage.ShowRulers            = true;
                newPage.SmallestRulerDivision = 0.5;

                layout = LayoutFactory.Instance.CreateLayout(newPage);
                layout.SetName("Game Board");

                //*** INSERT MAP FRAME ***

                // create a new map with an ArcGIS Online basemap
                Map map = MapFactory.Instance.CreateMap("World Map", MapType.Map, MapViewingMode.Map, Basemap.NationalGeographic);

                //Build map frame geometry
                Coordinate2D ll = new Coordinate2D(4, 0.5);
                Coordinate2D ur = new Coordinate2D(13, 6.5);
                Envelope env    = EnvelopeBuilder.CreateEnvelope(ll, ur);

                //Create map frame and add to layout
                MapFrame mfElm = LayoutElementFactory.Instance.CreateMapFrame(layout, env, map);
                mfElm.SetName("Main MF");

                //Set the camera
                Camera camera = mfElm.Camera;
                camera.X      = 3365;
                camera.Y      = 5314468;
                camera.Scale  = 175000000;
                mfElm.SetCamera(camera);

                //*** INSERT TEXT ELEMENTS ***

                //Title text
                Coordinate2D titleTxt_ll   = new Coordinate2D(6.5, 10);
                CIMTextSymbol arial36bold  = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB, 36, "Arial", "Bold");
                GraphicElement titleTxtElm = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, titleTxt_ll, "Feeling Puzzled?", arial36bold);
                titleTxtElm.SetName("Title");

                //Instuctions text
                Coordinate2D recTxt_ll = new Coordinate2D(4.25, 6.5);
                Coordinate2D recTxt_ur = new Coordinate2D(13, 9.75);
                Envelope recEnv        = EnvelopeBuilder.CreateEnvelope(recTxt_ll, recTxt_ur);
                CIMTextSymbol arial18  = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.GreyRGB, 20, "Arial", "Regular");
                string text            = "<bol>Instructions:</bol> " +
                                         "\n\n  - Activate the map frame below and pan / zoom to desired extent" +
                                         "\n\n  - Close map frame activation" +
                                         "\n\n  - Click the 'Scramble Pieces' command" as String;
                GraphicElement recTxtElm = LayoutElementFactory.Instance.CreateRectangleParagraphGraphicElement(layout, recEnv, text, arial18);
                recTxtElm.SetName("Instructions");

                //Service layer credits
                Coordinate2D slcTxt_ll   = new Coordinate2D(0.5, 0.2);
                Coordinate2D slcTxt_ur   = new Coordinate2D(16.5, 0.4);
                Envelope slcEnv          = EnvelopeBuilder.CreateEnvelope(slcTxt_ll, slcTxt_ur);
                CIMTextSymbol arial8reg  = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 8, "Arial", "Regular");
                String slcText           = "<dyn type='layout' name='Game Board' property='serviceLayerCredits'/>";
                GraphicElement slcTxtElm = LayoutElementFactory.Instance.CreateRectangleParagraphGraphicElement(layout, slcEnv, slcText, arial8reg);
                slcTxtElm.SetName("SLC");

                //Status and results text (blank to start)
                Coordinate2D statusTxt_ll   = new Coordinate2D(4.5, 7);
                CIMTextSymbol arial24bold   = SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB, 24, "Arial", "Bold");
                GraphicElement statusTxtElm = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, statusTxt_ll, "", arial24bold);
                statusTxtElm.SetName("Status");
                return(layout);
            });

            //*** OPEN LAYOUT VIEW (must be in the GUI thread) ***
            var layoutPane = await ProApp.Panes.CreateLayoutPaneAsync(layout);

            var sel = layoutPane.LayoutView.GetSelectedElements();

            if (sel.Count > 0)
            {
                layoutPane.LayoutView.ClearElementSelection();
            }
        }
        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);
        }
示例#25
0
        // todo daro: drop or refactor
        protected static Envelope GetExtentFromItems(IEnumerable <IWorkItem> items)
        {
            double           xmin = double.MaxValue, ymin = double.MaxValue, zmin = double.MaxValue;
            double           xmax = double.MinValue, ymax = double.MinValue, zmax = double.MinValue;
            SpatialReference sref  = null;
            long             count = 0;

            if (items != null)
            {
                foreach (var item in items)
                {
                    if (item == null)
                    {
                        continue;
                    }
                    var extent = item.Extent;
                    if (extent == null)
                    {
                        continue;
                    }
                    if (extent.IsEmpty)
                    {
                        continue;
                    }

                    if (extent.XMin < xmin)
                    {
                        xmin = extent.XMin;
                    }
                    if (extent.YMin < ymin)
                    {
                        ymin = extent.YMin;
                    }
                    if (extent.ZMin < zmin)
                    {
                        zmin = extent.ZMin;
                    }

                    if (extent.XMax > xmax)
                    {
                        xmax = extent.XMax;
                    }
                    if (extent.YMax > ymax)
                    {
                        ymax = extent.YMax;
                    }
                    if (extent.ZMax > zmax)
                    {
                        zmax = extent.ZMax;
                    }

                    sref = extent.SpatialReference;

                    count += 1;
                }
            }

            // Should return null and not an empty envelope. Pluggable Datasource cannot handle
            // an empty envelope.
            return(count > 0
                                       ? EnvelopeBuilder.CreateEnvelope(new Coordinate3D(xmin, ymin, zmin),
                                                                        new Coordinate3D(xmax, ymax, zmax), sref)
                                       : null);
        }
        public async void Examples2()
        {
            //var scenelayerName = featSceneLayer?.Name;

            #region Has Associated FeatureService

            var featSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList()
                                 .OfType <FeatureSceneLayer>().First();
            if (featSceneLayer.HasAssociatedFeatureService)
            {
                //Can Select and Search...possibly edit
            }

            #endregion

            #region Search Rows on the FeatureSceneLayer

            //var featSceneLayer = ...;
            if (!featSceneLayer.HasAssociatedFeatureService)
            {
                return;//Search and Select not supported
            }
            //Multipatch (Object3D) or point?
            var is3dObject = ((ISceneLayerInfo)featSceneLayer).SceneServiceLayerType
                             == esriSceneServiceLayerType.Object3D;
            await QueuedTask.Run(() =>
            {
                var queryFilter = new QueryFilter
                {
                    WhereClause = "Name = 'Ponderosa Pine'",
                    SubFields   = "*"
                };

                int rowCount = 0;
                //or select... var select = featSceneLayer.Select(queryFilter)
                using (RowCursor rowCursor = featSceneLayer.Search(queryFilter))
                {
                    while (rowCursor.MoveNext())
                    {
                        using (var feature = rowCursor.Current as Feature)
                        {
                            var oid    = feature.GetObjectID();
                            var shape  = feature.GetShape();
                            var attrib = feature["Name"];
                            if (is3dObject)
                            {
                                //shape is a multipatch
                            }
                            else
                            {
                                //shape is a point
                            }
                            rowCount += 1;
                        }
                    }
                }
            });

            #endregion

            #region Hide Selected features and Show Hidden features

            //var featSceneLayer = ...;
            if (featSceneLayer.HasAssociatedFeatureService)
            {
                return;//Search and Select not supported
            }
            await QueuedTask.Run(() =>
            {
                QueryFilter qf = new QueryFilter()
                {
                    ObjectIDs = new List <long>()
                    {
                        6069, 6070, 6071
                    },
                    SubFields = "*"
                };
                featSceneLayer.Select(qf, SelectionCombinationMethod.New);

                featSceneLayer.HideSelectedFeatures();
                var selectionCount = featSceneLayer.SelectionCount;

                featSceneLayer.ShowHiddenFeatures();
                selectionCount = featSceneLayer.SelectionCount;
            });

            #endregion

            #region Use MapView Selection SelectFeaturesEx or GetFeaturesEx

            //var featSceneLayer = ...;
            var sname = featSceneLayer.Name;

            await QueuedTask.Run(() =>
            {
                //Select all features within the current map view
                var sz = MapView.Active.GetViewSize();

                var c_ll = new Coordinate2D(0, 0);
                var c_ur = new Coordinate2D(sz.Width, sz.Height);
                //Use screen coordinates for 3D selection on MapView
                var env = EnvelopeBuilder.CreateEnvelope(c_ll, c_ur);

                //HasAssociatedFeatureService does not matter for SelectFeaturesEx
                //or GetFeaturesEx
                var result = MapView.Active.SelectFeaturesEx(env);
                //var result = MapView.Active.GetFeaturesEx(env);

                //The list of object ids from SelectFeaturesEx
                var oids1 = result.Where(kvp => kvp.Key.Name == sname).First().Value;
                //TODO - use the object ids

                MapView.Active.Map.ClearSelection();
            });

            #endregion

            #region Use Select or Search with a Spatial Query

            //var featSceneLayer = ...;
            //var sname = featSceneLayer.Name;
            await QueuedTask.Run(() =>
            {
                if (!featSceneLayer.HasAssociatedFeatureService)
                {
                    return;//no search or select
                }
                //Select all features within the current map view
                var sz      = MapView.Active.GetViewSize();
                var map_pt1 = MapView.Active.ClientToMap(new System.Windows.Point(0, sz.Height));
                var map_pt2 = MapView.Active.ClientToMap(new System.Windows.Point(sz.Width, 0));

                //Convert to an envelope
                var temp_env = EnvelopeBuilder.CreateEnvelope(map_pt1, map_pt2, MapView.Active.Map.SpatialReference);

                //Project if needed to the layer spatial ref
                SpatialReference sr = null;
                using (var fc = featSceneLayer.GetFeatureClass())
                    using (var fdef = fc.GetDefinition())
                        sr = fdef.GetSpatialReference();

                var env = GeometryEngine.Instance.Project(temp_env, sr) as Envelope;

                //Set up a query filter
                var sf = new SpatialQueryFilter()
                {
                    FilterGeometry      = env,
                    SpatialRelationship = SpatialRelationship.Intersects,
                    SubFields           = "*"
                };

                //Select against the feature service
                var select = featSceneLayer.Select(sf);
                if (select.GetCount() > 0)
                {
                    //enumerate over the selected features
                    using (var rc = select.Search())
                    {
                        while (rc.MoveNext())
                        {
                            using (var feature = rc.Current as Feature)
                            {
                                var oid = feature.GetObjectID();
                                //etc.
                            }
                        }
                    }
                }

                MapView.Active.Map.ClearSelection();
            });

            #endregion
        }
        /// <summary>
        /// asynchronous function to request or this spatial reference exists in the current area
        /// </summary>
        public async Task <bool> ExistsInAreaAsync()
        {
            await QueuedTask.Run(() =>
            {
                if (ArcGisSpatialReference == null)
                {
                    CreateSpatialReference();
                }

                if (ArcGisSpatialReference != null)
                {
                    MapView activeView = MapView.Active;
                    Envelope envelope  = null;

                    if (activeView == null)
                    {
                        FileSettings settings             = FileSettings.Instance;
                        SpatialReference spatialReference = settings.CycloramaViewerCoordinateSystem;

                        if (spatialReference != null)
                        {
                            if (spatialReference.ArcGisSpatialReference == null)
                            {
                                spatialReference.CreateSpatialReference();
                            }

                            if (spatialReference.ArcGisSpatialReference != null)
                            {
                                Bounds bounds     = spatialReference.NativeBounds;
                                var minCoordinate = new Coordinate2D(bounds.MinX, bounds.MinY);
                                var maxCoordinate = new Coordinate2D(bounds.MaxX, bounds.MaxY);
                                envelope          = EnvelopeBuilder.CreateEnvelope(minCoordinate, maxCoordinate,
                                                                                   spatialReference.ArcGisSpatialReference);
                            }
                        }
                    }
                    else
                    {
                        envelope = activeView.Extent;
                    }

                    if (envelope != null)
                    {
                        ArcGISSpatialReference spatEnv = envelope.SpatialReference;
                        int spatEnvFactoryCode         = spatEnv?.Wkid ?? 0;

                        if (spatEnv != null && spatEnvFactoryCode != ArcGisSpatialReference.Wkid)
                        {
                            try
                            {
                                ProjectionTransformation projection = ProjectionTransformation.Create(envelope.SpatialReference,
                                                                                                      ArcGisSpatialReference);

                                if (!(GeometryEngine.Instance.ProjectEx(envelope, projection) is Envelope copyEnvelope) || copyEnvelope.IsEmpty)
                                {
                                    ArcGisSpatialReference = null;
                                }
                                else
                                {
                                    if (NativeBounds != null)
                                    {
                                        double xMin = NativeBounds.MinX;
                                        double yMin = NativeBounds.MinY;
                                        double xMax = NativeBounds.MaxX;
                                        double yMax = NativeBounds.MaxY;

                                        if (copyEnvelope.XMin < xMin || copyEnvelope.XMax > xMax || copyEnvelope.YMin < yMin ||
                                            copyEnvelope.YMax > yMax)
                                        {
                                            ArcGisSpatialReference = null;
                                        }
                                    }
                                }
                            }
                            catch (ArgumentException)
                            {
                                ArcGisSpatialReference = null;
                            }
                        }
示例#28
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
        }
示例#29
0
        private void AddTableToLayout(Layout layout, Map theMap, MapFrame mfElm, string layerName, SetPage setPage, double yOffset)
        {
            var lyrs = theMap.FindLayers(layerName, true);

            if (lyrs.Count > 0)
            {
                Layer lyr      = lyrs[0];
                var   ptSymbol = GetPointSymbolFromLayer(lyr);
                if (ptSymbol != null)
                {
                    Coordinate2D llSym = new Coordinate2D(setPage.XOffsetMapMarginalia, setPage.YOffsetSymbol + yOffset);
                    var          sym   = LayoutElementFactory.Instance.CreatePointGraphicElement(layout, llSym, ptSymbol);

                    Coordinate2D llText = new Coordinate2D(setPage.XOffsetMapMarginalia + sym.GetWidth(), setPage.YOffsetSymbol + yOffset - sym.GetHeight() / 2);
                    var          text   = LayoutElementFactory.Instance.CreatePointTextGraphicElement(layout, llText, lyr.Name);
                    text.SetAnchor(Anchor.CenterPoint);
                    text.SetHeight(text.GetHeight());
                    if (text.GetHeight() > sym.GetHeight())
                    {
                        sym.SetLockedAspectRatio(true);
                        sym.SetHeight(text.GetHeight());
                    }
                    else
                    {
                        text.SetLockedAspectRatio(true);
                        text.SetHeight(sym.GetHeight());
                    }
                }
                Coordinate2D llTab1 = new Coordinate2D(setPage.XOffsetMapMarginalia, yOffset - setPage.HeightPartsMarginalia);
                Coordinate2D urTab1 = new Coordinate2D(setPage.XOffsetMapMarginalia + setPage.XWidthMapMarginalia, yOffset);
                var          table1 = LayoutElementFactory.Instance.CreateTableFrame(layout, EnvelopeBuilder.CreateEnvelope(llTab1, urTab1), mfElm, lyr, new string[] { "No", "Type", "Description" });
            }
        }
示例#30
0
        private void AddTableToLayout(Layout layout, Map theMap, MapFrame mfElm, string layerName, SetPage setPage, double yOffset)
        {
            var lyrs = theMap.FindLayers(layerName, true);

            if (lyrs.Count > 0)
            {
                Layer lyr = lyrs[0];

                Coordinate2D llTab1   = new Coordinate2D(setPage.XOffsetMapMarginalia, yOffset - 2 * setPage.HeightPartsMarginalia);
                Coordinate2D urTab1   = new Coordinate2D(setPage.XOffsetMapMarginalia + setPage.XWidthMapMarginalia, yOffset);
                var          theTable = LayoutElementFactory.Instance.CreateTableFrame(layout, EnvelopeBuilder.CreateEnvelope(llTab1, urTab1), mfElm, lyr, new string[] { "Label", "Description" });
                var          def      = theTable.GetDefinition() as CIMTableFrame;
                def.FillingStrategy = TableFrameFillingStrategy.ShowAllRows;
                theTable.SetDefinition(def);
            }
        }