ProSnippets MapAuthoring - Esri/arcgis-pro-sdk GitHub Wiki
Language: C#
Subject: MapAuthoring
Contributor: ArcGIS Pro SDK Team <[email protected]>
Organization: Esri, http://www.esri.com
Date: 11/18/2026
ArcGIS Pro: 3.8
IDE: Visual Studio 2026, Visual Studio Code
Style Management
How to get a style in project by name
//Get all styles in the projectvarProjectStyles=Project.Current.GetItems<StyleProjectItem>();//Get a specific style in the project by nameStyleProjectItemstyleFound=ProjectStyles.First(x =>x.Name=="NameOfTheStyle");
How to create a new style
//Full path for the new style file (.stylx) to be createdstringstyleToCreate=@"C:\Temp\NewStyle.stylx";varproject=Project.Current;awaitQueuedTask.Run(()=>StyleHelper.CreateStyle(project,styleToCreate));
How to add a style to project
varproject=Project.Current;awaitQueuedTask.Run(()=>{//For ArcGIS Pro system styles, just pass in the name of the style to add to the projectStyleHelper.AddStyle(project,"3D Vehicles");//For custom styles, pass in the full path to the style file on diskstringcustomStyleToAdd=@"C:\Temp\CustomStyle.stylx";StyleHelper.AddStyle(project,customStyleToAdd);});
How to remove a style from project
varproject=Project.Current;awaitQueuedTask.Run(()=>{//For ArcGIS Pro system styles, just pass in the name of the style to remove from the projectStyleHelper.RemoveStyle(project,"3D Vehicles");//For custom styles, pass in the full path to the style file on diskstringcustomStyleToAdd=@"C:\Temp\CustomStyle.stylx";StyleHelper.RemoveStyle(project,customStyleToAdd);});
How to add a style item to a style
//Create a new style item//You can generate a swatch for a text symbols also.CIMSymbolsymbolToAdd=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,1.0,SimpleMarkerStyle.Circle);SymbolStyleItemstyleItemToAdd=newSymbolStyleItem(){Symbol=symbolToAdd,PatchHeight=64,PatchWidth=64};styleProjectItem.AddItem(styleItemToAdd);
How to remove a style item from a style
//Remove any item from style//Note: symbolStyleItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.RemoveItem(symbolStyleItem));
How to determine if a style can be upgraded
//Add the style to the current projectstringstylePath=@"C:\MyStyles\OldStyle.stylx";varproject=Project.Current;awaitQueuedTask.Run(()=>StyleHelper.AddStyle(project,stylePath));StyleProjectItemstyleToUpgrade=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//returns true if style can be upgradedboolcanUpgrade=styleToUpgrade.CanUpgrade;
How to determine if a style is read-only
//Add the style to the current projectstringstylePath=@"C:\MyStyles\MyStyle.stylx";varproject=Project.Current;awaitQueuedTask.Run(()=>StyleHelper.AddStyle(project,stylePath));StyleProjectItemstyleToCheck=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//returns true if style is read-onlyboolisReadOnly=styleToCheck.IsReadOnly;
How to determine if a style is current
//Add the style to the current projectstringstylePath=@"C:\MyStyles\MyStyle.stylx";varproject=Project.Current;awaitQueuedTask.Run(()=>StyleHelper.AddStyle(project,stylePath));StyleProjectItemstyleToCheck=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//returns true if style matches the current Pro versionboolisCurrent=styleToCheck.IsCurrent;
How to upgrade a style
boolsuccess=false;//Add the style to the current projectstringstylePath=@"C:\MyStyles\OldStyle.stylx";varproject=Project.Current;awaitQueuedTask.Run(()=>StyleHelper.AddStyle(project,stylePath));StyleProjectItemstyleToUpgrade=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//Verify that style can be upgradedif(styleToUpgrade.CanUpgrade){success=awaitQueuedTask.Run(()=>StyleHelper.UpgradeStyle(styleToUpgrade));}
Symbols
How to construct a point symbol of a specific color and size
How to construct a point symbol from a file on disk
//The following file formats can be used to create the marker: DAE, 3DS, FLT, EMF, JPG, PNG, BMP, GIFawaitQueuedTask.Run(()=>{CIMMarkermarkerFromFile=SymbolFactory.Instance.ConstructMarkerFromFile(@"C:\Temp\fileName.dae");CIMPointSymbolpointSymbolFromFile=SymbolFactory.Instance.ConstructPointSymbol(markerFromFile);});
How to construct a point symbol from a in memory graphic
//Create a stream for the image//At 3.0 you need https://www.nuget.org/packages/Microsoft.Windows.Compatibility//System.DrawingSystem.Drawing.ImagenewImage=System.Drawing.Image.FromFile(@"C:\PathToImage\Image.png");varstream=newSystem.IO.MemoryStream();newImage.Save(stream,System.Drawing.Imaging.ImageFormat.Png);stream.Position=0;//Create marker using the streamCIMMarkermarkerFromStream=SymbolFactory.Instance.ConstructMarkerFromStream(stream);//Create the point symbol from the markerCIMPointSymbolpointSymbolFromStream=SymbolFactory.Instance.ConstructPointSymbol(markerFromStream);
How to construct a polygon symbol of specific color and fill style
How to construct a multilayer line symbol with an arrow head on the end
varmarkerTriangle=SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB,12,SimpleMarkerStyle.Triangle);markerTriangle.Rotation=-90;// or -90markerTriangle.MarkerPlacement=newCIMMarkerPlacementOnLine(){AngleToLine=true,RelativeTo=PlacementOnLineRelativeTo.LineEnd};varlineSymbolWithArrow=newCIMLineSymbol(){SymbolLayers=newCIMSymbolLayer[2]{markerTriangle,SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB,2)}};
How to get symbol reference from a symbol
CIMPolygonSymbolpolySymbol=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB);//Get symbol reference from the symbolCIMSymbolReferencesymbolReference=polySymbol.MakeSymbolReference();
Modify a point symbol created from a character marker
//create marker from the Font, char index,size,colorawaitQueuedTask.Run(()=>{varcimMarker=SymbolFactory.Instance.ConstructMarker(125,"Wingdings 3","Regular",6,ColorFactory.Instance.BlueRGB)asCIMCharacterMarker;varpolygonMarker=cimMarker.Symbol;//modifying the polygon's outline and fill//This is the outlinepolygonMarker.SymbolLayers[0]=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB,2,SimpleLineStyle.Solid);//This is the fillpolygonMarker.SymbolLayers[1]=SymbolFactory.Instance.ConstructSolidFill(ColorFactory.Instance.BlueRGB);//create a symbol from the marker//Note this overload of ConstructPointSymbol does not need to be run within QueuedTask.Run.varpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(cimMarker);});
Get a List of Available Fonts
//returns a tuple per font: (string fontName, List<string> fontStyles)varfonts=SymbolFactory.Instance.GetAvailableFonts();foreach(varfontinfonts){varstyles=string.Join(",",font.fontStyles);System.Diagnostics.Debug.WriteLine($"{font.fontName}, styles: {styles}");}
Get/Set Default Font
vardef_font=SymbolFactory.Instance.DefaultFont;System.Diagnostics.Debug.WriteLine($"{def_font.fontName}, styles: {def_font.styleName}");//set default font - set through application optionsawaitQueuedTask.Run(()=>{ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultFont("tahoma");ApplicationOptions.TextAndGraphicsElementsOptions.SetDefaultFont("tahoma","bold");});
Construct a Text Symbol With Options
awaitQueuedTask.Run(()=>{//using the default fontvartextSym1=SymbolFactory.Instance.ConstructTextSymbol();vartextSym2=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB,14);//using a specific fontvartextSym3=SymbolFactory.Instance.ConstructTextSymbol("Arial");vartextSym4=SymbolFactory.Instance.ConstructTextSymbol("Arial","Narrow Bold");//or query available fonts to ensure the font is therevarall_fonts=SymbolFactory.Instance.GetAvailableFonts();varfont=all_fonts.FirstOrDefault(f =>f.fontName=="Arial");if(!string.IsNullOrEmpty(font.fontName)){vartextSym5=SymbolFactory.Instance.ConstructTextSymbol(font.fontName);//or with a font+stylevartextSym6=SymbolFactory.Instance.ConstructTextSymbol(font.fontName,font.fontStyles.First());}//overloads - font + color and size, etcvartextSym7=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlueRGB,14,"Times New Roman","Italic");//custom symbol - black stroke, red fillvarpoly_symbol=SymbolFactory.Instance.ConstructPolygonSymbol(SymbolFactory.Instance.ConstructSolidFill(ColorFactory.Instance.RedRGB),SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,1));vartextSym8=SymbolFactory.Instance.ConstructTextSymbol(poly_symbol,14,"Georgia","Bold");});
Create a Swatch for a given symbol
awaitQueuedTask.Run(()=>{CIMSymbolsymbolForSwatch=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,1.0,SimpleMarkerStyle.Circle);//You can generate a swatch for a text symbols also.varsi=newSymbolStyleItem(){Symbol=symbolForSwatch,PatchHeight=64,PatchWidth=64};});
Convert Point Symbol to SVG
varmem_strm=awaitQueuedTask.Run(()=>{//Create a point symbolvarpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,24,SimpleMarkerStyle.RoundedSquare);//Generate image returns a streamreturnSymbolFactory.Instance.GenerateImage(pointSymbol,OutputImageFormat.SVG,2.0,true,300,100,100,ColorFactory.Instance.WhiteRGB);});//Set the memory stream position to the beginningmem_strm.Seek(0,SeekOrigin.Begin);//File path and name for saving the SVG filevarfileName="RoundedSquareSymbol.svg";stringpath_svg=System.IO.Path.Combine(System.IO.Path.GetTempPath()+fileName);//Write the memory stream to the fileSystem.IO.File.WriteAllBytes(path_svg,mem_strm.ToArray());////////////////////////////////////////////////Note: to convert SVG to image format, use a 3rd party//e.g. Aspose.SVG for .NET, for example convert SVG to PNG//using (var svg_doc = new Aspose.Svg.SVGDocument(path_svg))//{// string path_png = Path.Combine(Path.GetTempPath() + "RoundedSquareSymbol.png");// using (var img_png = new Aspose.Svg.Rendering.Image.ImageDevice(// new ImageRenderingOptions(ImageFormat.Png), path_png))// {// svg_doc.RenderTo(img_png);// }// //also: https://docs.aspose.com/imaging/net/convert-svg-to-png///}
Convert Point Symbol to PNG
varmem_strm=awaitQueuedTask.Run(()=>{//Create a point symbolvarpointSymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,24,SimpleMarkerStyle.RoundedSquare);//Generate image returns a streamreturnSymbolFactory.Instance.GenerateImage(pointSymbol,OutputImageFormat.PNG,2.0,true,300,100,100,ColorFactory.Instance.WhiteRGB);});//Set the memory stream position to the beginningmem_strm.Seek(0,SeekOrigin.Begin);//Write the stream to a bit mapvarbitmapImage=newSystem.Windows.Media.Imaging.BitmapImage();bitmapImage.BeginInit();bitmapImage.StreamSource=mem_strm;bitmapImage.CacheOption=System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;bitmapImage.EndInit();bitmapImage.Freeze();//Write the bit map out to a file//File path and name for saving the PNG filevarfileName="RoundedSquareSymbol.png";stringpath_png=System.IO.Path.Combine(System.IO.Path.GetTempPath()+fileName);BitmapEncoderencoder=newPngBitmapEncoder();encoder.Frames.Add(BitmapFrame.Create(bitmapImage));using(varfileStream=newSystem.IO.FileStream(path_png,System.IO.FileMode.Create)){encoder.Save(fileStream);}
Lookup Symbol
//feature layer from the active mapvarlookupMapView=MapView.Active;varfeatureLayerLookUp=lookupMapView.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();awaitQueuedTask.Run(()=>{//Get the selectionvarselection=featureLayerLookUp.GetSelection();//Get the first Object IDvarfirstOID=selection.GetObjectIDs().FirstOrDefault();//Determine whether the layer's renderer type supports symbol lookup.if(featureLayerLookUp.CanLookupSymbol()){//Looks up the symbol for the corresponding feature identified by the object id.varlookupSymbol=featureLayerLookUp.LookupSymbol(firstOID,lookupMapView);varjSon=lookupSymbol.ToJson();//Create a JSON encoding of the symbol//Do something with symbol}});
Symbol Search
How to search for a specific item in a style
//Search for a specific point symbol in style//Note: styleProjectItem was created above in the variable initialization sectionstringkey="Circle 1_Shapes_3";SymbolStyleItemitem=awaitQueuedTask.Run(()=>(SymbolStyleItem)styleProjectItem.LookupItem(StyleItemType.PointSymbol,key));
How to search for point symbols in a style
//Search for point symbols//Note: styleProjectItem was created above in the variable initialization section//Search for point symbolsawaitQueuedTask.Run(()=>styleProjectItem.SearchSymbols(StyleItemType.PointSymbol,"searchString"));
How to search for line symbols in a style
//Note: styleProjectItem was created above in the variable initialization section//Search for line symbolsawaitQueuedTask.Run(()=>styleProjectItem.SearchSymbols(StyleItemType.LineSymbol,"searchString"));
How to search for polygon symbols in a style
//Note: styleProjectItem was created above in the variable initialization section//Search for polygon symbolsawaitQueuedTask.Run(()=>styleProjectItem.SearchSymbols(StyleItemType.PolygonSymbol,"searchString"));
How to search for colors in a style
//Search for colors//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchColors("searchString"));
How to search for color ramps in a style
//StyleProjectItem can be "ColorBrewer Schemes (RGB)", "ArcGIS 2D"...//Search for color ramps//Color Ramp searchString can be "Spectral (7 Classes)", "Pastel 1 (3 Classes)", "Red-Gray (10 Classes)"..styleProjectItem.SearchColorRamps("searchString");
How to search for north arrows in a style
//Search for north arrows//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchNorthArrows("searchString"));
How to search for scale bars in a style
//Search for scale bars//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchScaleBars("searchString"));
How to search for label placements in a style
//Search for label placements//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchLabelPlacements(StyleItemType.StandardLabelPlacement,"searchString"));
How to search for legends in a style
//Search for legends//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchLegends("searchString"));
How to search for legend items in a style
//Search for legend items//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchLegendItems("searchString"));
How to search for grids in a style
//Search for grids//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchGrids("searchString"));
How to search for map surrounds in a style
//Search for map surrounds//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchMapSurrounds("searchString"));
How to search for table frames in a style
//Search for table frames//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchTableFrames("searchString"));
How to search for table frame fields in a style
//Search for table frame fields//Note: styleProjectItem was created above in the variable initialization sectionawaitQueuedTask.Run(()=>styleProjectItem.SearchTableFrameFields("searchString"));
Feature Layer Symbology
How to set symbol for a feature layer symbolized with simple renderer
awaitQueuedTask.Run(()=>{//Get simple renderer from the feature layerCIMSimpleRenderercurrentRenderer=featureLayer.GetRenderer()asCIMSimpleRenderer;if(currentRenderer==null){return;}//Set symbol's real world setting to be the same as that of the feature layersymbol.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);//Update the symbol of the current simple renderercurrentRenderer.Symbol=symbol.MakeSymbolReference();//Update the feature layer rendererfeatureLayer.SetRenderer(currentRenderer);});
How to apply a symbol from style to a feature layer
awaitQueuedTask.Run(()=>{//Get simple renderer from the feature layerCIMSimpleRenderercurrentRenderer=featureLayer.GetRenderer()asCIMSimpleRenderer;if(currentRenderer==null){return;}//Get symbol from the SymbolStyleItemCIMSymbolsymbolToApply=symbolStyleItem.Symbol;//Set symbol's real world setting to be the same as that of the feature layersymbolToApply.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);//Update the symbol of the current simple renderercurrentRenderer.Symbol=symbolToApply.MakeSymbolReference();//Update the feature layer rendererfeatureLayer.SetRenderer(currentRenderer);});
How to apply a point symbol from a style to a feature layer
//Get the ArcGIS 2D System style from the ProjectvararcGIS2DStyle=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s =>s.Name=="ArcGIS 2D");awaitQueuedTask.Run(()=>{//Search for the symbolName style items within the ArcGIS 2D style project item.varitems=arcGIS2DStyle.SearchSymbols(StyleItemType.PointSymbol,"Circle 1");//Gets the CIMSymbolCIMSymbolsymbolToUse=items.FirstOrDefault().Symbol;//Get the renderer of the point feature layerCIMSimpleRendererrenderer=featureLayer.GetRenderer()asCIMSimpleRenderer;//Set symbol's real world setting to be the same as that of the feature layersymbolToUse.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);//Apply the symbol to the feature layer's current rendererrenderer.Symbol=symbolToUse.MakeSymbolReference();//Apply the renderer to the feature layerfeatureLayer.SetRenderer(renderer);});
How to apply a color ramp from a style to a feature layer
//Finding the first project item with name matches with mapNameMapProjectItem?mpi=Project.Current.GetItems<MapProjectItem>().FirstOrDefault(m =>m.Name.Equals("The Map",StringComparison.CurrentCultureIgnoreCase));varmapFromItem=awaitQueuedTask.Run(()=>mpi?.GetMap());if(mapFromItem!=null){//Open the map in a new map pane//Must be called from the UI threadawaitProApp.Panes.CreateMapPaneAsync(map);}
Open a webmap
//Assume we get the selected webmap from the Project pane's Portal tabif(Project.Current.SelectedItems.Count>0){if(MapFactory.Instance.CanCreateMapFrom(Project.Current.SelectedItems[0])){map=MapFactory.Instance.CreateMapFromItem(Project.Current.SelectedItems[0]);awaitProApp.Panes.CreateMapPaneAsync(map);}}
//Gets the unique list of Maps from all the MapPanes.//Note: The list of maps retrieved from the MapPanes//maybe less than the total number of Maps in the project.//It depends on what maps the user has actually opened.varmapPanes=ProApp.Panes.OfType<IMapPane>().GroupBy((mp)=>mp.MapView.Map.URI).Select(grp =>grp.FirstOrDefault());List<Map>uniqueMaps=newList<Map>();foreach(varpaneinmapPanes){uniqueMaps.Add(pane.MapView.Map);}
Change the Map name and caption of the active pane
//Basemaps stored locally in the project. This is usually an empty collectionstringlocalBasemapTypeID="cim_map_basemap";varproject=Project.Current;awaitQueuedTask.Run(()=>{varmapContainer=project.GetProjectItemContainer("Map");mapContainer.GetItems().Where(i =>i.TypeID==localBasemapTypeID).ToList();});//portal basemaps. If there is no current active portal, the usual default//is arcgis onlinevarportal=ArcGISPortalManager.Current.GetActivePortal();varportalBaseMaps=awaitportal.GetBasemapsAsync();//use one of them...local or portal...//var map = MapView.Active.Map;//QueuedTask.Run(() => map?.SetBasemapLayers(portalBaseMaps[0]));
Save Map as MapX
map.SaveAsFile(@"C:\Data\MyMap.mapx",true);
Save 2D Map as WebMap on Disk
//2D maps onlyawaitQueuedTask.Run(()=>{if(map.DefaultViewingMode==MapViewingMode.Map){//Only webmap compatible layers will be saved out to the filemap.SaveAsWebMapFile(@"C:\Data\MyMap.json");}});
Clip Map to the provided clip polygon
varmapToClip=MapView.Active.Map;awaitQueuedTask.Run(()=>{//A layer to use for the clip extentvarlyrOfInterest=mapToClip.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l =>l.Name=="TestPoly").FirstOrDefault();//Get the polygon to use to clip the mapvarextent=lyrOfInterest.QueryExtent();varpolygonForClipping=PolygonBuilderEx.CreatePolygon(extent);//Clip the map using the layer's extentmapToClip.SetClipGeometry(polygonForClipping,SymbolFactory.Instance.ConstructLineSymbol(SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB,2.0,SimpleLineStyle.Dash)));});
Clear the current map clip geometry
varmapWithClip=MapView.Active.Map;//Clear the Map clip.//If no clipping is set then this is a no-op.mapWithClip.ClearClipGeometry();
Get the map clipping geometry
varmapWithClip=MapView.Active.Map;awaitQueuedTask.Run(()=>{//If clipping is set to ArcGIS.Core.CIM.ClippingMode.None or ArcGIS.Core.CIM.ClippingMode.MapSeries null is returned//If clipping is set to ArcGIS.Core.CIM.ClippingMode.MapExtent the ArcGIS.Core.CIM.CIMMap.CustomFullExtent is returned.//Otherwise, if clipping is set to ArcGIS.Core.CIM.ClippingMode.CustomShape the custom clip polygon is returned.varpoly=mapWithClip.GetClipGeometry();//You can use the polygon returned//For example: We make a polygon graphic element and add it to a Graphics Layer.vargl=mapWithClip.GetLayersAsFlattenedList().OfType<GraphicsLayer>().FirstOrDefault();if(gl==null){return;}varpolygonSymbol=SymbolFactory.Instance.ConstructPolygonSymbol(CIMColor.CreateRGBColor(255,255,0));varcimGraphicElement=newCIMPolygonGraphic{Polygon=poly,Symbol=polygonSymbol.MakeSymbolReference()};gl.AddElement(cimGraphicElement);});
Get the Current Map Location Unit
//var map = MapView.Active.Map;awaitQueuedTask.Run(()=>{//Get the current location unitvarloc_unit=map.GetLocationUnitFormat();varline=$"{loc_unit.DisplayName}, {loc_unit.UnitCode}";System.Diagnostics.Debug.WriteLine(line);});
Get the Available List of Map Location Units
//Linear location unit formats are not included if the map sr//is geographic.varloc_units=awaitQueuedTask.Run(()=>map.GetAvailableLocationUnitFormats());
Format a Location Using the Current Map Location Unit
//Get the current view camera locationvarcenter_pt=newCoordinate2D(mapView.Camera.X,mapView.Camera.Y);//Get the current location unitvarloc_unit=awaitQueuedTask.Run(()=>map.GetLocationUnitFormat());//Format the camera locationvarstr=loc_unit.FormatLocation(center_pt,map.SpatialReference);System.Diagnostics.Debug.WriteLine($"Formatted location: {str}");
Set the Location Unit for the Current Map
//Get the list of available location unit formats//for the current mapawaitQueuedTask.Run(()=>{varloc_units=map.GetAvailableLocationUnitFormats();//arbitrarily use the last unit in the listmap.SetLocationUnitFormat(loc_units.Last());});
//If the map is not a scene, the list of current//Project distance units will be returnedvarelev_units=awaitQueuedTask.Run(()=>map.GetAvailableElevationUnitFormats());
Format an Elevation Using the Current Map Elevation Unit
//Get the current elevation unit. If the map is not//a scene the default Project distance unit is returnedvarelev_unit=awaitQueuedTask.Run(()=>map.GetElevationUnitFormat());//Format the view camera elevationvarstr=elev_unit.FormatValue(mapView.Camera.Z);System.Diagnostics.Debug.WriteLine($"Formatted elevation: {str}");
Set the Elevation Unit for the Current Map
//Trying to set the elevation unit on a map other than//a scene will throw an InvalidOperationExceptionawaitQueuedTask.Run(()=>{if(map.IsScene){//Get the list of available elevation unit formats//for the current mapvarloc_units=map.GetAvailableElevationUnitFormats();//arbitrarily use the last unit in the listmap.SetElevationUnitFormat(loc_units.Last());}});
vargridOptionsMapView=MapView.Active;if(gridOptionsMapView==null)return;awaitQueuedTask.Run(()=>{//Does the 'map' currently have any options?varhasOptions=GridOptionsEnvironment.Instance.HasGridOptions(map);//If grid options have not been set for the map, then default grid options are added//for the map otherwise the existing gridoptions are returned.//NOTE: Grid options are returned by value meaning a copy is always returned. Any changes made to the//grid options need to be -set- back on the map using SetGridOptions for the changes to persist.vargridOptions=GridOptionsEnvironment.Instance.GetGridOptions(gridOptionsMapView.Map);//Only return grid options if grid options have previously been set:vargridOptions2=GridOptionsEnvironment.Instance.GetGridOptions(gridOptionsMapView.Map,false);});
Get and Set Grid Options for a Map
//assume//var map = MapView.Active.Map;awaitQueuedTask.Run(()=>{//If grid options have not been set for the map, then default grid options are added//for the map and returned otherwise the existing gridoptions are returned.//NOTE: Grid options are by value meaning a copy is returned. Any changes made to the//grid options need to be -set- back on the map using SetGridOptions for the changes to persist.vargridOptions=GridOptionsEnvironment.Instance.GetGridOptions(map);//change some propertiesgridOptions.RotateWithMap=!gridOptions.RotateWithMap;gridOptions.GridLineColor=ColorFactory.Instance.RedRGB;gridOptions.GridLineColor=ColorFactory.Instance.BlueRGB;//To apply changes, the gridoptions must be set back on the mapGridOptionsEnvironment.Instance.SetGridOptions(map,gridOptions);});
Set Grid Origin for Grid Options for a Map
//assume//var map = MapView.Active.Map;varcenter_pt=mapView.Extent.Center;varwidth=mapView.Extent.Width;varheight=mapView.Extent.Height;varqtr_width=width*0.25;varqtr_ht=height*0.25;awaitQueuedTask.Run(()=>{//If grid options have not been set for the map, then default grid options are added//for the map and returned otherwise the existing gridoptions are returned.//NOTE: Grid options are by value meaning a copy is returned. Any changes made to the//grid options need to be -set- back on the map using SetGridOptions for the changes to persist.vargridOptions=GridOptionsEnvironment.Instance.GetGridOptions(map);//Set the grid originvarx1=center_pt.X+qtr_width;vary1=center_pt.Y+qtr_ht;gridOptions.SetGridOrigin(newCoordinate2D(x1,y1));//or use Coordinate3DgridOptions.SetGridOrigin(newCoordinate3D(x1,y1,0));//To apply changes, the gridoptions must be set back on the mapGridOptionsEnvironment.Instance.SetGridOptions(map,gridOptions);});
Set Various Grid Option parameters for GridOptions for a Map
varcenter_pt=mapView.Extent.Center;varwidth=mapView.Extent.Width;varheight=mapView.Extent.Height;varqtr_width=width*0.25;varqtr_ht=height*0.25;awaitQueuedTask.Run(()=>{//use defaultsvargridOptions=GridOptionsEnvironment.Instance.DefaultGridOptions;//customize the options as neededgridOptions.RotateWithMap=!gridOptions.RotateWithMap;gridOptions.GridLineColor=ColorFactory.Instance.RedRGB;vargs_rotation=gridOptions.GetGridRotation();gridOptions.SetGridRotation(gs_rotation*1.5);vargs_meters=gridOptions.GetGridSpacingMeters();vargs_in_spacing_units=gridOptions.GetGridSpacing();vargs_units=gridOptions.GridSpacingUnits;//meters assumedgridOptions.SetGridSpacingInMeters(gs_meters+10);//specify units explicitlygridOptions.SetGridSpacing(1000,LinearUnit.Feet);//internally will be converted to metersgridOptions.IsGridLines=true;//use lines (default)vargrid_interval=gridOptions.GridMajorInterval;gridOptions.SnapToGridEnabled=true;varx1=center_pt.X-qtr_width;vary1=center_pt.Y+qtr_ht;gridOptions.SetGridOrigin(newCoordinate2D(x1,y1));//To apply changes, the gridoptions must be set back on the mapGridOptionsEnvironment.Instance.SetGridOptions(map,gridOptions);});
Reset the Grid Options for a Map back to Defaults
awaitQueuedTask.Run(()=>{if(GridOptionsEnvironment.Instance.HasGridOptions(map)){//set back to defaults - will overwrite existingGridOptionsEnvironment.Instance.SetGridOptions(map,GridOptionsEnvironment.Instance.DefaultGridOptions);}});
varhasSyncEnabledContent=GenerateOfflineMap.Instance.GetCanGenerateReplicas(map);if(hasSyncEnabledContent){//TODO - use status...}
Generate Replicas for Sync-Enabled Content
//namespace ArcGIS.Desktop.Mapping.Offlinevarextent=mapView.Extent;awaitQueuedTask.Run(()=>{//Check map has sync-enabled content that can be taken offlinevarhasSyncEnabledContent=GenerateOfflineMap.Instance.GetCanGenerateReplicas(map);if(hasSyncEnabledContent){//Generate Replicas and take the content offline//sync-enabled content gets copied local into a SQLite DBvargen_params=newGenerateReplicaParams(){Extent=extent,//SR of extent must match map SR//DestinationFolder can be left blank, if specified,//it must exist. Defaults to project offline maps locationDestinationFolder=@"C:\Data\Offline"};//Sync-enabled layer content will be resourced to point to the//local replica content.GenerateOfflineMap.Instance.GenerateReplicas(map,gen_params);}});
Check Map Has Local Syncable Content
//Check map has local syncable contentvarcanSyncContent=awaitQueuedTask.Run(()=>GenerateOfflineMap.Instance.GetCanSynchronizeReplicas(map));if(canSyncContent){//TODO - use status}
Synchronize Replicas for Syncable Content
awaitQueuedTask.Run(()=>{//Check map has local syncable contentvarcanSyncContent=GenerateOfflineMap.Instance.GetCanSynchronizeReplicas(map);if(canSyncContent){//Sync Replicas - changes since last sync are pushed to the//parent replica. Parent changes are pulled to the client.//Unsaved edits are _not_ sync'd.GenerateOfflineMap.Instance.SynchronizeReplicas(map);}});
Remove Replicas for Syncable Content
awaitQueuedTask.Run(()=>{//Check map has local syncable content//Either..//var canSyncContent = GenerateOfflineMap.Instance.GetCanSynchronizeReplicas(map);//Or...both accomplish the same thing...varcanRemove=GenerateOfflineMap.Instance.GetCanRemoveReplicas(map);if(canRemove){//Remove Replicas - any unsync'd changes are lost//Call sync _first_ to push any outstanding changes if//needed. Local syncable content is re-sourced//to point to the serviceGenerateOfflineMap.Instance.RemoveReplicas(map);}});
Export Map Raster Tile Cache Content
//Does the map have any exportable raster content?varcanExport=GenerateOfflineMap.Instance.GetCanExportRasterTileCache(map);varrasterTileExtent=MapView.Active.Extent;if(canExport){//Check the available LOD scale rangesvarscales=GenerateOfflineMap.Instance.GetExportRasterTileCacheScales(map,rasterTileExtent);//Pick the desired LOD scalevarmax_scale=scales[scales.Count()/2];//Configure the export parametersvarexport_params=newExportTileCacheParams(){Extent=rasterTileExtent,//Use same extent as was used to retrieve scalesMaximumUserDefinedScale=max_scale//DestinationFolder = .... (optional)};//If DestinationFolder is not set, output defaults to project//offline maps location set in the project properties. If that is//not set, output defaults to the current project folder location.//Do the export. Depending on the MaximumUserDefinedScale and the//area of the extent requested, this can take minutes for tile packages//over 1 GB or less if your network speed is slow...GenerateOfflineMap.Instance.ExportRasterTileCache(map,export_params);}
Export Map Vector Tile Cache Content
varmapVectorTileExtent=MapView.Active.Extent;//Does the map have any exportable vector tile content?varcanExport=GenerateOfflineMap.Instance.GetCanExportVectorTileCache(map);if(canExport){//Check the available LOD scale rangesvarscales=GenerateOfflineMap.Instance.GetExportVectorTileCacheScales(map,mapVectorTileExtent);//Pick the desired LOD scalevarmax_scale=scales[scales.Count()/2];//Configure the export parametersvarexport_params=newExportTileCacheParams(){Extent=mapVectorTileExtent,//Use same extent as was used to retrieve scalesMaximumUserDefinedScale=max_scale,DestinationFolder=@"C:\Data\Offline"};//If DestinationFolder is not set, output defaults to project//offline maps location set in the project properties. If that is//not set, output defaults to the current project folder location.//Do the export. Depending on the MaximumUserDefinedScale and the//area of the extent requested, this can take minutes for tile packages//over 1 GB or less if your network speed is slow...GenerateOfflineMap.Instance.ExportVectorTileCache(map,export_params);}
Create Layer
Create and add a layer to the active map
//* string url = @"c:\data\project.gdb\DEM"; //Raster dataset from a FileGeodatabase//* string url = @"c:\connections\mySDEConnection.sde\roads"; //FeatureClass of a SDE//* string url = @"c:\connections\mySDEConnection.sde\States\roads"; //FeatureClass within a FeatureDataset from a SDE//* string url = @"c:\data\roads.shp"; //Shapefile//* string url = @"c:\data\imagery.tif"; //Image from a folder//* string url = @"c:\data\mySDEConnection.sde\roads"; //.lyrx or .lpkx file//* string url = @"c:\data\CAD\Charlottesville\N1W1.dwg\Polyline"; //FeatureClass in a CAD dwg file//* string url = @"C:\data\CAD\UrbanHouse.rvt\Architectural\Windows"; //Features in a Revit file//* string url = @"http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer"; //map service//* string url = @"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0"; //FeatureLayer off a map service or feature servicestringurlRoads=@"c:\data\project.gdb\roads";//FeatureClass of a FileGeodatabaseUriuri=newUri(urlRoads);varnewLayer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer(uri,map));
Create layer with create-params
varflyrCreatnParam=newFeatureLayerCreationParams(newUri(@"c:\data\world.gdb\cities")){Name="World Cities",IsVisible=false,MinimumScale=1000000,MaximumScale=5000,DefinitionQuery=newDefinitionQuery(whereClause:"Population > 100000",name:"More than 100k"),RendererDefinition=newSimpleRendererDefinition(){SymbolTemplate=SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(255,0,0),8,SimpleMarkerStyle.Hexagon).MakeSymbolReference()}};varfeatureLayerWithParams=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(flyrCreatnParam,map));
Create FeatureLayer and add to Map using LayerCreationParams
//Get the LayerDocument from a lyrx filevarlayerDoc=newLayerDocument(@"E:\Data\SDK\Default2DPointSymbols.lyrx");//Get the CIMLayerDocument from the LayerDocument and use it to create LayerCreationParamsvarcreateParams=newLayerCreationParams(layerDoc.GetCIMLayerDocument());//Create a FeatureLayer using the LayerCreationParamsawaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(createParams,map));
Create FeatureLayer and set to not display in Map.
//The catalog path of the feature layer to add to the mapvarfeatureClassUriVisibility=newUri(@"C:\Data\Admin\AdminData.gdb\USA\cities");//Define the Feature Layer's parameters.varlayerParamsVisibility=newFeatureLayerCreationParams(featureClassUriVisibility){//Set visibilityIsVisible=false,};//Create the layer with the feature layer parameters and add it to the active mapvarcreatedFC=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParamsVisibility,map));
Create FeatureLayer with a Renderer
//Define a simple renderer to draw the Point US Cities feature class.varsimpleRender=newSimpleRendererDefinition{SymbolTemplate=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,4.0,SimpleMarkerStyle.Circle).MakeSymbolReference()};//The catalog path of the feature layer to add to the mapvarfeatureClassUri=newUri(@"C:\Data\Admin\AdminData.gdb\USA\cities");//Define the Feature Layer's parameters.varlayerParams=newFeatureLayerCreationParams(featureClassUri){//Set visibilityIsVisible=true,//Set RendererRendererDefinition=simpleRender,};//Create the layer with the feature layer parameters and add it to the active mapvarcreatedFCWithRenderer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams,map));
Create FeatureLayer with a Query Definition
//The catalog path of the feature layer to add to the mapvarfeatureClassUriDefinition=newUri(@"C:\Data\Admin\AdminData.gdb\USA\cities");//Define the Feature Layer's parameters.varlayerParamsQueryDefn=newFeatureLayerCreationParams(featureClassUriDefinition){IsVisible=true,DefinitionQuery=newDefinitionQuery(whereClause:"STATE_NAME = 'California'",name:"CACities")};//Create the layer with the feature layer parameters and add it to the active mapvarcreatedFCWithQueryDefn=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParamsQueryDefn,map));
Create multiple layers
//Define a list of dataset URIs for the layers to be createdvaruriShp=newUri(@"c:\data\roads.shp");varuriSde=newUri(@"c:\MyDataConnections\MySDE.sde\Census");varuri=newUri(@"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0");// Create a list of URIs to be used for creating multiple layersvaruris=newList<Uri>(){uriShp,uriSde,uri};// Create multiple layers using the LayerFactoryvarlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(uris,map));
Create multiple layers with BulkLayerCreationParams 1
//Uris to the datasets for the layers to be createdvaruriShp=newUri(@"c:\data\roads.shp");varuriSde=newUri(@"c:\MyDataConnections\MySDE.sde\Census");varuri=newUri(@"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0");// Create a list of URIs to be used for creating multiple layersvaruris=newList<Uri>(){uriShp,uriSde,uri};;// set the index and visibilityvarblkParams=newBulkLayerCreationParams(uris);blkParams.MapMemberPosition=MapMemberPosition.Index;blkParams.MapMemberIndex=2;blkParams.IsVisible=false;// blkParams.AutoGroup = true; AutoGroup is set to true by default// Create multiple layers using the BulkLayerCreationParamsvarlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(blkParams,map));
Create multiple layers with BulkLayerCreationParams 1 - No AutoGroup
// same example as "Create multiple layers with BulkLayerCreationParams 1" but without// adding layers in a group layer//Uris to the datasets for the layers to be createdvaruriShp=newUri(@"c:\data\roads.shp");varuriSde=newUri(@"c:\MyDataConnections\MySDE.sde\Census");varuri=newUri(@"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0");// Create a list of URIs to be used for creating multiple layersvaruris=newList<Uri>(){uriShp,uriSde,uri};;// set the index and visibilityvarblkParams=newBulkLayerCreationParams(uris);blkParams.MapMemberPosition=MapMemberPosition.Index;blkParams.MapMemberIndex=2;blkParams.IsVisible=false;blkParams.AutoGroup=false;// Create multiple layers using the BulkLayerCreationParamsvarlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(blkParams,map));
Create multiple layers with BulkLayerCreationParams 2 - invalid
// get a feature class that is selected in the catalog paneItemitem=Project.GetCatalogPane().SelectedItems.FirstOrDefault();varuriShp=newUri(@"c:\data\roads.shp");varlcpShp=newFeatureLayerCreationParams(uriShp);lcpShp.Name="Roads";lcpShp.IsVisible=false;lcpShp.DefinitionQuery=newDefinitionQuery("shpQuery","OBJECTID > 10");varlcpItem=newFeatureLayerCreationParams(item);lcpItem.Name="Census Polygons";lcpItem.IsVisible=true;// list contains a Uri data source and an Item data source// LayerFactory.Instance.CreateLayers will throw an ArgumentExceptionvarlcps=newList<FeatureLayerCreationParams>();lcps.Add(lcpShp);lcps.Add(lcpItem);varblkParams=newBulkLayerCreationParams(lcps);// LayerFactory.Instance.CreateLayers will thrown an ArgumentException// because the LayerCreationParams are created using different// types of data sources (1 Uri and 1 Item)varlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(blkParams,map));
Create multiple layers with BulkLayerCreationParams 2 - Valid
varuriShp=newUri(@"c:\data\roads.shp");varuriSde=newUri(@"c:\MyDataConnections\MySDE.sde\Census");varuri=newUri(@"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0");varlcpShp=newFeatureLayerCreationParams(uriShp);lcpShp.Name="Roads";lcpShp.IsVisible=false;lcpShp.DefinitionQuery=newDefinitionQuery("shpQuery","OBJECTID > 10");varlcpSde=newFeatureLayerCreationParams(uriSde);lcpSde.Name="Census Polygons";lcpSde.IsVisible=true;varlcpService=newFeatureLayerCreationParams(uri);lcpService.Name="Shelters";lcpService.IsVisible=true;// set some renderer here ...//lcpService.RendererDefinition = ...varlcps=newList<FeatureLayerCreationParams>();lcps.Add(lcpShp);lcps.Add(lcpSde);lcps.Add(lcpService);varblkParams=newBulkLayerCreationParams(lcps);// set the positioning on the BulkLayerCreationParamsblkParams.MapMemberPosition=MapMemberPosition.Index;blkParams.MapMemberIndex=0;varlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(blkParams,map));
Create multiple layers with BulkLayerCreationParams 3 - Valid
// illustrates using a collection of CIMLayerDocumentvarlayerFile1=@"c:\data\CitiesRivers.lyrx";varlayerfile2=@"c:\data\StatesWorld.lyrx";varlayerDoc1=newLayerDocument(layerFile1);varcimLayerDoc1=layerDoc1.GetCIMLayerDocument();varlayerDoc2=newLayerDocument(layerfile2);varcimLayerDoc2=layerDoc2.GetCIMLayerDocument();varcimLayerDocs=newList<CIMLayerDocument>(){cimLayerDoc1,cimLayerDoc2};varblkParams=newBulkLayerCreationParams(cimLayerDocs);blkParams.AutoGroup=true;// add the layersfiles within an encompassing group layervarlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(blkParams,map));
Create multiple layers with BulkLayerCreationParams - Using RollbackBehavior
varuriShp=newUri(@"c:\data\roads.shp");varuriSde=newUri(@"c:\MyDataConnections\MySDE.sde\Census");varuri=newUri(@"http://sampleserver6.arcgisonline.com/arcgis/rest/services/NapervilleShelters/FeatureServer/0");varlcpShp=newFeatureLayerCreationParams(uriShp);lcpShp.Name="Roads";lcpShp.IsVisible=false;lcpShp.DefinitionQuery=newDefinitionQuery("shpQuery","OBJECTID > 10");varlcpSde=newFeatureLayerCreationParams(uriSde);lcpSde.Name="Census Polygons";lcpSde.IsVisible=true;varlcpService=newFeatureLayerCreationParams(uri);lcpService.Name="Shelters";lcpService.IsVisible=true;// set some renderer here ...//lcpService.RendererDefinition = ...varlcps=newList<FeatureLayerCreationParams>();lcps.Add(lcpShp);lcps.Add(lcpSde);lcps.Add(lcpService);varblkParams=newBulkLayerCreationParams(lcps);// set the positioning on the BulkLayerCreationParamsblkParams.MapMemberPosition=MapMemberPosition.Index;blkParams.MapMemberIndex=0;// set the rollback behavior// - rollback if one or more layers cannot be created due to an invalid data sourceblkParams.RollbackBehavior=LayerCreationRollbackBehavior.RollbackOnMissingLayers;varlayers=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayers(blkParams,map));
Add a GeoPackage to the Map
stringpathToGeoPackage=@"C:\Data\Geopackage\flooding.gpkg";//Create lists to hold the URIs of the layers and tables in the geopackagevarlayerUris=newList<Uri>();vartableUris=newList<Uri>();awaitQueuedTask.Run(()=>{//Create an item from the geopackagevaritem=ItemFactory.Instance.Create(pathToGeoPackage,ItemFactory.ItemType.PathItem);varchildren=item.GetItems();//Collect the table and spatial data in the geopackageforeach(varchildinchildren){varchildPath=child.Path;if(child.TypeID=="sqlite_table"){tableUris.Add(newUri(childPath));}else{layerUris.Add(newUri(childPath));}}//Add the spatial data in the geopackage using the BulkLayerCreationParamsif(layerUris.Count>0){BulkLayerCreationParamsbulklcp=newBulkLayerCreationParams(layerUris);LayerFactory.Instance.CreateLayers(bulklcp,map);}// add the tables separatelyforeach(vartableUriintableUris){StandaloneTableFactory.Instance.CreateStandaloneTable(tableUri,map);}});
Create TopologyLayer with an Uri pointing to a Topology dataset
//Get the Topology of another Topology layervarexistingTopology=map.GetLayersAsFlattenedList().OfType<TopologyLayer>().FirstOrDefault();if(existingTopology!=null){awaitQueuedTask.Run(()=>{vartopology=existingTopology.GetTopology();//Configure the settings for a new Catalog layer using the CatalogDataset of an existing layervartopologyLyrParams=newTopologyLayerCreationParams(topology);topologyLyrParams.Name="NewTopologyLayerFromAnotherTopologyLayer";topologyLyrParams.AddAssociatedLayers=true;LayerFactory.Instance.CreateLayer<TopologyLayer>(topologyLyrParams,map);});}
Create Catalog Layer using Uri to a Catalog Feature Class
varcreateParams=newCatalogLayerCreationParams(newUri(@"C:\CatalogLayer\CatalogDS.gdb\HurricaneCatalogDS"));//Set the definition querycreateParams.DefinitionQuery=newDefinitionQuery("Query1","cd_itemname = 'PuertoRico'");//Set name of the new Catalog LayercreateParams.Name="PuertoRico";//Create LayervarcatalogLayer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<CatalogLayer>(createParams,map));
Create Catalog Layer using CatalogDataset
//Get the CatalogDataset of another Catalog layervarexistingCatalogLayer=map.GetLayersAsFlattenedList().OfType<CatalogLayer>().FirstOrDefault();if(existingCatalogLayer!=null){awaitQueuedTask.Run(()=>{varcatalogDataset=existingCatalogLayer.GetCatalogDataset();//Configure the settings for a new Catalog layer using the CatalogDataset of an existing layervarcatalogLyrParams=newCatalogLayerCreationParams(catalogDataset);catalogLyrParams.Name="NewCatalogLayerFromAnotherCatalogLayer";catalogLyrParams.DefinitionQuery=newDefinitionQuery("Query1","cd_itemname = 'Asia'");LayerFactory.Instance.CreateLayer<CatalogLayer>(catalogLyrParams,map);});}
Add MapNotes to the active map
//Gets the collection of layer template packages installed with Pro for use with mapsvaritems=map.LayerTemplatePackages;//Iterate through the collection of items to add each Map Note to the active mapforeach(variteminitems){//Create a parameter item for the map notevarlayer_params=newLayerCreationParams(item);layer_params.IsVisible=false;//Create a feature layer for the map notevarlayerCreated=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<Layer>(layer_params,map));}
Apply Symbology from a Layer in the TOC
awaitQueuedTask.Run(()=>{if(map==null){return;}//Get an existing Layer. This layer has a symbol you want to use in a new layer.varlyr=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l =>l.ShapeType==esriGeometryType.esriGeometryPoint).FirstOrDefault();//This is the renderer to use in the new Layervarrenderer=lyr.GetRenderer()asCIMSimpleRenderer;//Set the DataConnection for the new layerGeodatabasegeodatabase=newGeodatabase(newFileGeodatabaseConnectionPath(newUri(@"E:\Data\Admin\AdminData.gdb")));FeatureClassfeatureClass=geodatabase.OpenDataset<FeatureClass>("Cities");vardataConnection=featureClass.GetDataConnection();//Create the definition for the new feature layervarfeatureLayerParams=newFeatureLayerCreationParams(dataConnection){RendererDefinition=newSimpleRendererDefinition(renderer.Symbol),IsVisible=true,};//create the new layerLayerFactory.Instance.CreateLayer<FeatureLayer>(featureLayerParams,map);});
Create a new SubTypeGroupLayer
varsubtypeGroupLayerCreateParam=newSubtypeGroupLayerCreationParams(newUri(@"c:\data\SubtypeAndDomain.gdb\Fittings"));// Define Subtype layersvarrendererDefn1=newUniqueValueRendererDefinition(newList<string>{"type"});varrenderDefn2=newSimpleRendererDefinition(){SymbolTemplate=SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(255,0,0),8,SimpleMarkerStyle.Hexagon).MakeSymbolReference()};subtypeGroupLayerCreateParam.SubtypeLayers=newList<SubtypeFeatureLayerCreationParams>(){//define first subtype layer with unique value renderernewSubtypeFeatureLayerCreationParams(newUniqueValueRendererDefinition(newList<string>{"type"}),1),//define second subtype layer with simple symbol renderernewSubtypeFeatureLayerCreationParams(renderDefn2,2)};// Define additional parameterssubtypeGroupLayerCreateParam.DefinitionQuery=newDefinitionQuery(whereClause:"Enabled = 1",name:"IsActive");subtypeGroupLayerCreateParam.IsVisible=true;subtypeGroupLayerCreateParam.MinimumScale=50000;SubtypeGroupLayersubtypeGroupLayer2=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<SubtypeGroupLayer>(subtypeGroupLayerCreateParam,map));
Create layer from a lyrx file
awaitQueuedTask.Run(()=>{varlyrDocFromLyrxFile=newLayerDocument(@"d:\data\cities.lyrx");varcimLyrDoc=lyrDocFromLyrxFile.GetCIMLayerDocument();//modifying its renderer symbol to redvarcimSimpleRenderer=((CIMFeatureLayer)cimLyrDoc.LayerDefinitions[0]).RendererasCIMSimpleRenderer;cimSimpleRenderer?.Symbol.Symbol.SetColor(newCIMRGBColor(){R=255});//optionally save the updates out as a filelyrDocFromLyrxFile.Save(@"c:\data\cities_red.lyrx");//get a json representation of the layer document and you want store away...varaJSONString=lyrDocFromLyrxFile.AsJson();//... and load it back when neededlyrDocFromLyrxFile.Load(aJSONString);cimLyrDoc=lyrDocFromLyrxFile.GetCIMLayerDocument();//create a layer and add it to a mapvarlcp=newLayerCreationParams(cimLyrDoc);varlyr=LayerFactory.Instance.CreateLayer<FeatureLayer>(lcp,map);});
Apply Symbology to a layer from a Layer file
IEnumerable<FeatureLayer>featureLayers=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l =>l.ShapeType==esriGeometryType.esriGeometryPoint);varlayerFile=@"C:\Data\SDK\UniqueValuePointLayer.lyrx";foreach(varfeatureLayerToSymbolizeinfeatureLayers){//Get the Layer Document from the lyrx filevarlyrDocFromLyrxFile=newLayerDocument(layerFile);varcimLyrDoc=lyrDocFromLyrxFile.GetCIMLayerDocument();//Get the renderer from the layer filevarrendererFromLayerFile=((CIMFeatureLayer)cimLyrDoc.LayerDefinitions[0]).RendererasCIMUniqueValueRenderer;//Apply the renderer to the feature layer//Note: If working with a raster layer, use the SetColorizer method.featureLayerToSymbolize?.SetRenderer(rendererFromLayerFile);}
Add a WMS service
// Create a connection to the WMS servervarserverConnection=newCIMInternetServerConnection{URL="URL of the WMS service"};varconnection=newCIMWMSServiceConnection{ServerConnection=serverConnection};// Add a new layer to the mapvarlayerParams=newLayerCreationParams(connection);varlayerCreated=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams,map));
Add a WFS Service
CIMStandardDataConnectioncIMStandardDataConnection=newCIMStandardDataConnection(){WorkspaceConnectionString=@"SWAPXY=TRUE;SWAPXYFILTER=FALSE;URL=http://sampleserver6.arcgisonline.com/arcgis/services/SampleWorldCities/MapServer/WFSServer;VERSION=2.0.0",WorkspaceFactory=WorkspaceFactory.WFS,Dataset="Continent",DatasetType=esriDatasetType.esriDTFeatureClass};// Add a new layer to the mapvarlayerPamsDC=newLayerCreationParams(cIMStandardDataConnection);LayerlayerCreated=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerPamsDC,map));
Add a WMTS service
// Create a connection to the WMS servervarserverConnection=newCIMProjectServerConnection{URL="URL of the WMTS service.xml",ServerType=ServerType.WMTS,};varservice_connection=newCIMWMTSServiceConnection{ServerConnection=serverConnection,LayerName="AdminBoundaries",// Specify the layer name you want to add};// Add a new layer to the mapvarlayerParams=newLayerCreationParams(service_connection);layerParams.MapMemberPosition=MapMemberPosition.AddToBottom;varlayerCreated=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams,map));
Connect to an AGS Service using a .ags File
//This workflow would work forvaragsFilePath=@"C:\Data\ServerConnectionFiles\AcmeSampleService.ags";//ServerConnectionProjectItem supports .ags, .wms, .wmts, .wfs, and .wcs filesvarserver_conn_item=ItemFactory.Instance.Create(agsFilePath)asArcGIS.Desktop.Catalog.ServerConnectionProjectItem;//Get the server connection - passwords are never returnedvarserverConnection=server_conn_item.ServerConnectionasCIMProjectServerConnection;//Add to an AGS service connectionvarservice_connection=newCIMAGSServiceConnection(){URL="URL to the AGS _service_ on the AGS _server_",ServerConnection=serverConnection};// Add a new layer to the mapvarlayerParams=newLayerCreationParams(service_connection);layerParams.MapMemberPosition=MapMemberPosition.AddToBottom;varlayerCreated=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams,map));
Connect to an AGS Service using ServiceConnectionProperties
//Connect to the AGS service. Note: the connection will persist for the//duration of the Pro session.varserverUrl="https://sampleserver6.arcgisonline.com/arcgis/rest/services";varusername="user1";varpassword="user1";//at any point before creating a layer, first make a connection to the server//if one has not been already established for the current sessionvaruri=newUri(serverUrl);varprops=newServiceConnectionProperties(uri){User=username};//It is preferred that you use the Windows Credential Manager to store the password//However, it can be set as clear text if you so chooseprops.Password=password;//not recommended//Establish a connection to the server at any point in time _before_//creating a layer from a service on the serverawaitQueuedTask.Run(()=>{usingvargdb=newGeodatabase(props);});//later in the session, as needed...create a layer from one of the services//on the servervarserviceUrl="https://sampleserver6.arcgisonline.com/arcgis/rest/services/Wildfire_secure/MapServer";varlc=newLayerCreationParams(newUri(serviceUrl));awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<MapImageLayer>(lc,map));
Adding and changing styles for WMS Service Layer
varserverConnection=newCIMInternetServerConnection{URL="https://spritle.esri.com/arcgis/services/sanfrancisco_sld/MapServer/WMSServer"};varconnection=newCIMWMSServiceConnection{ServerConnection=serverConnection};LayerCreationParamsparameters=newLayerCreationParams(connection);parameters.MapMemberPosition=MapMemberPosition.AddToBottom;awaitQueuedTask.Run(()=>{varcompositeLyr=LayerFactory.Instance.CreateLayer<WMSLayer>(parameters,map);//wms layer in ArcGIS Pro always has a composite layer inside itvarwmsLayers=compositeLyr.Layers[0]asServiceCompositeSubLayer;//each wms sublayer belongs in that composite layervarhighwayLayerWMSSub=wmsLayers.Layers[1]asWMSSubLayer;//toggling a sublayer's visibilityif((highwayLayerWMSSub!=null)){boolvisibility=highwayLayerWMSSub.IsVisible;highwayLayerWMSSub.SetVisibility(!visibility);}//applying an existing style to a wms sub layervarpizzaLayerWMSSub=wmsLayers.Layers[0]asWMSSubLayer;varcurrentStyles=pizzaLayerWMSSub.GetStyleNames();pizzaLayerWMSSub.SetStyleName(currentStyles[1]);});
Create a query layer
Geodatabasegeodatabase=newGeodatabase(newDatabaseConnectionFile(newUri(@"C:\Connections\mySDE.sde")));CIMSqlQueryDataConnectionsqldc=newCIMSqlQueryDataConnection(){WorkspaceConnectionString=geodatabase.GetConnectionString(),GeometryType=esriGeometryType.esriGeometryPolygon,OIDFields="OBJECTID",Srid="102008",SqlQuery="select * from MySDE.dbo.STATES",Dataset="States"};varlcp=newLayerCreationParams(sqldc){Name="States"};FeatureLayerflyr=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(lcp,map));
Create a feature layer with class breaks renderer with defaults
varfeatureLayerCreationParams=newFeatureLayerCreationParams(newUri(@"c:\data\countydata.gdb\counties")){Name="Population Density (sq mi) Year 2010",RendererDefinition=newGraduatedColorsRendererDefinition("POP10_SQMI")};awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<FeatureLayer>(featureLayerCreationParams,map));
//Get an existing Layer. This layer has a symbol you want to use in a new layer.varlyr=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l =>l.ShapeType==esriGeometryType.esriGeometryPoint).FirstOrDefault();
Find a layer
//Finds layers by name and returns a read only list of LayersIReadOnlyList<Layer>layers=map.FindLayers("cities",true);//Finds a layer using a URI.//The Layer URI you pass in helps you search for a specific layer in a mapvarlyrFindLayer=MapView.Active.Map.FindLayer("CIMPATH=map/u_s__states__generalized_.xml");//This returns a collection of layers of the "name" specified. You can use any Linq expression to query the collection.varlyrExists=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Any(f =>f.Name=="U.S. States (Generalized)");
Find a standalone table
// these routines find a standalone table whether it is a child of the Map or a GroupLayervartblFind=map.FindStandaloneTable("CIMPATH=map/address_audit.xml");IReadOnlyList<StandaloneTable>tables=map.FindStandaloneTables("addresses");// this method finds a standalone table as a child of the map onlyvartable=map.StandaloneTables.FirstOrDefault(t =>t.Name=="Addresses");
Find a layer using partial name search
IEnumerable<Layer>matches=map.GetLayersAsFlattenedList().Where(l =>l.Name.Contains("partialLayerName",StringComparison.CurrentCultureIgnoreCase));List<Layer>layers=newList<Layer>();foreach(Layerlinmatches){layers.Add(l);}System.Diagnostics.Debug.WriteLine($"Found {layers.Count} layers with name containing '{"partialLayerName"}'");
// group a set of layers selected in the TOCvarselectedLayers=mapView.GetSelectedLayers();if(map.CanGroupMapMembers(selectedLayers)){map.GroupMapMembers(selectedLayers,"Group1");}// ungroup a groupLayerif(map.CanUngroupLayer(groupLayer)){map.UngroupLayer(groupLayer);}
// get the layers selected in the TOCvarselectedLayers=MapView.Active.GetSelectedLayers();// get the standalonetables elected in the TOCvarselectedTables=MapView.Active.GetSelectedStandaloneTables();varselectedMMs=newList<MapMember>(selectedLayers);selectedMMs.AddRange(selectedTables);// create the LayerDocumentLayerDocumentlayerDocument=newLayerDocument(selectedMMs);awaitQueuedTask.Run(()=>layerDocument.Save(@"c:\Data\MyLayerDocument.lyrx"));
awaitQueuedTask.Run(()=>{// get the CIM definition from the layervarcimFeatureDefinition=featureLayer.GetDefinition()asArcGIS.Core.CIM.CIMBasicFeatureLayer;// get the view of the source table underlying the layervarcimDisplayTable=cimFeatureDefinition.FeatureTable;// this field is used as the 'label' to represent the rowvardisplayField=cimDisplayTable.DisplayField;});
Enable labeling on a layer
// toggle the label visibilityawaitQueuedTask.Run(()=>featureLayer.SetLabelVisibility(!featureLayer.IsLabelVisible));
Set Elevation Mode for a layer
awaitQueuedTask.Run(()=>{ElevationTypeDefinitionelevationTypeDefinition=featureLayer.GetElevationTypeDefinition();elevationTypeDefinition.ElevationType=LayerElevationType.OnGround;//elevationTypeDefinition.ElevationType = LayerElevationType.RelativeToGround;//elevationTypeDefinition.ElevationType = LayerElevationType.RelativeToScene;//elevationTypeDefinition.ElevationType = LayerElevationType.AtAbsoluteHeight;//..so on.//Optional: Specify the cartographic offsetelevationTypeDefinition.CartographicOffset=1000;//Optional: Specify the VerticalExaggerationelevationTypeDefinition.VerticalExaggeration=2;if(featureLayer.CanSetElevationTypeDefinition(elevationTypeDefinition)){featureLayer.SetElevationTypeDefinition(elevationTypeDefinition);}});
Move a layer in the 2D group to the 3D Group in a Local Scene
awaitQueuedTask.Run(()=>{//The layer in the 2D group to move to the 3D Group in a Local Scene//Get the layer's definitionvarlyrDefn=featureLayer.GetDefinition()asCIMBasicFeatureLayer;//setting this property moves the layer to 3D group in a scenelyrDefn.IsFlattened=false;//Set the definition back to the layerfeatureLayer.SetDefinition(lyrDefn);});
Change the underlying data source of a feature layer - same workspace type
awaitQueuedTask.Run(()=>{//This is the existing layer for which we want to switch the underlying datasourcevarlyr=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();varconnectionStringToReplace=lyr.GetFeatureClass().GetDatastore().GetConnectionString();stringdatabaseConnectionPath=@"Path to the .sde connection file to replace with";//If the new SDE connection did not have a dataset with the same name as in the feature layer,//pass false for the validate parameter of the FindAndReplaceWorkspacePath method to achieve this.//If validate is true and the SDE did not have a dataset with the same name,//FindAndReplaceWorkspacePath will return failurelyr.FindAndReplaceWorkspacePath(connectionStringToReplace,databaseConnectionPath,true);});
Change Geodatabase Version of layers off a specified version in a map
awaitQueuedTask.Run(()=>{//Getting the current version name from the first feature layer of the mapDatastoredataStore=featureLayer.GetFeatureClass().GetDatastore();//getting datasourceGeodatabasegeodatabase=dataStoreasGeodatabase;//casting to Geodatabaseif(geodatabase==null){return;}VersionManagerversionManager=geodatabase.GetVersionManager();ArcGIS.Core.Data.VersioncurrentVersion=versionManager.GetCurrentVersion();stringcurrentVersionName=currentVersion.GetName();//Getting all available versions except the current oneList<ArcGIS.Core.Data.Version>versions=[];foreach(stringversionNameinversionManager.GetVersionNames()){if(versionName!=currentVersionName){break;}versions.Add(versionManager.GetVersion(versionName));}//Assuming there is at least one other version we pick the first one from the listArcGIS.Core.Data.VersiontoVersion=versions.FirstOrDefault();if(toVersion!=null){//Changing versionmap.ChangeVersion(currentVersion,toVersion);}});
Querying a feature layer
QueryFilterqf=newQueryFilter(){WhereClause="Class = 'city'"};intcount=0;using(RowCursorrows=selectedLayer.Search(qf))//execute{//Looping through to countwhile(rows.MoveNext()){count++;}}System.Diagnostics.Debug.WriteLine(String.Format("Total features that matched the search criteria: {0}",count));
Querying a feature layer with a spatial filter
varlayers=map.GetLayersAsFlattenedList().OfType<FeatureLayer>();varlayerToQuery=layers.FirstOrDefault(f =>f.Name=="USNationalParks");if(layerToQuery==null){return;}stringwhereClause="RecreationVisitsTotal > 1000000";//More than million visitors a yearvarspatialDefnLayer=layers.FirstOrDefault(f =>f.Name=="AllUSStates");if(spatialDefnLayer==null){return;}try{if(mapView==null){return;}awaitQueuedTask.Run(()=>{// Set the spatial filter geometry//Get the geometry from the selected features in the feature layervarspatialClauseGeom=spatialDefnLayer.GetFeatureOutline(mapView,FeatureOutlineType.Selected);//Create the definition queryDefinitionQuerydefinitionQuery=newDefinitionQuery{WhereClause=whereClause,Name=$"{layerToQuery.Name}"};//Setting the spatial filter to the Definition Queryif(definitionQuery.CanSetFilterGeometry(spatialClauseGeom)){definitionQuery.SetFilterGeometry(spatialClauseGeom);}layerToQuery.InsertDefinitionQuery(definitionQuery);layerToQuery.SetActiveDefinitionQuery(definitionQuery.Name);});}catch(Exceptionex){System.Diagnostics.Debug.WriteLine($"Error querying feature layer: {ex.Message}");}
Apply a Definition Query Filter to a Feature Layer
varus_parks=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l =>l.Name=="USNationalParks");varsql="STATE_ABBR = 'CA'";varisValid=awaitus_parks.IsValidDefinitionQuery(sql);if(isValid){awaitQueuedTask.Run(()=>{vardef_query=newDefinitionQuery("CaliforniaParks",sql);us_parks.InsertDefinitionQuery(def_query);us_parks.SetDefinitionQuery("STATE_ABBR = 'CA'");//Set it activeus_parks.SetActiveDefinitionQuery(def_query.Name);//or....also - set it active when it is inserted//us_parks.InsertDefinitionQuery(def_query, true);});}
Apply a Definition Query Filter With a Filter Geometry to a Feature Layer
vargreatLakes=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l =>l.Name=="Great Lakes");varusa_states=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l =>l.Name=="US_States");//name must be uniquevardef_query=newDefinitionQuery("GreatLakes","NAME in ('Huron','Michigan','Erie')");//create a filter geometry - in this example we will use the outline geometry//of all visible features from a us states layer...the filter geometry will be//intersected with the layer feature geometry when added to the def queryvarfilter_geom=awaitQueuedTask.Run(()=>usa_states.GetFeatureOutline(mapView,FeatureOutlineType.Visible));//other options...//var filter_geom = usa_states.GetFeatureOutline(mapView, FeatureOutlineType.All);//var filter_geom = usa_states.GetFeatureOutline(mapView, FeatureOutlineType.Selected);//Geometry must have a valid SR and be point, multi-point, line, or polyawaitQueuedTask.Run(()=>{if(def_query.CanSetFilterGeometry(filter_geom)){def_query.SetFilterGeometry(filter_geom);}});// test to ensure the definition query is validvarisValid=awaitgreatLakes.IsValidDefinitionQuery(def_query);if(isValid){awaitQueuedTask.Run(()=>{//Apply the def querygreatLakes.InsertDefinitionQuery(def_query);//Set it activegreatLakes.SetActiveDefinitionQuery(def_query.Name);//or....also - set it active when it is inserted//greatLakes.InsertDefinitionQuery(def_query, true);});}
Apply a Definition Query Filter to a Feature Layer Option 2
varus_parks=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l =>l.Name=="USNationalParks");varsql="STATE_ABBR = 'CA'";varisValid=awaitus_parks.IsValidDefinitionQuery(sql);if(isValid){//inserts a new definition query and makes it active//it will be assigned a unique nameus_parks.SetDefinitionQuery(sql);}
Retrieve the Definition Query Filters for a Feature Layer
varus_parks=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l =>l.Name=="USNationalParks");//enumerate the layer's definition queries - if anyvardef_queries=us_parks.DefinitionQueries;foreach(vardef_qryindef_queries){vargeom_uri=def_qry.GeometryUri??"null";varsr_wkid=def_qry.SpatialReference?.Wkid.ToString()??"null";vargeom=def_qry.GetFilterGeometry();vargeom_type=geom?.GeometryType.ToString()??"null";System.Diagnostics.Debug.WriteLine($" def_qry.Name: {def_qry.Name}");System.Diagnostics.Debug.WriteLine($" def_qry.WhereClause: {def_qry.WhereClause}");System.Diagnostics.Debug.WriteLine($" def_qry.GeometryUri: {geom_uri}");System.Diagnostics.Debug.WriteLine($" def_qry.SpatialReference: {sr_wkid}");System.Diagnostics.Debug.WriteLine($" def_qry.FilterGeometry: {geom_type}");System.Diagnostics.Debug.WriteLine("");}
Get Feature Outlines from a Feature Layer
vargreatLakes=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(l =>l.Name=="Great Lakes");varmichigan=map.GetBookmarks().First(b =>b.Name=="Michigan");//get all features - multiple feature geometries are always returned as a//single multi-partvarall_features_outline=greatLakes.GetFeatureOutline(mapView,FeatureOutlineType.All);//or get just the outline of selected featuresvarqry=newQueryFilter(){SubFields="*",WhereClause="NAME in ('Huron','Michigan','Erie')"};greatLakes.Select(qry);varsel_features_outline=greatLakes.GetFeatureOutline(mapView,FeatureOutlineType.Selected);greatLakes.ClearSelection();//or just the visible featuresmapView?.ZoomTo(michigan);varvisible_features_outline=greatLakes.GetFeatureOutline(mapView,FeatureOutlineType.Visible);
Get the attribute rotation field of a layer
awaitQueuedTask.Run(()=>{varcimRenderer=featureLayer.GetRenderer()asCIMUniqueValueRenderer;//Gets the visual variables from the renderervarcimRotationVariable=cimRenderer.VisualVariables.OfType<CIMRotationVisualVariable>().FirstOrDefault();//Gets the visual variable info for the z dimensionvarrotationInfoZ=cimRotationVariable.VisualVariableInfoZ;//The Arcade expression used to evaluate and return the field name for the rotationvarrotationExpression=rotationInfoZ.ValueExpressionInfo.Expression;// this expression stores the field name});
Find connected attribute field for rotation
awaitQueuedTask.Run(()=>{// get the CIM renderer from the layervarcimRenderer=featureLayer.GetRenderer()asArcGIS.Core.CIM.CIMSimpleRenderer;// get the collection of connected attributes for rotationvarcimRotationVariable=cimRenderer.VisualVariables.OfType<ArcGIS.Core.CIM.CIMRotationVisualVariable>().FirstOrDefault();// the z direction is describing the heading rotationvarrotationInfoZ=cimRotationVariable.VisualVariableInfoZ;varrotationExpression=rotationInfoZ.Expression;// this expression stores the field name});
Toggle "Scale layer symbols when reference scale is set"
awaitQueuedTask.Run(()=>{// get the CIM layer definitionvarcimFeatureLayer=featureLayer.GetDefinition()asArcGIS.Core.CIM.CIMFeatureLayer;// turn on the option to scale the symbols in this layer based in the map's reference scalecimFeatureLayer.ScaleSymbols=true;});
Set the layer cache
// change from the default 5 min to 2 minawaitQueuedTask.Run(()=>featureLayer.SetDisplayCacheMaxAge(TimeSpan.FromMinutes(2)));
Change the layer selection color - using CIM
awaitQueuedTask.Run(()=>{// get the CIM definition of the layervarlayerDef=featureLayer.GetDefinition()asArcGIS.Core.CIM.CIMBasicFeatureLayer;// disable the default symbollayerDef.UseSelectionSymbol=false;// assign a new colorlayerDef.SelectionColor=ColorFactory.Instance.RedRGB;// apply the definition to the layerfeatureLayer.SetDefinition(layerDef);if(!featureLayer.IsVisible){featureLayer.SetVisibility(true);}//Do a selectionmapView.SelectFeatures(mapView.Extent);});
Change the layer selection color - using Layer methods
awaitQueuedTask.Run(()=>{if(featureLayer.SupportsCustomSelectionProperties()){// get the set of propertiesvar(useCustomSelectioncolur,customSelectionColor,usecustomSelectioinFilleColor,customSelectionFillColor)=featureLayer.GetCustomSelectionProperties();// set the layer to use a specific colorfeatureLayer.SetCustomSelectionColor(ColorFactory.Instance.RedRGB);// or set a specific color AND fill colorfeatureLayer.SetCustomSelectionColor(ColorFactory.Instance.RedRGB,ColorFactory.Instance.BlueRGB);// reset to use the default selection colorfeatureLayer.SetUseDefaultSelectionColor();}if(!featureLayer.IsVisible){featureLayer.SetVisibility(true);}//Do a selectionmapView.SelectFeatures(mapView.Extent);});
Removes all layers that are unchecked
awaitQueuedTask.Run(()=>{//Get the group layers firstIReadOnlyList<GroupLayer>groupLayers=map.Layers.OfType<GroupLayer>().ToList();//Iterate and remove the layers within the group layers that are unchecked.foreach(vargroupLyringroupLayers){//Get layers that not visible within the groupvarlayers=groupLyr.Layers.Where(l =>l.IsVisible==false).ToList();//Remove all the layers that are not visible within the groupmap.RemoveLayers(layers);}//Group Layers that are empty and are uncheckedforeach(vargroupingroupLayers){if(group.Layers.Count==0&&group.IsVisible==false)//No layers in the group{//remove the groupmap.RemoveLayer(group);}}//Get Layers that are NOT Group layers and are uncheckedvarnotAGroupAndUnCheckedLayers=map.Layers.Where(l =>!(lisGroupLayer)&&l.IsVisible==false).ToList();//Remove all the non group layers that are not visiblemap.RemoveLayers(notAGroupAndUnCheckedLayers);});
Remove empty groups
awaitQueuedTask.Run(()=>{//Get the group layersIReadOnlyList<GroupLayer>groupLayers=map.Layers.OfType<GroupLayer>().ToList();foreach(vargroupingroupLayers){if(group.Layers.Count==0)//No layers in the group{//remove the groupmap.RemoveLayer(group);}}});
Create Abbreviation Dictionary in the Map Definition to a layer
awaitQueuedTask.Run(()=>{//Get the map's definitionvarmapDefn=map.GetDefinition();//Get the Map's Maplex labelling engine propertiesvarmapDefnPlacementProps=mapDefn.GeneralPlacementPropertiesasCIMMaplexGeneralPlacementProperties;//Define the abbreviations we need in an arrayList<CIMMaplexDictionaryEntry>abbreviationDictionary=newList<CIMMaplexDictionaryEntry>{newCIMMaplexDictionaryEntry{Abbreviation="Hts",Text="Heights",MaplexAbbreviationType=MaplexAbbreviationType.Ending},newCIMMaplexDictionaryEntry{Abbreviation="Ct",Text="Text",MaplexAbbreviationType=MaplexAbbreviationType.Ending}//etc};//The Maplex Dictionary - can hold multiple Abbreviation collectionsvarmaplexDictionary=newList<CIMMaplexDictionary>{newCIMMaplexDictionary{Name="NameEndingsAbbreviations",MaplexDictionary=abbreviationDictionary.ToArray()}};//Set the Maplex Label Engine Dictionary property to the Maplex Dictionary collection created above.mapDefnPlacementProps.Dictionaries=maplexDictionary.ToArray();//Set the Map definitionmap.SetDefinition(mapDefn);});
Apply Abbreviation Dictionary in the Map Definition to a layer
awaitQueuedTask.Run(()=>{//Creates Abbreviation dictionary and adds to Map Definition//Refer to the " Create Abbreviation Dictionary in the Map Definition to a layer" snippet above//Get the layer's definitionvarlyrDefn=featureLayer.GetDefinition()asCIMFeatureLayer;//Get the label classes - we need the first onevarlistLabelClasses=lyrDefn.LabelClasses.ToList();vartheLabelClass=listLabelClasses.FirstOrDefault();//Modify label Placement props to use abbreviation dictionaryCIMGeneralPlacementPropertieslabelEngine=map.GetDefinition().GeneralPlacementProperties;//Get the dictionary from the map definitiontheLabelClass.MaplexLabelPlacementProperties.DictionaryName="NameEndingsAbbreviations";theLabelClass.MaplexLabelPlacementProperties.CanAbbreviateLabel=true;theLabelClass.MaplexLabelPlacementProperties.CanStackLabel=false;//Set the labelClasses backlyrDefn.LabelClasses=listLabelClasses.ToArray();//set the layer's definitionfeatureLayer.SetDefinition(lyrDefn);});
Symbol Layer Drawing (SLD)
Add SLD
awaitQueuedTask.Run(()=>{//check if it can be added to the layerif(featureLayer.CanAddSymbolLayerDrawing()){featureLayer.AddSymbolLayerDrawing();}//ditto for a group layer...must have at least//one child feature layer that can participateif(groupLayer.CanAddSymbolLayerDrawing()){groupLayer.AddSymbolLayerDrawing();}});
Determine if a layer has SLD added
//SLD can be added to feature layers and group layers//For a group layer, SLD controls all child feature layers//that are participating in the SLD//var featLayer = ...;//retrieve the feature layer//var groupLayer = ...;//retrieve the group layer//Check if the layer has SLD added -returns a tuplevartuple=awaitQueuedTask.Run(()=>featureLayer.HasSymbolLayerDrawingAdded());if(tuple.addedOnLayer){//SLD is added on the layer}elseif(tuple.addedOnParent){//SLD is added on the parent (group layer) -//check parent...this can be recursivevarparentLayer=awaitGetParentLayerWithSLDAsync(featureLayer.ParentasGroupLayer);//Recursively get the parent with SLDTask<GroupLayer>GetParentLayerWithSLDAsync(GroupLayergroupLayer)=>QueuedTask.Run(()=>{while(groupLayer!=null){varsld_added=groupLayer.HasSymbolLayerDrawingAdded();if(sld_added.addedOnLayer){returngroupLayer;}if(!sld_added.addedOnParent){break;}groupLayer=groupLayer.ParentasGroupLayer;}returnnull;});}
Enable/Disable SLD
awaitQueuedTask.Run(()=>{//A layer may have SLD added but is not using it//HasSymbolLayerDrawingAdded returns a tuple - to check//the layer has SLD (not its parent) check addedOnLayerif(featureLayer.HasSymbolLayerDrawingAdded().addedOnLayer){//the layer has SLD but is the layer currently using it?//GetUseSymbolLayerDrawing returns a tuple - useOnLayer for//the layer (and useOnParent for the parent layer)if(!featureLayer.GetUseSymbolLayerDrawing().useOnLayer){//enable itfeatureLayer.SetUseSymbolLayerDrawing(true);}}});//Enable/Disable SLD on a layer parentif(awaitQueuedTask.Run(()=>featureLayer.HasSymbolLayerDrawingAdded().addedOnParent)){//check parent...this can be recursivevarparent=awaitGetParentLayerWithSLDAsync(featureLayer.ParentasGroupLayer);if(parent!=null){awaitQueuedTask.Run(()=>{if(parent.GetUseSymbolLayerDrawing().useOnLayer){parent.SetUseSymbolLayerDrawing(true);}});}}//Recursively get the parent with SLDTask<GroupLayer>GetParentLayerWithSLDAsync(GroupLayergroupLayer)=>QueuedTask.Run(()=>{while(groupLayer!=null){varsld_added=groupLayer.HasSymbolLayerDrawingAdded();if(sld_added.addedOnLayer){returngroupLayer;}if(!sld_added.addedOnParent){break;}groupLayer=groupLayer.ParentasGroupLayer;}returnnull;});
awaitQueuedTask.Run(()=>{if(featureLayer.GetIsFeatureDrawOrderSupported()){//Provide the field name to use and the sort ordering//The field must exist on the layer. Check the field can be used firstif(featureLayer.GetCanSetFeatureDrawOrder("Police_Precinct",SortOrderType.Ascending)){//Set the FDO to use the "Police_Precinct" field and ascending sort orderfeatureLayer.SetFeatureDrawOrder("Police_Precinct",SortOrderType.Ascending);}}});
Set Feature Drawing Order 2
awaitQueuedTask.Run(()=>{if(featureLayer.GetIsFeatureDrawOrderSupported()){varlistOfSortInfo=newList<CIMFeatureSortInfo>{//Draw features in the layer ordered by Police_Precinct field in ascending order//and then by Crime_rate field in descending ordernewCIMFeatureSortInfo{FieldName="Police_Precinct",SortDirection=SortOrderType.Ascending},newCIMFeatureSortInfo{FieldName="Crime_rate",SortDirection=SortOrderType.Descending}};//Provide the list of FSOs to use and their sort ordering//All fields must exist on the layer.if(featureLayer.GetCanSetFeatureDrawOrder(listOfSortInfo)){//Set the FDO to use the list of FSOsfeatureLayer.SetFeatureDrawOrder(listOfSortInfo);}}});
awaitQueuedTask.Run(()=>{if(featureLayer.GetIsFeatureDrawOrderSupported()){//will throw an InvalidOperation exception if the layer does//not support FDOfeatureLayer.ClearFeatureDrawOrder();//Passing an empty or null list to 'SetFeatureDrawOrder()' will also clear the FDOfeatureLayer.SetFeatureDrawOrder(newList<CIMFeatureSortInfo>());//orfeatureLayer.SetFeatureDrawOrder(null);}});
//Define a ServiceConnection to use for the new Elevation surfacevarserverConnection=newCIMInternetServerConnection{Anonymous=true,HideUserProperty=true,URL="https://elevation.arcgis.com/arcgis/services"};CIMAGSServiceConnectionserviceConnection=newCIMAGSServiceConnection{ObjectName="WorldElevation/Terrain",ObjectType="ImageServer",URL="https://elevation.arcgis.com/arcgis/services/WorldElevation/Terrain/ImageServer",ServerConnection=serverConnection};//Defines a new elevation source set to the CIMAGSServiceConnection defined above//Get the elevation surfaces defined in the mapvarlistOfElevationSurfaces=map.GetElevationSurfaceLayers();//Add the new elevation surfacevarelevationLyrCreationParams=newElevationLayerCreationParams(serviceConnection);varelevationSurface=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<ElevationSurfaceLayer>(elevationLyrCreationParams,map));
Set a custom elevation surface to a Z-Aware layer
awaitQueuedTask.Run(()=>{//Define the custom elevation surface to usevarlayerElevationSurface=newCIMLayerElevationSurface{ElevationSurfaceLayerURI="https://elevation3d.arcgis.com/arcgis/services/WorldElevation3D/Terrain3D/ImageServer"};//Get the layer's definitionvarlyrDefn=featureLayer.GetDefinition()asCIMBasicFeatureLayer;//Set the layer's elevation surfacelyrDefn.LayerElevation=layerElevationSurface;//Set the layer's definitionfeatureLayer.SetDefinition(lyrDefn);});
Add an elevation source to an existing elevation surface layer
ElevationSurfaceLayersurfaceLayer=null;// surfaceLayer could also be the ground layerstringuri="https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer";varcreateParams=newElevationLayerCreationParams(newUri(uri));createParams.Name="Terrain 3D";vareleSourceLayer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<Layer>(createParams,surfaceLayer));
Get the elevation surface layers and elevation source layers from a map
// retrieve the elevation surface layers in the map including the GroundvarsurfaceLayers=map.GetElevationSurfaceLayers();// retrieve the single ground elevation surface layer in the mapvargroundSurfaceLayer=map.GetGroundElevationSurfaceLayer();// determine the number of elevation sources in the ground elevation surface layerintnumberGroundSources=groundSurfaceLayer.Layers.Count;// get the first elevation source layer from the ground elevation surface layervargroundSourceLayer=groundSurfaceLayer.Layers.FirstOrDefault();
Find an elevation surface layer
// retrieve the elevation surface layers in the mapvarsurfaceLayers=map.GetElevationSurfaceLayers();// find a specific elevation surface layer by its URIvarsurfaceLayer=surfaceLayers.FirstOrDefault(l =>l.Name=="Surface2");// or use the FindElevationSurfaceLayer method, passing the layer URIsurfaceLayer=map.FindElevationSurfaceLayer("layerUri");
Remove elevation surface layers
//Ground will not be removedmap.ClearElevationSurfaceLayers();ElevationSurfaceLayersurfaceLayer=map.GetElevationSurfaceLayers().FirstOrDefault(l =>l.Name=="Surface2");//Cannot remove groundmap.RemoveLayer(surfaceLayer);//Ground will not be removedmap.RemoveLayers(map.GetElevationSurfaceLayers());
Get Z values from the default ground surface
varsurfaceZResult=awaitQueuedTask.Run(async()=>{// Get the center of the map's full extentMapPointmapPoint=map.CalculateFullExtent().Center;//Pass any Geometry type to GetZsFromSurfaceAsyncreturnawaitmap.GetZsFromSurfaceAsync(mapPoint);});if(surfaceZResult.Status==SurfaceZsResultStatus.Ok){// cast to a mapPointvarmapPointZ=surfaceZResult.GeometryasMapPoint;varz=mapPointZ.Z;}
Get Z values from a specific surface
awaitQueuedTask.Run(async()=>{vareleLayer=map.GetElevationSurfaceLayers().FirstOrDefault(l =>l.Name=="TIN");//Pass any Geometry type to GetZsFromSurfaceAsync//Ensure the feature layer is a line layer and is Z awarevarselectedFeatures=featureLayer.GetSelection();varrowCursor=selectedFeatures.Search();while(rowCursor.MoveNext()){varfeature=rowCursor.CurrentasFeature;varpolyline=feature.GetShape()asPolyline;varzResult=awaitmap.GetZsFromSurfaceAsync(polyline,eleLayer);if(zResult.Status==SurfaceZsResultStatus.Ok){varpolylineZ=zResult.GeometryasPolyline;// process the polylineZ// For example, you can iterate through the points and access their Z values}}});
Get Z values from a layer
awaitQueuedTask.Run(()=>{TinLayertinLayer=map.GetLayersAsFlattenedList().OfType<TinLayer>().FirstOrDefault();MapPointmapPoint=map.CalculateFullExtent().Center;//Any Map PointPolylinepolyline=PolylineBuilderEx.CreatePolyline(mapView.Extent);//Any Polylineif(tinLayer.CanGetZs()){// get z value for a mapPointvarzResult=tinLayer.GetZs(mapPoint);if(zResult.Status==SurfaceZsResultStatus.Ok){// cast to a mapPointvarmapPointZ=zResult.GeometryasMapPoint;varz=mapPointZ.Z;}// get z values for a polylinezResult=tinLayer.GetZs(polyline);if(zResult.Status==SurfaceZsResultStatus.Ok){// cast to a mapPointvarpolylineZ=zResult.GeometryasPolyline;}}});
Raster Layers
Create a raster layer
stringurlRatser=@"C:\Images\Italy.tif";awaitQueuedTask.Run(()=>{// Create a raster layer using a path to an image.// Note: You can create a raster layer from a url, project item, or data connection.varrasterLayerToCreate=LayerFactory.Instance.CreateLayer(newUri(urlRatser),map)asRasterLayer;});
Update the raster colorizer on a raster layer
awaitQueuedTask.Run(()=>{// Get the colorizer from the raster layer.CIMRasterColorizerrasterColorizer=rasterLayer.GetColorizer();// Update raster colorizer properties.rasterColorizer.Brightness=10;rasterColorizer.Contrast=-5;rasterColorizer.ResamplingType=RasterResamplingType.NearestNeighbor;// Update the raster layer with the changed colorizer.rasterLayer.SetColorizer(rasterColorizer);});
Update the RGB colorizer on a raster layer
awaitQueuedTask.Run(()=>{// Get the colorizer from the raster layer.CIMRasterColorizerrColorizer=rasterLayer.GetColorizer();// Check if the colorizer is an RGB colorizer.if(rColorizerisCIMRasterRGBColorizerrasterRGBColorizer){// Update RGB colorizer properties.rasterRGBColorizer.StretchType=RasterStretchType.ESRI;// Update the raster layer with the changed colorizer.rasterLayer.SetColorizer(rasterRGBColorizer);}});
Check if a certain colorizer can be applied to a raster layer
boolisTrue_ContainTheColorizerType=awaitQueuedTask.Run(()=>{// Get the list of colorizers that can be applied to the raster layer.IEnumerable<RasterColorizerType>applicableColorizerList=rasterLayer.GetApplicableColorizers();// Check if the RGB colorizer is part of the list.returnapplicableColorizerList.Contains(RasterColorizerType.RGBColorizer);});
Create a new colorizer based on a default colorizer definition and apply it to the raster layer
awaitQueuedTask.Run(async()=>{// Check if the Stretch colorizer can be applied to the raster layer.if(rasterLayer.GetApplicableColorizers().Contains(RasterColorizerType.StretchColorizer)){// Create a new Stretch Colorizer Definition using the default constructor.StretchColorizerDefinitionstretchColorizerDef_default=newStretchColorizerDefinition();// Create a new Stretch colorizer using the colorizer definition created above.CIMRasterStretchColorizernewStretchColorizer_default=awaitrasterLayer.CreateColorizerAsync(stretchColorizerDef_default)asCIMRasterStretchColorizer;// Set the new colorizer on the raster layer.rasterLayer.SetColorizer(newStretchColorizer_default);}});
Create a new colorizer based on a custom colorizer definition and apply it to the raster layer
// Check if the Stretch colorizer can be applied to the raster layer.//Get a color ramp from a stylevarproject=Project.Current;StyleProjectItemArcGISColorsStyleItem=project.GetItems<StyleProjectItem>().FirstOrDefault(s =>s.Name=="ArcGIS Colors");awaitQueuedTask.Run(async()=>{varcolorRamps=ArcGISColorsStyleItem.SearchColorRamps("Heat Map 4 - Semitransparent");CIMColorRampcolorRampToUse=colorRampList[0].ColorRamp;if(rasterLayer.GetApplicableColorizers().Contains(RasterColorizerType.StretchColorizer)){// Create a new Stretch Colorizer Definition specifying parameters// for band index, stretch type, gamma and color ramp.StretchColorizerDefinitionstretchColorizerDef_custom=newStretchColorizerDefinition(1,RasterStretchType.ESRI,2,colorRamp);// Create a new stretch colorizer using the colorizer definition created above.CIMRasterStretchColorizernewStretchColorizer_custom=awaitrasterLayer.CreateColorizerAsync(stretchColorizerDef_custom)asCIMRasterStretchColorizer;// Set the new colorizer on the raster layer.rasterLayer.SetColorizer(newStretchColorizer_custom);}});
Create a raster layer with a new colorizer definition
// Create a new stretch colorizer definition using default constructor.StretchColorizerDefinitionstretchColorizerDef=newStretchColorizerDefinition();// Create a raster layer creation parameters object with the raster file path.varrasterLayerCreationParams=newRasterLayerCreationParams(newUri("rasterPath")){ColorizerDefinition=stretchColorizerDef,Name="rasterLayerName",MapMemberIndex=0};// Create a raster layer using the colorizer definition created above.// Note: You can create a raster layer from a url, project item, or data connection.RasterLayerrasterLayerfromURL=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<RasterLayer>(rasterLayerCreationParams,map));
Mosaic Layers
Create a mosaic layer
//Path to mosaic datasetstringurlItaly=@"C:\Images\countries.gdb\Italy";// Create a mosaic layer using a path to a mosaic dataset.// Note: You can create a mosaic layer from a url, project item, or data connection.mosaicLayer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer(newUri(urlItaly),map)asMosaicLayer);
Update the raster colorizer on a mosaic layer
awaitQueuedTask.Run(()=>{// Get the image sub-layer from the mosaic layer.ImageMosaicSubLayermosaicImageSubLayer=mosaicLayer.GetImageLayer();// Get the colorizer from the image sub-layer.CIMRasterColorizerrasterColorizer=mosaicImageSubLayer.GetColorizer();// Update raster colorizer properties.rasterColorizer.Brightness=10;rasterColorizer.Contrast=-5;rasterColorizer.ResamplingType=RasterResamplingType.NearestNeighbor;// Update the image sub-layer with the changed colorizer.mosaicImageSubLayer.SetColorizer(rasterColorizer);});
Update the RGB colorizer on a mosaic layer
awaitQueuedTask.Run(()=>{// Get the image sub-layer from the mosaic layer.ImageMosaicSubLayermosaicImageSubLayer=mosaicLayer.GetImageLayer();// Get the colorizer from the image sub-layer.CIMRasterColorizerrColorizer=mosaicImageSubLayer.GetColorizer();// Check if the colorizer is an RGB colorizer.if(rColorizerisCIMRasterRGBColorizerrasterRGBColorizer){// Update RGB colorizer properties.rasterRGBColorizer.StretchType=RasterStretchType.ESRI;// Update the image sub-layer with the changed colorizer.mosaicImageSubLayer.SetColorizer(rasterRGBColorizer);}});
Check if a certain colorizer can be applied to a mosaic layer
boolisTrue_ContainTheColorizerType=awaitQueuedTask.Run(()=>{// Get the image sub-layer from the mosaic layer.ImageMosaicSubLayermosaicImageSubLayer=mosaicLayer.GetImageLayer();// Get the list of colorizers that can be applied to the image sub-layer.IEnumerable<RasterColorizerType>applicableColorizerList=mosaicImageSubLayer.GetApplicableColorizers();// Check if the RGB colorizer is part of the list.returnapplicableColorizerList.Contains(RasterColorizerType.RGBColorizer);});
Create a new colorizer based on a default colorizer definition and apply it to the mosaic layer
awaitQueuedTask.Run(async()=>{// Get the image sub-layer from the mosaic layer.ImageMosaicSubLayermosaicImageSubLayer=mosaicLayer.GetImageLayer();// Check if the Stretch colorizer can be applied to the image sub-layer.if(mosaicImageSubLayer.GetApplicableColorizers().Contains(RasterColorizerType.StretchColorizer)){// Create a new Stretch Colorizer Definition using the default constructor.StretchColorizerDefinitionstretchColorizerDef_default=newStretchColorizerDefinition();// Create a new Stretch colorizer using the colorizer definition created above.CIMRasterStretchColorizernewStretchColorizer_default=awaitmosaicImageSubLayer.CreateColorizerAsync(stretchColorizerDef_default)asCIMRasterStretchColorizer;// Set the new colorizer on the image sub-layer.mosaicImageSubLayer.SetColorizer(newStretchColorizer_default);}});
Create a new colorizer based on a custom colorizer definition and apply it to the mosaic layer
awaitQueuedTask.Run(async()=>{// Get the image sub-layer from the mosaic layer.ImageMosaicSubLayermosaicImageSubLayer=mosaicLayer.GetImageLayer();// Check if the Stretch colorizer can be applied to the image sub-layer.if(mosaicImageSubLayer.GetApplicableColorizers().Contains(RasterColorizerType.StretchColorizer)){// Create a new Stretch colorizer definition specifying parameters// for band index, stretch type, gamma and color ramp.StretchColorizerDefinitionstretchColorizerDef_custom=newStretchColorizerDefinition(1,RasterStretchType.ESRI,2,colorRamp);// Create a new stretch colorizer using the colorizer definition created above.CIMRasterStretchColorizernewStretchColorizer_custom=awaitmosaicImageSubLayer.CreateColorizerAsync(stretchColorizerDef_custom)asCIMRasterStretchColorizer;// Set the new colorizer on the image sub-layer.mosaicImageSubLayer.SetColorizer(newStretchColorizer_custom);}});
Create a mosaic layer with a new colorizer definition
// Create a new colorizer definition using default constructor.{StretchColorizerDefinitionstretchColorizerDef=newStretchColorizerDefinition();varrasterLayerCreationParams=newRasterLayerCreationParams(newUri("url")){Name="layerRasterName",ColorizerDefinition=stretchColorizerDef,MapMemberIndex=0};// Create a mosaic layer using the colorizer definition created above.// Note: You can create a mosaic layer from a url, project item, or data connection.MosaicLayernewMosaicLayer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<MosaicLayer>(rasterLayerCreationParams,map));}
Update the sort order - mosaic method on a mosaic layer
awaitQueuedTask.Run(()=>{// Get the image sub-layer from the mosaic layer.ImageServiceLayermosaicImageSubLayer=mosaicLayer.GetImageLayer();// Get the mosaic rule.CIMMosaicRulemosaicingRule=mosaicImageSubLayer.GetMosaicRule();// Set the Mosaic Method to Center.mosaicingRule.MosaicMethod=RasterMosaicMethod.Center;// Update the mosaic with the changed mosaic rule.mosaicImageSubLayer.SetMosaicRule(mosaicingRule);});
Update the resolve overlap - mosaic operator on a mosaic layer
awaitQueuedTask.Run(()=>{// Get the image sub-layer from the mosaic layer.ImageServiceLayermosaicImageSublayerToUse=mosaicLayer.GetImageLayer();// Get the mosaic rule.CIMMosaicRulemosaicRule=mosaicImageSublayerToUse.GetMosaicRule();// Set the Mosaic Operator to Mean.mosaicRule.MosaicOperatorType=RasterMosaicOperatorType.Mean;// Update the mosaic with the changed mosaic rule.mosaicImageSublayerToUse.SetMosaicRule(mosaicRule);});
Image Service Layers
Create an image service layer
stringurlToUse=@"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";// Create an image service layer using the url for an image service.varisLayer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer(newUri(urlToUse),map)asImageServiceLayer);
Update the raster colorizer on an image service layer
awaitQueuedTask.Run(()=>{// Get the colorizer from the image service layer.CIMRasterColorizerrasterColorizer=imageServiceLayer.GetColorizer();// Update the colorizer properties.rasterColorizer.Brightness=10;rasterColorizer.Contrast=-5;rasterColorizer.ResamplingType=RasterResamplingType.NearestNeighbor;// Update the image service layer with the changed colorizer.imageServiceLayer.SetColorizer(rasterColorizer);});
Update the RGB colorizer on an image service layer
awaitQueuedTask.Run(()=>{// Get the colorizer from the image service layer.CIMRasterColorizerrColorizer=imageServiceLayer.GetColorizer();// Check if the colorizer is an RGB colorizer.if(rColorizerisCIMRasterRGBColorizerrasterRGBColorizer){// Update RGB colorizer properties.rasterRGBColorizer.StretchType=RasterStretchType.ESRI;// Update the image service layer with the changed colorizer.imageServiceLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);}});
Check if a certain colorizer can be applied to an image service layer
boolisTrue_ContainTheColorizerType=awaitQueuedTask.Run(()=>{// Get the list of colorizers that can be applied to the imager service layer.IEnumerable<RasterColorizerType>applicableColorizerList=imageServiceLayer.GetApplicableColorizers();// Check if the RGB colorizer is part of the list.returnapplicableColorizerList.Contains(RasterColorizerType.RGBColorizer);});
Create a new colorizer based on a default colorizer definition and apply it to the image service layer
awaitQueuedTask.Run(async()=>{// Check if the Stretch colorizer can be applied to the image service layer.if(imageServiceLayer.GetApplicableColorizers().Contains(RasterColorizerType.StretchColorizer)){// Create a new Stretch Colorizer Definition using the default constructor.StretchColorizerDefinitionstretchColorizerDef_default=newStretchColorizerDefinition();// Create a new Stretch colorizer using the colorizer definition created above.CIMRasterStretchColorizernewStretchColorizer_default=awaitimageServiceLayer.CreateColorizerAsync(stretchColorizerDef_default)asCIMRasterStretchColorizer;// Set the new colorizer on the image service layer.imageServiceLayer.SetColorizer(newStretchColorizer_default);}});
Create a new colorizer based on a custom colorizer definition and apply it to the image service layer
awaitQueuedTask.Run(async()=>{// Check if the Stretch colorizer can be applied to the image service layer.if(imageServiceLayer.GetApplicableColorizers().Contains(RasterColorizerType.StretchColorizer)){// Create a new Stretch Colorizer Definition specifying parameters// for band index, stretch type, gamma and color ramp.StretchColorizerDefinitionstretchColorizerDef_custom=newStretchColorizerDefinition(1,RasterStretchType.ESRI,2,colorRamp);// Create a new stretch colorizer using the colorizer definition created above.CIMRasterStretchColorizernewStretchColorizer_custom=awaitimageServiceLayer.CreateColorizerAsync(stretchColorizerDef_custom)asCIMRasterStretchColorizer;// Set the new colorizer on the image service layer.imageServiceLayer.SetColorizer(newStretchColorizer_custom);}});
Create an image service layer with a new colorizer definition
// Create a new colorizer definition using default constructor.StretchColorizerDefinitionstretchColorizerDef=newStretchColorizerDefinition();varrasterLayerCreationParams=newRasterLayerCreationParams(newUri(url)){Name="RasterLayer",ColorizerDefinition=stretchColorizerDef,MapMemberIndex=0};// Create an image service layer using the colorizer definition created above.ImageServiceLayerimageServiceLayerWithColorizer=awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer<ImageServiceLayer>(rasterLayerCreationParams,map));
Update the sort order - mosaic method on an image service layer
awaitQueuedTask.Run(()=>{// Get the mosaic rule of the image service.CIMMosaicRulemosaicRule=imageServiceLayer.GetMosaicRule();// Set the Mosaic Method to Center.mosaicRule.MosaicMethod=RasterMosaicMethod.Center;// Update the image service with the changed mosaic rule.imageServiceLayer.SetMosaicRule(mosaicRule);});
Update the resolve overlap - mosaic operator on an image service layer
awaitQueuedTask.Run(()=>{// Get the mosaic rule of the image service.CIMMosaicRulemosaicingRule=imageServiceLayer.GetMosaicRule();// Set the Mosaic Operator to Mean.mosaicingRule.MosaicOperatorType=RasterMosaicOperatorType.Mean;// Update the image service with the changed mosaic rule.imageServiceLayer.SetMosaicRule(mosaicingRule);});
Renderers
Set unique value renderer to the selected feature layer of the active map
awaitQueuedTask.Run(()=>{//field to be used to retrieve unique valuesvarfields=newList<string>{"Type"};//constructing a point symbol as a template symbolCIMPointSymbolpointSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,16.0,SimpleMarkerStyle.Pushpin);CIMSymbolReferencesymbolPointTemplate=pointSym.MakeSymbolReference();//constructing renderer definition for unique value rendererUniqueValueRendererDefinitionuniqueValueRendererDef=newUniqueValueRendererDefinition(fields,symbolPointTemplate);//creating a unique value rendererCIMUniqueValueRendereruniqueValueRenderer=featureLayer.CreateRenderer(uniqueValueRendererDef)asCIMUniqueValueRenderer;//setting the renderer to the feature layerfeatureLayer.SetRenderer(uniqueValueRenderer);});
Create a UniqueValueRenderer to specify symbols to values
awaitQueuedTask.Run(()=>{//The goal is to construct the CIMUniqueValueRenderer which will be applied to the feature layer.// To do this, the following are the objects we need to set the renderer up with the fields and symbols.// As a reference, this is the USCities dataset. Snippet will create a unique value renderer that applies// specific symbols to all the cities in California and Alabama. The rest of the cities will use a default symbol.// First create a "CIMUniqueValueClass" for the cities in Alabama.List<CIMUniqueValue>listUniqueValuesAlabama=newList<CIMUniqueValue>{newCIMUniqueValue{FieldValues=newstring[]{"Alabama"}}};CIMUniqueValueClassalabamaUniqueValueClass=newCIMUniqueValueClass{Editable=true,Label="Alabama",Patch=PatchShape.Default,Symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB).MakeSymbolReference(),Visible=true,Values=listUniqueValuesAlabama.ToArray()};// Create a "CIMUniqueValueClass" for the cities in California.List<CIMUniqueValue>listUniqueValuescalifornia=newList<CIMUniqueValue>{newCIMUniqueValue{FieldValues=newstring[]{"California"}}};CIMUniqueValueClasscaliforniaUniqueValueClass=newCIMUniqueValueClass{Editable=true,Label="California",Patch=PatchShape.Default,Symbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.BlueRGB).MakeSymbolReference(),Visible=true,Values=listUniqueValuescalifornia.ToArray()};//Create a list of the above two CIMUniqueValueClassesList<CIMUniqueValueClass>listUniqueValueClasses=newList<CIMUniqueValueClass>{alabamaUniqueValueClass,californiaUniqueValueClass};//Create a list of CIMUniqueValueGroupCIMUniqueValueGroupuvg=newCIMUniqueValueGroup{Classes=listUniqueValueClasses.ToArray(),};List<CIMUniqueValueGroup>listUniqueValueGroups=newList<CIMUniqueValueGroup>{uvg};//Create the CIMUniqueValueRendererCIMUniqueValueRendereruvr=newCIMUniqueValueRenderer{UseDefaultSymbol=true,DefaultLabel="all other values",DefaultSymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreyRGB).MakeSymbolReference(),Groups=listUniqueValueGroups.ToArray(),Fields=newstring[]{"STATE_NAME"}};//Set the feature layer's renderer.featureLayer.SetRenderer(uvr);});
Create a Heatmap Renderer
stringcolorBrewerSchemesName="ArcGIS Colors";//Get the style project item that contains the color ramps//Refer to the Initialize region for an example of how to get a style item//and the color ramp from it.awaitQueuedTask.Run(()=>{//defining a heatmap renderer that uses values from Population field as the weightsHeatMapRendererDefinitionheatMapDef=newHeatMapRendererDefinition(){Radius=20,WeightField="Population",ColorRamp=colorRamp,RendereringQuality=8,UpperLabel="High Density",LowerLabel="Low Density"};CIMHeatMapRendererheatMapRndr=featureLayer.CreateRenderer(heatMapDef)asCIMHeatMapRenderer;featureLayer.SetRenderer(heatMapRndr);});
Use Arcade expression to create Class Breaks
varusaStatesLayer=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(fl =>fl.Name=="USA States");if(usaStatesLayer==null){return;}awaitQueuedTask.Run(()=>{//Create a color ramp from red to bluevarcolorRampForPopulation=ColorFactory.Instance.ConstructColorRamp(ColorRampAlgorithm.LinearContinuous,ColorFactory.Instance.RedRGB,ColorFactory.Instance.BlueRGB);//This Arcade expression categorizes the POP2000 field in the usaStates layer//into Low, Medium, and High valuesvararcade=@"if ($feature.POP2000 < 1000000) {return ""Low"";}"+@"else if ($feature.POP2000 >= 100000 && $feature.POP2000 < 5000000) {return ""Medium""; }"+@"else if ($feature.POP2000 >= 5000000) {return ""High"";}"+@"else{return ""NA"";}";//Create the Arcade expression infoCIMExpressionInfoarcadeExp=newCIMExpressionInfo();arcadeExp.Expression=arcade;arcadeExp.ReturnType=ExpressionReturnType.Default;arcadeExp.Title="State Population Categorized";arcadeExp.Name="USA States Population 2000";//Each population category is assigned a color from the color ramp and symbolized on the map// using a unique value renderervaruvr_desc=newUniqueValueRendererDefinition(){//ValueFields = new List<string> { "STATION" },ColorRamp=colorRampForPopulation,UseDefaultSymbol=true,ValuesLimit=100,ArcadeExpression=arcadeExp.Expression};//Create the renderer and assign it to the layervarrenderer=usaStatesLayer.CreateRenderer(uvr_desc);usaStatesLayer.SetRenderer(renderer);});
Create an unclassed Renderer
stringcolorBrewerSchemesName="ArcGIS Colors";//Get the style project item that contains the color ramps//Refer to the Initialize region for an example of how to get a style itemawaitQueuedTask.Run(()=>{CIMPointSymbolpointSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,16.0,SimpleMarkerStyle.Diamond);CIMSymbolReferencesymbolPointTemplate=pointSym.MakeSymbolReference();//defining an unclassed renderer with custom upper and lower stops//all features with value >= 5,000,000 will be drawn with the upper color from the color ramp//all features with value <= 50,000 will be drawn with the lower color from the color rampUnclassedColorsRendererDefinitionunclassRndrDef=newUnclassedColorsRendererDefinition("Population",symbolPointTemplate,colorRamp,"Highest","Lowest",5000000,50000){//drawing features with null values with a different symbolShowNullValues=true,NullValueLabel="Unknown"};// Create a point symbol for null valuesCIMPointSymbolnullSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,16.0,SimpleMarkerStyle.Circle);unclassRndrDef.NullValueSymbol=nullSym.MakeSymbolReference();//Create the unclassed renderer using the definitionCIMClassBreaksRenderercbRndr=featureLayer.CreateRenderer(unclassRndrDef)asCIMClassBreaksRenderer;//Set the renderer to the feature layerfeatureLayer.SetRenderer(cbRndr);});
Create a Proportion Renderer with max and min symbol size capped
stringcolorBrewerSchemesName="ArcGIS Colors";//Get the style project item that contains the color ramps//Refer to the Initialize region for an example of how to get a style itemawaitQueuedTask.Run(()=>{//Creating a point symbol to be used as a template symbol for the proportional rendererCIMPointSymbolpointSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,1.0,SimpleMarkerStyle.Circle);CIMSymbolReferencesymbolPointTemplate=pointSym.MakeSymbolReference();//minimum symbol size is capped to 4 point while the maximum symbol size is set to 50 point//Creating a proportional renderer definition that uses the "Population" fieldProportionalRendererDefinitionprDef=newProportionalRendererDefinition("POPULATION",symbolPointTemplate,4,50,true){//setting upper and lower size stops to stop symbols growing or shrinking beyond those thresholdsUpperSizeStop=5000000,//features with values >= 5,000,000 will be drawn with maximum symbol sizeLowerSizeStop=50000//features with values <= 50,000 will be drawn with minimum symbol size};// Create a proportional renderer using the definitionCIMProportionalRendererpropRndr=featureLayer.CreateRenderer(prDef)asCIMProportionalRenderer;// Set the renderer to the feature layerfeatureLayer.SetRenderer(propRndr);});
Create a True Proportion Renderer
stringcolorBrewerSchemesName="ArcGIS Colors";//Get the style project item that contains the color ramps//Refer to the Initialize region for an example of how to get a style itemawaitQueuedTask.Run(()=>{//Creating a point symbol to be used as a template symbol for the proportional rendererCIMPointSymbolpointSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,1.0,SimpleMarkerStyle.Circle);CIMSymbolReferencesymbolPointTemplate=pointSym.MakeSymbolReference();//Defining proportional renderer where size of symbol will be same as its value in field used in the renderer.ProportionalRendererDefinitionprDef=newProportionalRendererDefinition("POPULATION",esriUnits.esriMeters,symbolPointTemplate,SymbolShapes.Square,ValueRepresentations.Radius);//Create a Proportional renderer using the definitionCIMProportionalRendererpropRndr=featureLayer.CreateRenderer(prDef)asCIMProportionalRenderer;// Set the renderer to the feature layerfeatureLayer.SetRenderer(propRndr);});
Attribute Table - ITablePane
Set zoom level for Attribute Table
//Check if the active pane is an ITablePaneif(FrameworkApplication.Panes.ActivePaneisITablePanetablePane){//Get the current zoom level of the table panevarcurrentZoomLevel=tablePane.ZoomLevel;// Set a new zoom level, for example, increase it by 50varnewZoomLevel=currentZoomLevel+50;// Set the new zoom level to the table panetablePane.SetZoomLevel(newZoomLevel);}
Retrieve the values of selected cell in the attribute table
{if(FrameworkApplication.Panes.ActivePaneisITablePanetablePane){varmapMember=tablePane.MapMember;//Get the active row's object ID from the table panevaroid=tablePane.ActiveObjectID;if(oid.HasValue&&oid.Value!=-1&&mapMember!=null){//Get the field of the active columnvaractiveField=tablePane.ActiveColumn;awaitQueuedTask.Run(()=>{// TODO: Use core objects to retrieve record and get value});}}}
Move to a particular row
// Check if the active pane is an ITablePaneif(FrameworkApplication.Panes.ActivePaneisITablePanetablePane){// move to first rowtablePane.BringIntoView(0);// move to sixth rowtablePane.BringIntoView(5);}
Working with Standalone Tables
Create a StandaloneTable
//container can be a map or group layervarcontainer=map;//var container = MapView.Active.Map.GetLayersAsFlattenedList()// .OfType<GroupLayer>().First();awaitQueuedTask.Run(()=>{//use a local pathvartable=StandaloneTableFactory.Instance.CreateStandaloneTable(newUri(@"C:\Temp\Data\SDK.gdb\EarthquakeDamage",UriKind.Absolute),container);//use a URI to a feature service table endpointvartable2=StandaloneTableFactory.Instance.CreateStandaloneTable(newUri(@"https://bexdog.esri.com/server/rest/services/FeatureServer"+"/2",UriKind.Absolute),container);//Use an itemvaritem=ItemFactory.Instance.Create(@"C:\Temp\Data\SDK.gdb\ParcelOwners");vartableCreationParams=newStandaloneTableCreationParams(item);vartable3=StandaloneTableFactory.Instance.CreateStandaloneTable(tableCreationParams,container);//use table creation paramsvartable_params=newStandaloneTableCreationParams(item){DefinitionQuery=newDefinitionQuery(whereClause:"LAND_USE = 3",name:"Landuse")};vartable4=StandaloneTableFactory.Instance.CreateStandaloneTable(table_params,container);});
Retrieve a table from its container
varcontainer=MapView.Active.Map;//the map standalone table collectionvartable=container.GetStandaloneTablesAsFlattenedList().FirstOrDefault(tbl =>tbl.Name=="EarthquakeDamage");//or from a group layervargrp_layer=MapView.Active.Map.FindLayers("GroupLayer1").First()asGroupLayer;vartable2=grp_layer.FindStandaloneTables("EarthquakeDamage").First();//or grp_layer.GetStandaloneTablesAsFlattenedList().First()//or grp_layer.StandaloneTables.Where(...).First(), etc.//show the table in a table view//use FrameworkApplication.Current.Dispatcher.BeginInvoke if not on the UI threadFrameworkApplication.Panes.OpenTablePane(table2);
Move a Standalone table
//get the first group layer that has at least one tablevargrp_layer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<GroupLayer>().First(g =>g.StandaloneTables.Count>0);grp_layer.MoveStandaloneTable(grp_layer.StandaloneTables.First(),-1);//move the last table in the map standalone tables to a group//layer and place it at position 3. If 3 is invalid, the table//will be placed at the bottom of the target container//assumes the map has at least one standalone table...vartable=map.StandaloneTables.Last();map.MoveStandaloneTable(table,grp_layer,3);//move a table from a group layer to the map standalone tables//collection - assumes a table called 'Earthquakes' existsvartable2=grp_layer.FindStandaloneTables("Earthquakes").First();//move to the map containermap.MoveStandaloneTable(table2,0);//will be placed at the top
Remove a Standalone table
//get the first group layer that has at least one tablevargrp_layer=map.GetLayersAsFlattenedList().OfType<GroupLayer>().First(g =>g.StandaloneTables.Count>0);awaitQueuedTask.Run(()=>{//get the tables from the map containervartables=map.GetStandaloneTablesAsFlattenedList();//delete the first...if(tables.Count()>0){map.RemoveStandaloneTable(tables.First());//or delete all of themmap.RemoveStandaloneTables(tables);}//delete a table from a group layer//assumes it has at least one table...grp_layer.RemoveStandaloneTable(grp_layer.StandaloneTables.First());});
Metadata
Get and Set Map Metadata
awaitQueuedTask.Run(()=>{//Get map's metadatavarmapMetadata=map.GetMetadata();//TODO:Make edits to metadata using the retrieved mapMetadata string.//Set the modified metadata back to the map.if(map.GetCanEditMetadata()){map.SetMetadata(mapMetadata);}});
Layer Metadata
//Search for only layers/tables here if needed.MapMembermapMember=map.GetLayersAsFlattenedList().FirstOrDefault();if(mapMember==null){return;}awaitQueuedTask.Run(()=>{//Gets whether or not the MapMember stores its own metadata or uses metadata retrieved//from its source.booldoesUseSourceMetadata=mapMember.GetUseSourceMetadata();//Sets whether or not the MapMember will use its own metadata or the metadata from//its underlying source (if it has one).mapMember.SetUseSourceMetadata(true);//Does the MapMember supports metadatavarsupportsMetadata=mapMember.SupportsMetadata;//Get MapMember metadatavarmetadatstring=mapMember.GetMetadata();//TODO:Make edits to metadata using the retrieved mapMetadata string.//Set the modified metadata back to the mapmember (layer, table..)if(mapMember.GetCanEditMetadata()){mapMember.SetMetadata(metadatstring);}});
SelectionSet
Translate From Dictionary to SelectionSet
//Create a selection set from a list of object ids//using FromDictionaryMapMemberus_zips_layer=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(s =>s.Name=="USA zips layer");varaddToSelection=newDictionary<MapMember,List<long>>();addToSelection.Add(us_zips_layer,newList<long>{1506,2696,2246,1647,948});//Create a SelectionSet objectvarselSet=ArcGIS.Desktop.Mapping.SelectionSet.FromDictionary(addToSelection);
Translate from SelectionSet to Dictionary
MapMemberus_zips_layer=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(s =>s.Name=="USA zips layer");varaddToSelection=newDictionary<MapMember,List<long>>();addToSelection.Add(us_zips_layer,newList<long>{1506,2696,2246,1647,948});//Create a SelectionSet objectvarselSet=ArcGIS.Desktop.Mapping.SelectionSet.FromDictionary(addToSelection);varselSetDict=selSet.ToDictionary();// convert to the dictionary and only include those that are of type FeatureLayervarselSetDictFeatureLayer=selSet.ToDictionary<FeatureLayer>();
Get OIDS from a SelectionSet for a given MapMember
MapMemberus_zips_layer=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(s =>s.Name=="USA zips layer");varaddToSelection=newDictionary<MapMember,List<long>>();addToSelection.Add(us_zips_layer,newList<long>{1506,2696,2246,1647,948});//Create a SelectionSet objectvarselSet=ArcGIS.Desktop.Mapping.SelectionSet.FromDictionary(addToSelection);if(selSet.Contains(us_zips_layer)){varoids=selSet[us_zips_layer];}
Get OIDS from a SelectionSet for a given MapMember by Name
MapMemberus_zips_layer=map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First(s =>s.Name=="USA zips layer");varaddToSelection=newDictionary<MapMember,List<long>>();addToSelection.Add(us_zips_layer,newList<long>{1506,2696,2246,1647,948});//Create a SelectionSet objectvarselSet=ArcGIS.Desktop.Mapping.SelectionSet.FromDictionary(addToSelection);varkvp=selSet.ToDictionary().Where(kvp =>kvp.Key.Name=="LayerName").FirstOrDefault();varoidList=kvp.Value;
Check SelectionSet Equality
// get map selectionvarmapSelSet=MapView.Active.Map.GetSelection();// create a selectionSetvarselDict=newDictionary<MapMember,List<long>>();selDict.Add(featureLayer,newList<long>{1506,2696,2246,1647,948});varlayerSelSet=ArcGIS.Desktop.Mapping.SelectionSet.FromDictionary(selDict);// test for equality - use Equals methodvarisEquals=mapSelSet.Equals(layerSelSet);// test for equality - use operatorsvarequals=mapSelSet==layerSelSet;varnotEquals=mapSelSet!=layerSelSet;
Selection Options
Get/Set Selection Options
varoptions=ApplicationOptions.SelectionOptions;awaitQueuedTask.Run(()=>{vardefaultColor=options.DefaultSelectionColor;//Set the selection color to redvarcolor=options.SelectionColorasCIMRGBColor;options.SetSelectionColor(ColorFactory.Instance.CreateRGBColor(255,0,0));//Set the selection fill color and fill hatchvardefaultFill=options.DefaultSelectionFillColor;varfill=options.SelectionFillColor;varisHatched=options.IsSelectionFillHatched;options.SetSelectionFillColor(ColorFactory.Instance.CreateRGBColor(100,100,0));if(!isHatched){options.SetSelectionFillIsHatched(true);}//Toggle the selection Chip and GraphicvarshowSelectionChip=options.ShowSelectionChip;options.SetShowSelectionChip(!showSelectionChip);varshowSelectionGraphic=options.ShowSelectionGraphic;options.SetShowSelectionGraphic(!showSelectionGraphic);//Get the value indicating whether to save the layer and standalone table selection with the map.varsaveSelection=options.SaveSelection;options.SetSaveSelection(!saveSelection);//Get/Set the selection tolerancevardefaultTol=options.DefaultSelectionTolerance;vartol=options.SelectionTolerance;options.SetSelectionTolerance(2*defaultTol);// extension methods available for selection methods and combination methodsvarselMethod=options.SelectionMethod;options.SetSelectionMethod(SelectionMethod.Contains);varcombMethod=options.CombinationMethod;options.SetCombinationMethod(SelectionCombinationMethod.Add);// note that the following SelectionCombinationMethod is not supported//options.SetCombinationMethod(SelectionCombinationMethod.XOR);});
Elevation Profile
Get Elevation profile from the default ground surface
// get the elevation profile for a polyline / set of polylinesPolylinepolyline=PolylineBuilderEx.CreatePolyline();MapPointmapPoint=MapPointBuilderEx.CreateMapPoint(34,-118,SpatialReferences.WGS84);List<MapPoint>mapPoints=newList<MapPoint>{mapPoint};varresult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync([polyline]);if(result.Status==SurfaceZsResultStatus.Ok){varpolylineZ=result.Polyline;// process the polylineZ// get the elevation profile for a set of pointsresult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync(mapPoints);if(result.Status==SurfaceZsResultStatus.Ok){polylineZ=result.Polyline;// process the polylineZ}}
Get Elevation profile from a specific surface
// find a specific elevation surface layervareleLayer=MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l =>l.Name=="TIN");Polylinepolyline=PolylineBuilderEx.CreatePolyline();MapPointmapPoint=MapPointBuilderEx.CreateMapPoint(34,-118,SpatialReferences.WGS84);List<MapPoint>mapPoints=newList<MapPoint>{mapPoint};// get the elevation profile for a polyline / set of polylines// use the specific elevation surface layervarzResult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync([polyline],eleLayer);if(zResult.Status==SurfaceZsResultStatus.Ok){varpolylineZ=zResult.Polyline;// process the polylineZ}// get the elevation profile for a set of points// use the specific elevation surface layerzResult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync(mapPoints,eleLayer);if(zResult.Status==SurfaceZsResultStatus.Ok){varpolylineZ=zResult.Polyline;// process the polylineZ}
Interpolate a line between two points and calculate the elevation profile
intnumPoints=20;//Or any number of points you want to interpolate// use a specific elevation surfacevareleLayer=MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l =>l.Name=="TIN");// use the default ground elevation surfaceMapPointstartPt=MapPointBuilderEx.CreateMapPoint(-130,20,SpatialReferences.WGS84);MapPointendPt=MapPointBuilderEx.CreateMapPoint(-100,50,SpatialReferences.WGS84);varresult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync(startPt,endPt,numPoints);if(result.Status==SurfaceZsResultStatus.Ok){varpolylineZ=result.Polyline;// process the polylineZ}// use a specific elevation surfaceresult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync(startPt,endPt,numPoints,eleLayer);if(result.Status==SurfaceZsResultStatus.Ok){varpolylineZ=result.Polyline;// process the polylineZ}
Show Elevation profile graph with the default ground surface
if(!MapView.Active.CanShowElevationProfileGraph()){return;}// show the elevation profile for a polyline// use the default ground surface layerPolylinepolyline=PolylineBuilderEx.CreatePolyline();MapView.Active.ShowElevationProfileGraph([polyline]);// show the elevation profile for a set of points// use the default ground surface layer//Some pointsMapPointmapPoint=MapPointBuilderEx.CreateMapPoint(34,-118,SpatialReferences.WGS84);List<MapPoint>mapPoints=newList<MapPoint>{mapPoint};MapView.Active.ShowElevationProfileGraph(mapPoints);
Show Elevation profile graph with a specific surface
if(!MapView.Active.CanShowElevationProfileGraph()){return;}// use a specific elevation surfacevareleLayer=MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l =>l.Name=="TIN");// set up the parametersvarprofileParams=newElevationProfileParameters();profileParams.SurfaceLayer=eleLayer;profileParams.Densify=true;// show the elevation profile for a polyline using the params//Any linePolylinepolyline=PolylineBuilderEx.CreatePolyline();MapView.Active.ShowElevationProfileGraph([polyline],profileParams);// show the elevation profile for a set of points using the params//Some pointsMapPointmapPoint=MapPointBuilderEx.CreateMapPoint(34,-118,SpatialReferences.WGS84);List<MapPoint>mapPoints=newList<MapPoint>{mapPoint};MapView.Active.ShowElevationProfileGraph(mapPoints,profileParams);
Show Elevation profile graph between two points
intnumPoints=20;if(!MapView.Active.CanShowElevationProfileGraph()){return;}// show the elevation profile// use the default ground elevation surfaceMapPointstartPt=MapPointBuilderEx.CreateMapPoint(-130,20,SpatialReferences.WGS84);MapPointendPt=MapPointBuilderEx.CreateMapPoint(-100,50,SpatialReferences.WGS84);MapView.Active.ShowElevationProfileGraph(startPt,endPt,numPoints);// find a specific elevation surface layervartinLayer=MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l =>l.Name=="TIN");// set up the paramsvarelevProfileParams=newElevationProfileParameters();elevProfileParams.SurfaceLayer=tinLayer;elevProfileParams.Densify=false;// show the elevation profile using the paramsMapView.Active.ShowElevationProfileGraph(startPt,endPt,numPoints,elevProfileParams);
Show Elevation profile graph using an ElevationProfileResult
MapPointstartPt=MapPointBuilderEx.CreateMapPoint(-130,20,SpatialReferences.WGS84);MapPointendPt=MapPointBuilderEx.CreateMapPoint(-100,50,SpatialReferences.WGS84);varelevProfileResult=awaitMapView.Active.Map.GetElevationProfileFromSurfaceAsync(startPt,endPt,10);if(elevProfileResult.Status!=SurfaceZsResultStatus.Ok){return;}if(!MapView.Active.CanShowElevationProfileGraph()){return;}// show the elevation profile using the resultMapView.Active.ShowElevationProfileGraph(elevProfileResult);
Access the ElevationProfileGraph when added
// subscribe to the Added, Removed events for the elevation profile graphmapView.ElevationProfileGraphAdded+=Mv_ElevationProfileGraphAdded;mapView.ElevationProfileGraphRemoved+=Mv_ElevationProfileGraphRemoved;//Handles the event triggered when an elevation profile graph is removed.voidMv_ElevationProfileGraphRemoved(objectsender,EventArgse){//TODO: handle the removal of the elevation profile graph}//Handles the event triggered when an elevation profile graph is added to the active map view.voidMv_ElevationProfileGraphAdded(objectsender,EventArgse){// get the elevation profile graph from the view// this will be non-null since we are in a ElevationProfileGraphAdded handlervarmv=MapView.Active;vargraph=mv.GetElevationProfileGraph();// subscribe to the ContentLoaded eventgraph.ContentLoaded+=Graph_ContentLoaded;}// Handles the event triggered when the elevation profile graph content is loaded.voidGraph_ContentLoaded(objectsender,EventArgse){// get the elevation profile graphvargraph=senderasArcGIS.Desktop.Mapping.ElevationProfileGraph;// get the elevation profile geometryvarpolyline=graph.Geometry;// get the elevation profile statisticsvarstats=graph.ElevationProfileStatistics;}
Access the ElevationProfileGraph
varelevProfileGraph=MapView.Active.GetElevationProfileGraph();// Elevation profile graph will be null if no profile graph is displayedif(elevProfileGraph==null){return;}// get the elevation profile geometry and statsvarpolyline=elevProfileGraph.Geometry;varstats=elevProfileGraph.ElevationProfileStatistics;// reverse the graphelevProfileGraph.IsReversed=!elevProfileGraph.IsReversed;// collapse the graphelevProfileGraph.IsExpanded=false;
Export Elevation Profile Graph
varelevProfileGraph=MapView.Active.GetElevationProfileGraph();// Elevation profile graph will be null if no profile graph is displayedif(elevProfileGraph==null){return;}if(elevProfileGraph.CanExport){elevProfileGraph.ExportToImage("c:\\temp\\myprofileImage.png");elevProfileGraph.ExportToCSV("c:\\temp\\myprofile.csv");}
Customize Elevation Profile Graph Display
// customize the elevation profile graph optionsvaroptions=newElevationProfileOptions(){LineColor=ColorFactory.Instance.CreateRGBColor(0,0,100),ShowAverageSlope=false,ShowMaximumSlope=false};vareaOptions=ApplicationOptions.ExploratoryAnalysisOptions;if(eaOptions.CanSetElevationProfileOptions(options)){awaiteaOptions.SetElevationProfileOptionsAsync(options);}// or reset to default optionsvardefaultOptions=eaOptions.GetDefaultElevationProfileOptions();if(eaOptions.CanSetElevationProfileOptions(defaultOptions)){awaiteaOptions.SetElevationProfileOptionsAsync(defaultOptions);}
Device Location API, GPS/GNSS Devices
Connect to a Device Location Source
varnewSrc=newSerialPortDeviceLocationSource();//Specify the COM port the device is connected tonewSrc.ComPort="Com3";newSrc.BaudRate=4800;newSrc.AntennaHeight=3;// meters//fill in other properties as neededvarprops=newDeviceLocationProperties();props.AccuracyThreshold=10;// meters// jump to the background thread//open the deviceawaitQueuedTask.Run(()=>DeviceLocationService.Instance.Open(newSrc,props));
Get the Current Device Location Source
varsource=DeviceLocationService.Instance.GetSource();if(source==null){//There is no current source}
Close the Current Device Location Source
//Is there a current device source?varsrc=DeviceLocationService.Instance.GetSource();if(src==null){return;//no current source}awaitQueuedTask.Run(()=>DeviceLocationService.Instance.Close());
Get Current Device Location Source and Properties
// Check if a device is connectedboolisConnected=DeviceLocationService.Instance.IsDeviceConnected();if(!isConnected){return;// no device connected}// Get the current device location sourcevarsrc=DeviceLocationService.Instance.GetSource();// Check if the source is a SerialPortDeviceLocationSource//Set values for the SerialPortDeviceLocationSourceif(srcisSerialPortDeviceLocationSourceserialPortSrc){varport=serialPortSrc.ComPort;varantennaHeight=serialPortSrc.AntennaHeight;vardataBits=serialPortSrc.DataBits;varbaudRate=serialPortSrc.BaudRate;varparity=serialPortSrc.Parity;varstopBits=serialPortSrc.StopBits;varsr=awaitQueuedTask.Run(()=>{returnserialPortSrc.GetSpatialReference();});}//Get current device location properties being used.vardlProps=DeviceLocationService.Instance.GetProperties();varaccuracy=dlProps.AccuracyThreshold;
Update Properties on the Current Device Location Source
awaitQueuedTask.Run(()=>{// Get the current device location propertiesvardlProps=DeviceLocationService.Instance.GetProperties();//Change the accuracy thresholddlProps.AccuracyThreshold=22.5;// meters// Update the properties on the device location sourceDeviceLocationService.Instance.UpdateProperties(dlProps);});
Subscribe to DeviceLocationPropertiesUpdated event
DeviceLocationPropertiesUpdatedEvent.Subscribe(OnDeviceLocationPropertiesUpdated);// Event handler for DeviceLocationPropertiesUpdated event.staticvoidOnDeviceLocationPropertiesUpdated(DeviceLocationPropertiesUpdatedEventArgsargs){if(args==null){return;}varproperties=args.DeviceLocationProperties;// TODO - something with the updated properties}
Subscribe to DeviceLocationSourceChanged event
DeviceLocationSourceChangedEvent.Subscribe(OnDeviceLocationSourceChanged);// Event handler for DeviceLocationSourceChanged event.voidOnDeviceLocationSourceChanged(DeviceLocationSourceChangedEventArgsargs){if(args==null){return;}varsource=args.DeviceLocationSource;// TODO - something with the updated source properties}
Map Device Location Options
Enable/Disable Current Device Location Source For the Map
//Gets the current device location options used by the MapDeviceLocationServicevaroptions=MapDeviceLocationService.Instance.GetDeviceLocationOptions();//Device location visibility on the mapvarvisibility=options.DeviceLocationVisibility;//MappingDeviceLocationNavigationModevarnavMode=options.NavigationMode;//Heading of the location from the device points to the top of the screenvartrackUp=options.TrackUpNavigation;//Show accuracy buffer on the mapvarshowBuffer=options.ShowAccuracyBuffer;
Check if The Current Device Location Is Enabled On The Map
//Checks if the current device location source is enabled on the mapif(MapDeviceLocationService.Instance.IsDeviceLocationEnabled){//The Device Location Source is Enabled}
Set Current Map Device Location Options
awaitQueuedTask.Run(()=>{//Check there is a source first...if(DeviceLocationService.Instance.GetSource()==null){//Setting DeviceLocationOptions w/ no Device Location Source//Will throw an InvalidOperationExceptionreturn;}if(!MapDeviceLocationService.Instance.IsDeviceLocationEnabled){//Setting DeviceLocationOptions w/ no Device Location Enabled//Will throw an InvalidOperationExceptionreturn;}MapDeviceLocationService.Instance.SetDeviceLocationOptions(newMapDeviceLocationOptions(){DeviceLocationVisibility=true,NavigationMode=MappingDeviceLocationNavigationMode.KeepAtCenter,TrackUpNavigation=true});});
Zoom/Pan The Map To The Most Recent Location
awaitQueuedTask.Run(()=>{if(!MapDeviceLocationService.Instance.IsDeviceLocationEnabled){//Calling ZoomOrPanToCurrentLocation w/ no Device Location Enabled//Will throw an InvalidOperationExceptionreturn;}// true for zoom, false for panMapDeviceLocationService.Instance.ZoomOrPanToCurrentLocation(true);});
Add the Most Recent Location To A Graphics Layer
awaitQueuedTask.Run(()=>{// get the last locationvarpt=DeviceLocationService.Instance.GetCurrentSnapshot()?.GetPositionAsMapPoint();if(pt!=null){//Create a point symbolvarptSymbol=SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(125,125,0),10,SimpleMarkerStyle.Triangle);//Add a graphic to the graphics layergraphicsLayer.AddElement(pt,ptSymbol);//unselect itgraphicsLayer.ClearSelection();}});
Set map view to always be centered on the device location
// Get the MapDeviceLocationOptions currently used by the MapDeviceLocationServicevarcurrentOptions=MapDeviceLocationService.Instance.GetDeviceLocationOptions();if(currentOptions==null){return;}// Set the device location visibility on the map to truecurrentOptions.DeviceLocationVisibility=true;//Set the navigation mode to keep the device location at the center of the mapcurrentOptions.NavigationMode=MappingDeviceLocationNavigationMode.KeepAtCenter;//Sets the MapDeviceLocationOptions to be updates with these valuesawaitQueuedTask.Run(()=>MapDeviceLocationService.Instance.SetDeviceLocationOptions(currentOptions));
Subscribe to Location Snapshot event
SnapshotChangedEvent.Subscribe(args =>_=OnSnapshotChangedAsync(args));/// Handles changes to a snapshot by processing the provided snapshot data.asyncTaskOnSnapshotChangedAsync(SnapshotChangedEventArgsargs){if(args==null){return;}varsnapshot=args.SnapshotasNMEASnapshot;if(snapshot==null){return;}varpt=awaitQueuedTask.Run(()=>snapshot.GetPositionAsMapPoint());if(pt?.IsEmpty??true){return;}// access propertiesvaralt=snapshot.Altitude;vardt=snapshot.DateTime;varvdop=snapshot.VDOP;varhdop=snapshot.HDOP;// etc//TODO: use the snapshot}
Feature Masking
Get the Mask Geometry for a Feature
if(featureLayer==null){return;}varmv=MapView.Active;awaitQueuedTask.Run(()=>{using(vartable=featureLayer.GetTable()){using(varrc=table.Search()){//get the first feature...//...assuming at least one feature gets retrievedrc.MoveNext();varoid=rc.Current.GetObjectID();//Use DrawingOutlineType.BoundingEnvelope to retrieve a generalized//mask geometry or "Box". The mask will be in the same SpatRef as the mapvarmask_geom=featureLayer.GetDrawingOutline(oid,mv,DrawingOutlineType.Exact);//TODO - use the mask geometry...}}});