if(map.MapType!=MapType.Map)return;// not 2Dvargl_param=newGraphicsLayerCreationParams{Name="Graphics Layer"};// Note: must be called on the QueuedTask{//By default will be added to the top of the TOCgraphicsLayer=LayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.GraphicsLayer>(gl_param,map);//Add to the bottom of the TOCgl_param.MapMemberIndex=-1;//bottomLayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.GraphicsLayer>(gl_param,map);//Add a graphics layer to a group layer...vargroup_layer=map.GetLayersAsFlattenedList().OfType<GroupLayer>().First();LayerFactory.Instance.CreateLayer<ArcGIS.Desktop.Mapping.GraphicsLayer>(gl_param,group_layer);//TODO...use the graphics layer//// or use the specific CreateGroupLayer methodLayerFactory.Instance.CreateGroupLayer(map,-1,"Graphics Layer");}
Accessing GraphicsLayer
if(map.MapType!=MapType.Map){// not 2D - could be a scene - no graphics layers}//get the first graphics layer in the map's collection of graphics layersgraphicsLayer=map.GetLayersAsFlattenedList().OfType<GraphicsLayer>().FirstOrDefault();if(graphicsLayer!=null){//TODO...use the graphics layer }//Or, Get and set the graphic layer that acts as the target for interactive drawing tools. targetGraphicsLayer=map.TargetGraphicsLayer;// get the target graphics layermap.TargetGraphicsLayer=graphicsLayer;// set the target graphics layer
Copy Graphic elements
// Note: must be called on the QueuedTask{varelems=sourceGraphicsLayer.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});varcopiedElements=targetGraphicsLayer.CopyElements(elems);}
Remove Graphic elements
// Note: must be called on the QueuedTask{graphicsLayer.RemoveElements(graphicsLayer.GetSelectedElements());}
Create Graphic Elements
Point Graphic Element using CIMGraphic
// Note: must be called on the QueuedTask{//Place symbol in the center of the mapvarextent=MapView.Active.Extent;varlocation=extent.Center;//specify a symbolvarpt_symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB);//create a CIMGraphic vargraphic=newCIMPointGraphic(){Symbol=pt_symbol.MakeSymbolReference(),Location=location//center of map};graphicsLayer.AddElement(graphic);}
Line Graphic Element using CIMGraphic
// Note: must be called on the QueuedTask{//On the QueuedTask//Place a line symbol using the extent's lower left and upper right corner.varextent=MapView.Active.Extent;//get the lower left corner of the extentvarpointFromCoordinates=newCoordinate2D(extent.XMin,extent.YMin);//get the upper right corner of the extentvarpointToCoordinates=newCoordinate2D(extent.XMax,extent.YMax);List<Coordinate2D>points=newList<Coordinate2D>{pointFromCoordinates,pointToCoordinates};//create the polylinevarlineSegment=PolylineBuilderEx.CreatePolyline(points);//specify a symbolvarline_symbol=SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreenRGB);//create a CIMGraphic vargraphic=newCIMLineGraphic(){Symbol=line_symbol.MakeSymbolReference(),Line=lineSegment,};graphicsLayer.AddElement(graphic);}
Polygon Graphic Element using CIMGraphic
// Note: must be called on the QueuedTask{//On the QueuedTask//Place a polygon symbol using the mapview extent geometryvarextent=MapView.Active.Extent;//Contract the extentvarpolygonEnv=extent.Expand(-100000,-90000,false);//create a polygon using the envelopevarpolygon=PolygonBuilderEx.CreatePolygon(polygonEnv);//specify a symbolvarpoly_symbol=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.GreenRGB);//create a CIMGraphic vargraphic=newCIMPolygonGraphic(){Symbol=poly_symbol.MakeSymbolReference(),Polygon=polygon,};graphicsLayer.AddElement(graphic);}
Multi-point Graphic Element using CIMGraphic
// Note: must be called on the QueuedTask{//Place a multipoint graphic using the mapview extent geometryvarextent=MapView.Active.Extent;//Contract the extentvarpolygonEnv=extent.Expand(-100000,-90000,false);//create a polygon using the envelopevarpolygon=PolygonBuilderEx.CreatePolygon(polygonEnv);//Create MultipPoints from the polygonvarmultiPoints=MultipointBuilderEx.CreateMultipoint(polygon);//specify a symbolvarpoint_symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB);//create a CIMGraphic vargraphic=newCIMMultipointGraphic{Symbol=point_symbol.MakeSymbolReference(),Multipoint=multiPoints};graphicsLayer.AddElement(graphic);}
Graphic Element using CIMSymbol
// Note: must be called on the QueuedTask{//Place symbol in the center of the mapvarextent=MapView.Active.Extent;varlocation=extent.Center;//specify a symbolvarpt_symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB);graphicsLayer.AddElement(location,pt_symbol);}
Text Graphic Element
// Note: must be called on the QueuedTask{//Place symbol in the center of the mapvarextent=MapView.Active.Extent;varlocation=extent.Center;//specify a text symbolvartext_symbol=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB,8.5,"Corbel","Regular");graphicsLayer.AddElement(location,text_symbol,"Text Example");}
Bulk Graphics creation
//Point Feature layer to convert into graphicsvarlyr=MapView.Active?.Map?.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(s =>s.ShapeType==esriGeometryType.esriGeometryPoint);if(lyr==null)return;// Note: must be called on the QueuedTask{//Point symbol for graphicsvarpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(100,255,40),10,SimpleMarkerStyle.Circle);//Collection to hold the point graphicsvarlistGraphicElements=newList<CIMGraphic>();//Iterate through each point feature in the feature layerusing(RowCursorrows=lyr.Search())//execute{inti=0;while(rows.MoveNext()){usingvarfeature=rows.CurrentasFeature;//Create a point graphic for the featurevarcrimePt=feature.GetShape()asMapPoint;if(crimePt!=null){varcimGraphicElement=newCIMPointGraphic{Location=crimePt,//MapPointSymbol=pointSymbol.MakeSymbolReference()};//Add the point feature to the collectionlistGraphicElements.Add(cimGraphicElement);i++;}}}//Magic happens...Add all the features to the Graphics layer graphicsLayer.AddElements(listGraphicElements);}
Graphic Elements Selection
Select Graphic Elements
varelements=graphicsLayer.GetElementsAsFlattenedList().Where(e =>e.Name.StartsWith("Text"));// Note: must be called on the QueuedTask{graphicsLayer.SelectElements(elements);//or select one elementgraphicsLayer.SelectElement(elements.FirstOrDefault());}
Find Graphic elements
// Note: must be called on the QueuedTask{//Find elements by namevarelems=graphicsLayer.FindElements(newList<string>(){"Point 1","Line 3","Text 1"});//Find elements by type//Find all point graphics in the Graphics LayervarpointGraphics=graphicsLayer.GetElementsAsFlattenedList().Where(elem =>elem.GetGraphic()isCIMPointGraphic);//Find all line graphics in the Graphics LayervarlineGraphics=graphicsLayer.GetElementsAsFlattenedList().Where(elem =>elem.GetGraphic()isCIMLineGraphic);//Find all polygon graphics in the Graphics LayervarpolygonGraphics=graphicsLayer.GetElementsAsFlattenedList().Where(elem =>elem.GetGraphic()isCIMPolygonGraphic);//Find all text graphics in the Graphics LayervartextGraphics=graphicsLayer.GetElementsAsFlattenedList().Where(elem =>elem.GetGraphic()isCIMTextGraphic);//Find all picture graphics in the Graphics LayervarpictureGraphic=graphicsLayer.GetElementsAsFlattenedList().Where(elem =>elem.GetGraphic()isCIMPictureGraphic);}
Spatial selection of elements in all Graphics Layers
//Map Tool is used to perform Spatial selection.//Graphic selection uses the selection geometry //to intersect the geometries of those elements (graphic or group) //that will be selected and then highlights them. {varselPoly=geometryasPolygon;// Note: must be called on the QueuedTask{//note: the selected elements may belong to more than one layer...varelems=MapView.Active.SelectElements(selPoly,SelectionCombinationMethod.New);}}
Spatial selection of elements in one graphics layer
// Note: must be called on the QueuedTask{//Create an extent to use for the spatial selectionvarextent=MapView.Active.Extent;varselectionExtent=extent.Expand(0.5,0.5,true);//Select elements in specified graphics layer using the selection extent.varselectedElements=MapView.Active.SelectElements(graphicsLayer,selectionExtent,SelectionCombinationMethod.Add);}
//unselect the first element in the currently selected elementsvarelem=graphicsLayer.GetSelectedElements().FirstOrDefault();// Note: must be called on the QueuedTask{if(elem!=null)//Unselect one elementgraphicsLayer.UnSelectElement(elem);//unselect all elementsgraphicsLayer.UnSelectElements();//equivalent tographicsLayer.ClearSelection();}
Graphic Element Events
Subscribe to ElementSelectionChangedEvent
ArcGIS.Desktop.Layouts.Events.ElementEvent.Subscribe((args)=>{//check if the container is a graphics layer - could be a Layout (or even map view)if(args.ContainerisArcGIS.Desktop.Mapping.GraphicsLayergraphicsLayer){//get the total selection count for the containervarcount=args.Elements.Count();//Check count - could have been an unselect or clearselectif(count>0){//this is a selection or add to selectionvarelems=graphicsLayer.GetSelectedElements();//TODO process the selection...}else{//This is an unselect or clear selection//TODO process the unselect or clear select}}});
Grouping and Ordering Graphic Elements
Group Graphic Elements
// Note: must be called on the QueuedTask{varelemsToGroup=graphicsLayer.GetSelectedElements();//group elementsgroupElement=graphicsLayer.GroupElements(elemsToGroup);}
Un-Group Graphic Elements
// Note: must be called on the QueuedTask{varselectedElements=graphicsLayer.GetSelectedElements().ToList();;if(selectedElements?.Any()==false)//must be at least 1.return;varelementsToUnGroup=newList<GroupElement>();//All selected elements should be grouped.if(selectedElements.Count()==selectedElements.OfType<GroupElement>().Count()){//Convert to a GroupElement list.elementsToUnGroup=selectedElements.ConvertAll(x =>(GroupElement)x);}if(elementsToUnGroup.Count()==0)return;//UnGroupgraphicsLayer.UnGroupElements(elementsToUnGroup);}
Parent of GroupElement
//check the parentvarparent=groupElement.Elements.First().GetParent();//will be the group element//top-most parentvartop_most=groupElement.Elements.First().GetParent(true);//will be the GraphicsLayer
Ordering: Send backward and Bring forward
// Note: must be called on the QueuedTask{//get the current selection setvarsel_elems=graphicsLayer.GetSelectedElements();//can they be brought forward? This will also check that all elements have the same parentif(graphicsLayer.CanBringForward(sel_elems)){//bring forwardgraphicsLayer.BringForward(sel_elems);//bring to front (of parent)//graphicsLayer.BringToFront(sel_elems);}elseif(graphicsLayer.CanSendBackward(sel_elems)){//send backgraphicsLayer.SendBackward(sel_elems);//send to the back (of parent)//graphicsLayer.SendToBack(sel_elems);}}
Get Z-Order
// Note: must be called on the QueuedTask{varselElementsZOrder=graphicsLayer.GetSelectedElements();//list out the z orderforeach(vareleminselElementsZOrder)System.Diagnostics.Debug.WriteLine($"{elem.Name}: z-order {elem.ZOrder}");}
Modifying Graphic Elements
Move Graphic Elements
// Note: must be called on the QueuedTask{//Each selected element will move to a set distance to the upper right.varselElements=graphicsLayer.GetSelectedElements();if(selElements.Count==0)return;//Move the element upforeach(varselElementinselElements){//Get the element's boundsvarelementPoly=PolygonBuilderEx.CreatePolygon(selElement.GetBounds());//get the coordinates of the element bounding envelope.varpointsList=elementPoly.Copy2DCoordinatesToList();//Move the element's Anchor point to the upper right.selElement.SetAnchorPoint(pointsList[1]);}}
Modify symbology of a Graphic Element
// Note: must be called on the QueuedTask{//within a queued Task//get the first line element in the layervarge=graphicsLayer.FindElement("Line 10")asGraphicElement;vargraphic=ge.GetGraphic();if(graphicisCIMLineGraphiclineGraphic){//change its symbollineGraphic.Symbol=SymbolFactory.Instance.ConstructLineSymbol(SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB,2,SimpleLineStyle.DashDot)).MakeSymbolReference();//apply the changege.SetGraphic(lineGraphic);}}