awaitQueuedTask.Run(()=>{varmap=MapFactory.Instance.CreateMap(mapName,basemap:Basemap.ProjectDefault);//TODO: use the map...});
Find a map within a project and open it
publicstaticasyncTask<Map>FindOpenExistingMapAsync(stringmapName){returnawaitQueuedTask.Run(async()=>{Mapmap=null;Projectproj=Project.Current;//Finding the first project item with name matches with mapNameMapProjectItemmpi=proj.GetItems<MapProjectItem>().FirstOrDefault(m =>m.Name.Equals(mapName,StringComparison.CurrentCultureIgnoreCase));if(mpi!=null){map=mpi.GetMap();//Opening the map in a mapviewawaitProApp.Panes.CreateMapPaneAsync(map);}returnmap;});}
Open a webmap
Mapmap=null;//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);}}
Get Map Panes
publicstaticIEnumerable<IMapPane>GetMapPanes(){//Sorted by Map UrireturnProApp.Panes.OfType<IMapPane>().OrderBy((mp)=>mp.MapView.Map.URI??mp.MapView.Map.Name);}
Get the Unique List of Maps From the Map Panes
publicstaticIReadOnlyList<Map>GetMapsFromMapPanes(){//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);returnuniqueMaps;}
Change the Map name
MapView.Active.Map.SetName("Test");
Renames the caption of the pane
ProApp.Panes.ActivePane.Caption="Caption";
Convert Map to Local Scene
//Note: Run within the context of QueuedTask.RunboolcanConvertMap=MapFactory.Instance.CanConvertMap(map,MapConversionType.SceneLocal);if(canConvertMap)MapFactory.Instance.ConvertMap(map,MapConversionType.SceneLocal,true);
Get Basemaps
//Basemaps stored locally in the project. This is usually an empty collectionstringlocalBasemapTypeID="cim_map_basemap";varlocalBasemaps=awaitQueuedTask.Run(()=>{varmapContainer=Project.Current.GetProjectItemContainer("Map");returnmapContainer.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]));
Clip Map to the provided clip polygon
//Run within QueuedTaskvarmap=MapView.Active.Map;//A layer to use for the clip extentvarlyrOfInterest=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l =>l.Name=="TestPoly").FirstOrDefault();//Get the polygon to use to clip the mapvarextent=lyrOfInterest.QueryExtent();varpolygonForClipping=PolygonBuilder.CreatePolygon(extent);//Clip the map using the layer's extentmap.SetClipGeometry(polygonForClipping,SymbolFactory.Instance.ConstructLineSymbol(SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB,2.0,SimpleLineStyle.Dash)));
Clear the current map clip geometry
//Run within QueuedTaskvarmap=MapView.Active.Map;//Clear the Map clip.//If no clipping is set then this is a no-op.map.ClearClipGeometry();
Get the map clipping geometry
varmap=MapView.Active.Map;//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=map.GetClipGeometry();//You can use the polygon returned//For example: We make a polygon graphic element and add it to a Graphics Layer.vargl=map.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;//Must be on the QueuedTask.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
//var map = MapView.Active.Map;//Must be on the QueuedTask.Run()//Linear location unit formats are not included if the map sr//is geographic.varloc_units=map.GetAvailableLocationUnitFormats();
Format a Location Using the Current Map Location Unit
varmv=MapView.Active;varmap=mv.Map;QueuedTask.Run(()=>{//Get the current view camera locationvarcenter_pt=newCoordinate2D(mv.Camera.X,mv.Camera.Y);//Get the current location unitvarloc_unit=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
varmv=MapView.Active;varmap=mv.Map;QueuedTask.Run(()=>{//Get the list of available location unit formats//for the current mapvarloc_units=map.GetAvailableLocationUnitFormats();//arbitrarily use the last unit in the listmap.SetLocationUnitFormat(loc_units.Last());});
Get the Current Map Elevation Unit
//var map = MapView.Active.Map;//Must be on the QueuedTask.Run()//If the map is not a scene, the default Project distance//unit will be returnedvarelev_unit=map.GetElevationUnitFormat();varline=$"{elev_unit.DisplayName}, {elev_unit.UnitCode}";System.Diagnostics.Debug.WriteLine(line);
Get the Available List of Map Elevation Units
//var map = MapView.Active.Map;//Must be on the QueuedTask.Run()//If the map is not a scene, the list of current//Project distance units will be returnedvarelev_units=map.GetAvailableElevationUnitFormats();
Format an Elevation Using the Current Map Elevation Unit
varmv=MapView.Active;varmap=mv.Map;QueuedTask.Run(()=>{//Get the current elevation unit. If the map is not//a scene the default Project distance unit is returnedvarelev_unit=map.GetElevationUnitFormat();//Format the view camera elevationvarstr=elev_unit.FormatValue(mv.Camera.Z);System.Diagnostics.Debug.WriteLine($"Formatted elevation: {str}");});
Set the Elevation Unit for the Current Map
varmap=MapView.Active.Map;QueuedTask.Run(()=>{//Trying to set the elevation unit on a map other than//a scene will throw an InvalidOperationExceptionif(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());}});
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 service*/stringurl=@"c:\data\project.gdb\roads";//FeatureClass of a FileGeodatabaseUriuri=newUri(url);awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateLayer(uri,MapView.Active.Map));
Create layer with create-params
varflyrCreatnParam=newFeatureLayerCreationParams(newUri(@"c:\data\world.gdb\cities")){Name="World Cities",IsVisible=false,MinimumScale=1000000,MaximumScale=5000,DefinitionFilter=newCIMDefinitionFilter(){DefinitionExpression="Population > 100000",Name="More than 100k"},RendererDefinition=newSimpleRendererDefinition(){SymbolTemplate=SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(255,0,0),8,SimpleMarkerStyle.Hexagon).MakeSymbolReference()}};varfeatureLayer=LayerFactory.Instance.CreateLayer<FeatureLayer>(flyrCreatnParam,map,LayerPosition.AutoArrange);
Create FeatureLayer and add to Map using LayerCreationParams
//Note: Call within QueuedTask.Run()varlayerDoc=newLayerDocument(@"E:\Data\SDK\Default2DPointSymbols.lyrx");varcreateParams=newLayerCreationParams(layerDoc.GetCIMLayerDocument());LayerFactory.Instance.CreateLayer<FeatureLayer>(createParams,MapView.Active.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=LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParamsVisibility,MapView.Active.Map);
Create FeatureLayer with a Renderer
//Note: Call within QueuedTask.Run()//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=LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParams,MapView.Active.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,DefinitionFilter=newCIMDefinitionFilter(){Name="CACities",DefinitionExpression="STATE_NAME = 'California'"}};//Create the layer with the feature layer parameters and add it to the active mapvarcreatedFCWithQueryDefn=LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParamsQueryDefn,MapView.Active.Map);
Add MapNotes to the active map
//Gets the collection of layer template packages installed with Pro for use with mapsvaritems=MapView.Active.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;awaitQueuedTask.Run(()=>{//Create a feature layer for the map notevarlayer=LayerFactory.Instance.CreateLayer<Layer>(layer_params,MapView.Active.Map);});}
Apply Symbology from a Layer in the TOC
//Note: Call within QueuedTask.Run()if(MapView.Active.Map==null)return;//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();//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,MapView.Active.Map,LayerPosition.AutoArrange);
Create a new SubTypeGroupLayer
varsubtypeGroupLayerCreateParam=newSubtypeGroupLayerCreationParams(newUri(@"c:\data\SubtypeAndDomain.gdb\Fittings"));// Define Subtype layerssubtypeGroupLayerCreateParam.SubtypeLayers=newList<SubtypeFeatureLayerCreationParams>(){//define first subtype layer with unique value renderernewSubtypeFeatureLayerCreationParams(){SubtypeId=1,RendererDefinition=newUniqueValueRendererDefinition(newstring[]{"type"})},//define second subtype layer with simple symbol renderernewSubtypeFeatureLayerCreationParams(){SubtypeId=2,RendererDefinition=newSimpleRendererDefinition(){SymbolTemplate=SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(255,0,0),8,SimpleMarkerStyle.Hexagon).MakeSymbolReference()}}};// Define additional parameterssubtypeGroupLayerCreateParam.DefinitionFilter=newCIMDefinitionFilter(){Name="IsActive",DefinitionExpression="Enabled = 1"};subtypeGroupLayerCreateParam.IsVisible=true;subtypeGroupLayerCreateParam.MinimumScale=50000;SubtypeGroupLayersubtypeGroupLayer2=LayerFactory.Instance.CreateLayer<SubtypeGroupLayer>(subtypeGroupLayerCreateParam,MapView.Active.Map);
Create layer from a lyrx file
varlyrDocFromLyrxFile=newLayerDocument(@"d:\data\cities.lyrx");varcimLyrDoc=lyrDocFromLyrxFile.GetCIMLayerDocument();//modifying its renderer symbol to redvarr=((CIMFeatureLayer)cimLyrDoc.LayerDefinitions[0]).RendererasCIMSimpleRenderer;r.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,LayerPosition.AutoArrange);
Apply Symbology to a layer from a Layer file
//Note: Run within QueuedTask.Run//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.featureLayer?.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 mapawaitQueuedTask.Run(()=>{varlayer=LayerFactory.Instance.CreateLayer(connection,MapView.Active.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 mapawaitQueuedTask.Run(()=>{Layerlayer=LayerFactory.Instance.CreateLayer(cIMStandardDataConnection,MapView.Active.Map);});
Create a query layer
awaitQueuedTask.Run(()=>{Mapmap=MapView.Active.Map;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"};FeatureLayerflyr=(FeatureLayer)LayerFactory.Instance.CreateLayer(sqldc,map,layerName:"States");});
Create a feature layer with class breaks renderer with defaults
awaitQueuedTask.Run(()=>LayerFactory.Instance.CreateFeatureLayer(newUri(@"c:\data\countydata.gdb\counties"),MapView.Active.Map,layerName:"Population Density (sq mi) Year 2010",rendererDefinition:newGraduatedColorsRendererDefinition("POP10_SQMI")));
Move a layer in the 2D group to the 3D Group in a Local Scene
//The layer in the 2D group to move to the 3D Group in a Local Scenevarlayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();QueuedTask.Run(()=>{//Get the layer's definitionvarlyrDefn=layer.GetDefinition()asCIMBasicFeatureLayer;//setting this property moves the layer to 3D group in a scenelyrDefn.IsFlattened=false;//Set the definition back to the layerlayer.SetDefinition(lyrDefn);});
Change the underlying data source of a feature layer - same workspace type
//This is the existing layer for which we want to switch the underlying datasourcevarlyr=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();QueuedTask.Run(()=>{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 mapFeatureLayerflyr=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();//first feature layerDatastoredataStore=flyr.GetFeatureClass().GetDatastore();//getting datasourceGeodatabasegeodatabase=dataStoreasGeodatabase;//casting to Geodatabaseif(geodatabase==null)return;VersionManagerversionManager=geodatabase.GetVersionManager();ArcGIS.Core.Data.VersioncurrentVersion=versionManager.GetCurrentVersion();//Getting all available versions except the current oneIEnumerable<ArcGIS.Core.Data.Version>versions=versionManager.GetVersions().Where(v =>!v.GetName().Equals(currentVersion.GetName(),StringComparison.CurrentCultureIgnoreCase));//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 versionMapView.Active.Map.ChangeVersion(currentVersion,toVersion);}});
Querying a feature layer
varcount=awaitQueuedTask.Run(()=>{QueryFilterqf=newQueryFilter(){WhereClause="Class = 'city'"};//Getting the first selected feature layer of the map viewvarflyr=(FeatureLayer)MapView.Active.GetSelectedLayers().OfType<FeatureLayer>().FirstOrDefault();using(RowCursorrows=flyr.Search(qf))//execute{//Looping through to countinti=0;while(rows.MoveNext())i++;returni;}});MessageBox.Show(String.Format("Total features that matched the search criteria: {0}",count));
Update a map's basemap layer
aMap.SetBasemapLayers(Basemap.Gray);
Remove basemap layer from a map
aMap.SetBasemapLayers(Basemap.None);
Find a layer
//Finds layers by name and returns a read only list of LayersIReadOnlyList<Layer>layers=aMap.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)");
Retrieve the values of selected cell in the attribute table
if(FrameworkApplication.Panes.ActivePaneisITablePanetablePane){varmapMember=tablePane.MapMember;varoid=tablePane.ActiveObjectID;if(oid.HasValue&&oid.Value!=-1&&mapMember!=null){varactiveField=tablePane.ActiveColumn;returnQueuedTask.Run<object>(()=>{// TODO: Use core objects to retrieve record and get valuereturnnull;});}}
Get the attribute rotation field of a layer
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();QueuedTask.Run(()=>{varcimRenderer=featureLayer.GetRenderer()asCIMUniqueValueRenderer;varcimRotationVariable=cimRenderer.VisualVariables.OfType<CIMRotationVisualVariable>().FirstOrDefault();varrotationInfoZ=cimRotationVariable.VisualVariableInfoZ;varrotationExpression=rotationInfoZ.ValueExpressionInfo.Expression;// this expression stores the field name });
Enable labeling on a layer
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// toggle the label visibilityfeatureLayer.SetLabelVisibility(!featureLayer.IsLabelVisible);});
Access the display field for a layer
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.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;});
Find connected attribute field for rotation
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.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"
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.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
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(()=>{// change the layer cache type to maximum agefeatureLayer.SetDisplayCacheType(ArcGIS.Core.CIM.DisplayCacheType.MaxAge);// change from the default 5 min to 2 minfeatureLayer.SetDisplayCacheMaxAge(TimeSpan.FromMinutes(2));});
Change the layer selection color
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.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.Active.SelectFeatures(MapView.Active.Extent);});
Removes all layers that are unchecked
varmap=MapView.Active.Map;if(map==null)return;//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(vargroupLayeringroupLayers){//Get layers that not visible within the groupvarlayers=groupLayer.Layers.Where(l =>l.IsVisible==false).ToList();//Remove all the layers that are not visible within the groupawaitQueuedTask.Run(()=>map.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 groupawaitQueuedTask.Run(()=>map.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 visibleawaitQueuedTask.Run(()=>map.RemoveLayers(notAGroupAndUnCheckedLayers));
Remove empty groups
varmap=MapView.Active.Map;if(map==null)return;//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 groupawaitQueuedTask.Run(()=>map.RemoveLayer(group));}}
Create and apply Abbreviation Dictionary in the Map Definition to a layer
publicstaticvoidCreateDictionary(){//Get the map's defintionvarmapDefn=MapView.Active.Map.GetDefinition();//Get the Map's Maplex labelling engine propertiesvarmapDefnPlacementProps=mapDefn.GeneralPlacementPropertiesasCIMMaplexGeneralPlacementProperties;//Define the abbreaviations we need in an array List<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 defintion MapView.Active.Map.SetDefinition(mapDefn);}privatestaticvoidApplyDictionary(){varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First();QueuedTask.Run(()=>{//Creates Abbreviation dictionary and adds to Map Defintion CreateDictionary();//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 dictionary CIMGeneralPlacementPropertieslabelEngine=MapView.Active.Map.GetDefinition().GeneralPlacementProperties;theLabelClass.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);});}
Metadata
Get and Set Map Metadata
varmap=MapView.Active.Map;if(map==null)return;//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
MapMembermapMember=map.GetLayersAsFlattenedList().FirstOrDefault();//Search for only layers/tables here if needed.if(mapMember==null)return;//Gets whether or not the MapMember stores its own metadata or uses metadata retrieved//from its source. This method must be called on the MCT. Use QueuedTask.RunbooldoesUseSourceMetadata=mapMember.GetUseSourceMetadata();//Sets whether or not the MapMember will use its own metadata or the metadata from//its underyling source (if it has one). This method must be called on the MCT.//Use QueuedTask.RunmapMember.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);
Renderers
Set unique value renderer to the selected feature layer of the active map
awaitQueuedTask.Run(()=>{String[]fields=newstring[]{"Type"};//field to be used to retrieve unique valuesCIMPointSymbolpointSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,16.0,SimpleMarkerStyle.Pushpin);//constructing a point symbol as a template symbolCIMSymbolReferencesymbolPointTemplate=pointSym.MakeSymbolReference();//constructing renderer definition for unique value rendererUniqueValueRendererDefinitionuniqueValueRendererDef=newUniqueValueRendererDefinition(fields,symbolPointTemplate);//creating a unique value renderervarflyr=MapView.Active.GetSelectedLayers()[0]asFeatureLayer;CIMUniqueValueRendereruniqueValueRenderer=(CIMUniqueValueRenderer)flyr.CreateRenderer(uniqueValueRendererDef);//setting the renderer to the feature layerflyr.SetRenderer(uniqueValueRenderer);});
Create a UniqueValueRenderer to specify symbols to values
returnQueuedTask.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";StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(s =>s.Name==colorBrewerSchemesName);stringcolorRampName="Heat Map 4 - Semitransparent";IList<ColorRampStyleItem>colorRampList=awaitQueuedTask.Run(()=>{returnstyle.SearchColorRamps(colorRampName);});ColorRampStyleItemcolorRamp=colorRampList[0];awaitQueuedTask.Run(()=>{//defining a heatmap renderer that uses values from Population field as the weightsHeatMapRendererDefinitionheatMapDef=newHeatMapRendererDefinition(){Radius=20,WeightField="Population",ColorRamp=colorRamp.ColorRamp,RendereringQuality=8,UpperLabel="High Density",LowerLabel="Low Density"};FeatureLayerflyr=MapView.Active.Map.Layers[0]asFeatureLayer;CIMHeatMapRendererheatMapRndr=(CIMHeatMapRenderer)flyr.CreateRenderer(heatMapDef);flyr.SetRenderer(heatMapRndr);});
Create an Unclassed Renderer
stringcolorBrewerSchemesName="ArcGIS Colors";StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(s =>s.Name==colorBrewerSchemesName);stringcolorRampName="Heat Map 4 - Semitransparent";IList<ColorRampStyleItem>colorRampList=awaitQueuedTask.Run(()=>{returnstyle.SearchColorRamps(colorRampName);});ColorRampStyleItemcolorRamp=colorRampList[0];awaitQueuedTask.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.ColorRamp,"Highest","Lowest",5000000,50000){//drawing features with null values with a different symbolShowNullValues=true,NullValueLabel="Unknown"};CIMPointSymbolnullSym=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,16.0,SimpleMarkerStyle.Circle);unclassRndrDef.NullValueSymbol=nullSym.MakeSymbolReference();FeatureLayerflyr=MapView.Active.Map.Layers[0]asFeatureLayer;CIMClassBreaksRenderercbRndr=(CIMClassBreaksRenderer)flyr.CreateRenderer(unclassRndrDef);flyr.SetRenderer(cbRndr);});
Create a Proportion Renderer with max and min symbol size capped
stringcolorBrewerSchemesName="ArcGIS Colors";StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(s =>s.Name==colorBrewerSchemesName);stringcolorRampName="Heat Map 4 - Semitransparent";IList<ColorRampStyleItem>colorRampList=awaitQueuedTask.Run(()=>{returnstyle.SearchColorRamps(colorRampName);});ColorRampStyleItemcolorRamp=colorRampList[0];awaitQueuedTask.Run(()=>{CIMPointSymbolpointSym=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 pointProportionalRendererDefinitionprDef=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};FeatureLayerflyr=MapView.Active.Map.Layers[0]asFeatureLayer;CIMProportionalRendererpropRndr=(CIMProportionalRenderer)flyr.CreateRenderer(prDef);flyr.SetRenderer(propRndr);});
Create a True Proportion Renderer
stringcolorBrewerSchemesName="ArcGIS Colors";StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(s =>s.Name==colorBrewerSchemesName);stringcolorRampName="Heat Map 4 - Semitransparent";IList<ColorRampStyleItem>colorRampList=awaitQueuedTask.Run(()=>{returnstyle.SearchColorRamps(colorRampName);});ColorRampStyleItemcolorRamp=colorRampList[0];awaitQueuedTask.Run(()=>{CIMPointSymbolpointSym=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);FeatureLayerflyr=MapView.Active.Map.Layers[0]asFeatureLayer;CIMProportionalRendererpropRndr=(CIMProportionalRenderer)flyr.CreateRenderer(prDef);flyr.SetRenderer(propRndr);});
Arcade
Modify renderer using Arcade
varlyr=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(f =>f.ShapeType==esriGeometryType.esriGeometryPolygon);if(lyr==null)return;QueuedTask.Run(()=>{// GetRenderer from Layer (assumes it is a unique value renderer)varuvRenderer=lyr.GetRenderer()asCIMUniqueValueRenderer;if(uvRenderer==null)return;//layer has STATE_NAME field//community sample Data\Admin\AdminSample.aprxstringexpression="if ($view.scale > 21000000) { return $feature.STATE_NAME } else { return 'All' }";CIMExpressionInfoupdatedExpressionInfo=newCIMExpressionInfo{Expression=expression,Title="Custom"// can be any string used for UI purpose.};//set the renderer's expressionuvRenderer.ValueExpressionInfo=updatedExpressionInfo;//SetRenderer on Layerlyr.SetRenderer(uvRenderer);});
Modify label expression using Arcade
varlyr=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(f =>f.ShapeType==esriGeometryType.esriGeometryPolygon);if(lyr==null)return;QueuedTask.Run(()=>{//Get the layer's definition//community sample Data\Admin\AdminSample.aprxvarlyrDefn=lyr.GetDefinition()asCIMFeatureLayer;if(lyrDefn==null)return;//Get the label classes - we need the first onevarlistLabelClasses=lyrDefn.LabelClasses.ToList();vartheLabelClass=listLabelClasses.FirstOrDefault();//set the label class Expression to use the Arcade expressiontheLabelClass.Expression="return $feature.STATE_NAME + TextFormatting.NewLine + $feature.POP2000;";//Set the label definition back to the layer.lyr.SetDefinition(lyrDefn);});
Elevation Surface
Create a New Elevation Surface
//Note: call within QueuedTask.Run()//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 abovevarnewElevationSource=newArcGIS.Core.CIM.CIMElevationSource{VerticalUnit=ArcGIS.Core.Geometry.LinearUnit.Meters,DataConnection=serviceConnection,Name="WorldElevation/Terrain",Visibility=true};//The elevation surfacevarnewElevationSurface=newArcGIS.Core.CIM.CIMMapElevationSurface{Name="New Elevation Surface",BaseSources=newArcGIS.Core.CIM.CIMElevationSource[1]{newElevationSource},Visibility=true,ElevationMode=ElevationMode.CustomSurface,VerticalExaggeration=1,EnableSurfaceShading=false,SurfaceTINShadingMode=SurfaceTINShadingMode.Smooth,Expanded=false,MapElevationID="{3DEC3CC5-7C69-4132-A700-DCD5BDED14D6}"};//Get the active mapvarmap=MapView.Active.Map;//Get the active map's definitionvardefinition=map.GetDefinition();//Get the elevation surfaces defined in the mapvarlistOfElevationSurfaces=definition.ElevationSurfaces.ToList();//Add the new elevation surface listOfElevationSurfaces.Add(newElevationSurface);//Set the map definitions to ElevationSurface (this has the new elevation surface)definition.ElevationSurfaces=listOfElevationSurfaces.ToArray();//Set the map definitionmap.SetDefinition(definition);
Set a custom elevation surface to a Z-Aware layer
//Define the custom elevation surface to usevarlayerElevationSurface=newCIMLayerElevationSurface{MapElevationID="{3DEC3CC5-7C69-4132-A700-DCD5BDED14D6}"};//Get the layer's definitionvarlyrDefn=featureLayer.GetDefinition()asCIMBasicFeatureLayer;//Set the layer's elevation surfacelyrDefn.LayerElevation=layerElevationSurface;//Set the layer's definitionfeatureLayer.SetDefinition(lyrDefn);
Get Z values from a surface
vargeometry=awaitQueuedTask.Run<Geometry>(()=>{GeometrymapCentergeometry=MapView.Active.Map.CalculateFullExtent().Center;returnmapCentergeometry;});//Pass any Geometry type to GetZsFromSurfaceAsyncvarsurfaceZResult=awaitMapView.Active.Map.GetZsFromSurfaceAsync(geometry);returnsurfaceZResult;
Raster Layers
Create a raster layer
stringurl=@"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.rasterLayer=(RasterLayer)LayerFactory.Instance.CreateLayer(newUri(url),aMap);});
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(rColorizerisCIMRasterRGBColorizer){CIMRasterRGBColorizerrasterRGBColorizer=(CIMRasterRGBColorizer)rColorizer;// Update RGB colorizer properties.rasterRGBColorizer.StretchType=RasterStretchType.ESRI;// Update the raster layer with the changed colorizer.rasterLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);}});
Check if a certain colorizer can be applied to a raster layer
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.boolisTrue_ContainTheColorizerType=applicableColorizerList.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
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 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();awaitQueuedTask.Run(()=>{// 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=LayerFactory.Instance.CreateRasterLayer(newUri(url),aMap,0,layerName,stretchColorizerDef)asRasterLayer;});
Mosaic Layers
Create a mosaic layer
MosaicLayermosaicLayer=null;stringurl=@"C:\Images\countries.gdb\Italy";awaitQueuedTask.Run(()=>{// 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=(MosaicLayer)LayerFactory.Instance.CreateLayer(newUri(url),aMap);});
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(rColorizerisCIMRasterRGBColorizer){// Cast colorizer type from CIMRasterColorizer into CIMRasterRGBColorizer.CIMRasterRGBColorizerrasterRGBColorizer=(CIMRasterRGBColorizer)rColorizer;// Update RGB colorizer properties.rasterRGBColorizer.StretchType=RasterStretchType.ESRI;// Update the image sub-layer with the changed colorizer.mosaicImageSubLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);}});
Check if a certain colorizer can be applied to a mosaic layer
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.boolisTrue_ContainTheColorizerType=applicableColorizerList.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();awaitQueuedTask.Run(()=>{// 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=LayerFactory.Instance.CreateMosaicLayer(newUri(url),aMap,0,layerName,stretchColorizerDef)asMosaicLayer;});
Update the sort order (mosaic method) on a mosaic layer
awaitQueuedTask.Run(()=>{// Get the image sub-layer from the mosaic layer.ImageServiceLayermosaicImageSubLayer=(ImageServiceLayer)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.ImageServiceLayermosaicImageSublayer=(ImageServiceLayer)mosaicLayer.GetImageLayer();// Get the mosaic rule.CIMMosaicRulemosaicRule=mosaicImageSublayer.GetMosaicRule();// Set the Mosaic Operator to Mean.mosaicRule.MosaicOperatorType=RasterMosaicOperatorType.Mean;// Update the mosaic with the changed mosaic rule.mosaicImageSublayer.SetMosaicRule(mosaicRule);});
Image Service Layers
Create an image service layer
ImageServiceLayerisLayer=null;stringurl=@"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";awaitQueuedTask.Run(()=>{// Create an image service layer using the url for an image service.isLayer=(ImageServiceLayer)LayerFactory.Instance.CreateLayer(newUri(url),aMap);});
Update the raster colorizer on an image service layer
awaitQueuedTask.Run(()=>{// Get the colorizer from the image service layer.CIMRasterColorizerrasterColorizer=isLayer.GetColorizer();// Update the colorizer properties.rasterColorizer.Brightness=10;rasterColorizer.Contrast=-5;rasterColorizer.ResamplingType=RasterResamplingType.NearestNeighbor;// Update the image service layer with the changed colorizer.isLayer.SetColorizer(rasterColorizer);});
Update the RGB colorizer on an image service layer
awaitQueuedTask.Run(()=>{// Get the colorizer from the image service layer.CIMRasterColorizerrColorizer=isLayer.GetColorizer();// Check if the colorizer is an RGB colorizer.if(rColorizerisCIMRasterRGBColorizer){// Cast colorizer type from CIMRasterColorizer to CIMRasterRGBColorizer.CIMRasterRGBColorizerrasterRGBColorizer=(CIMRasterRGBColorizer)rColorizer;// Update RGB colorizer properties.rasterRGBColorizer.StretchType=RasterStretchType.ESRI;// Update the image service layer with the changed colorizer.isLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);}});
Check if a certain colorizer can be applied to an image service layer
awaitQueuedTask.Run(()=>{// Get the list of colorizers that can be applied to the imager service layer.IEnumerable<RasterColorizerType>applicableColorizerList=isLayer.GetApplicableColorizers();// Check if the RGB colorizer is part of the list.boolisTrue_ContainTheColorizerType=applicableColorizerList.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(isLayer.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=awaitisLayer.CreateColorizerAsync(stretchColorizerDef_default)asCIMRasterStretchColorizer;// Set the new colorizer on the image service layer.isLayer.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(isLayer.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=awaitisLayer.CreateColorizerAsync(stretchColorizerDef_custom)asCIMRasterStretchColorizer;// Set the new colorizer on the image service layer.isLayer.SetColorizer(newStretchColorizer_custom);}});
Create an image service layer with a new colorizer definition
// Create a new colorizer definition using default constructor.StretchColorizerDefinitionstretchColorizerDef=newStretchColorizerDefinition();awaitQueuedTask.Run(()=>{// Create an image service layer using the colorizer definition created above.ImageServiceLayerimageServiceLayer=LayerFactory.Instance.CreateRasterLayer(newUri(url),aMap,0,layerName,stretchColorizerDef)asImageServiceLayer;});
Update the sort order (mosaic method) on an image service layer
awaitQueuedTask.Run(()=>{// Get the mosaic rule of the image service.CIMMosaicRulemosaicRule=isLayer.GetMosaicRule();// Set the Mosaic Method to Center.mosaicRule.MosaicMethod=RasterMosaicMethod.Center;// Update the image service with the changed mosaic rule.isLayer.SetMosaicRule(mosaicRule);});
Update the resolve overlap (mosaic operator) on an image service layer
awaitQueuedTask.Run(()=>{// Get the mosaic rule of the image service.CIMMosaicRulemosaicingRule=isLayer.GetMosaicRule();// Set the Mosaic Operator to Mean.mosaicingRule.MosaicOperatorType=RasterMosaicOperatorType.Mean;// Update the image service with the changed mosaic rule.isLayer.SetMosaicRule(mosaicingRule);});
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 threadawaitQueuedTask.Run(()=>{//open the deviceDeviceLocationService.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 sourceawaitQueuedTask.Run(()=>{DeviceLocationService.Instance.Close();});
Get Current Device Location Source and Properties
boolisConnected=DeviceLocationService.Instance.IsDeviceConnected();varsrc=DeviceLocationService.Instance.GetSource();if(srcisSerialPortDeviceLocationSourceserialPortSrc){varport=serialPortSrc.ComPort;varantennaHeight=serialPortSrc.AntennaHeight;vardataBits=serialPortSrc.DataBits;varbaudRate=serialPortSrc.BaudRate;varparity=serialPortSrc.Parity;varstopBits=serialPortSrc.StopBits;// retrieving spatial reference needs the MCTvarsr=awaitQueuedTask.Run(()=>{returnserialPortSrc.GetSpatialReference();});}vardlProps=DeviceLocationService.Instance.GetProperties();varaccuracy=dlProps.AccuracyThreshold;
Update Properties on the Current Device Location Source
awaitQueuedTask.Run(()=>{vardlProps=DeviceLocationService.Instance.GetProperties();//Change the accuracy thresholddlProps.AccuracyThreshold=22.5;// metersDeviceLocationService.Instance.UpdateProperties(dlProps);});
Map Device Location Options
Enable/Disable Current Device Location Source For the Map
Check if The Current Device Location Is Enabled On The Map
if(MapDeviceLocationService.Instance.IsDeviceLocationEnabled){//The Device Location Source is Enabled}
Set Current Map Device Location Options
//Must be on the QueuedTask.Run()//Check there is a source first...if(DeviceLocationService.Instance.GetSource()==null)//Setting DeviceLocationOptions w/ no Device Location Source//Will throw an InvalidOperationExceptionreturn;varmap=MapView.Active.Map;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
//Must be on the QueuedTask.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
//var graphicsLayer = ... ;//Must be on the QueuedTask.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();}
Subscribe to Location Snapshot event
privatevoidSubscribeToEvents(){SnapshotChangedEvent.Subscribe(OnSnapshotChanged);}privatevoidOnSnapshotChanged(SnapshotChangedEventArgsargs){if(args==null)return;varsnapshot=args.SnapshotasNMEASnapshot;if(snapshot==null)return;QueuedTask.Run(()=>{varpt=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
varfeatureLayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<BasicFeatureLayer>().FirstOrDefault();if(featureLayer==null)return;varmv=MapView.Active;QueuedTask.Run(()=>{//get the first feature...//...assuming at least one feature gets selectedvarrc=featureLayer.GetTable().Search();rc.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.QueryDrawingOutline(oid,mv,DrawingOutlineType.Exact);//TODO - use the mask geometry...rc.Dispose();});
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 nameStyleProjectItemstyle=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";awaitQueuedTask.Run(()=>StyleHelper.CreateStyle(Project.Current,styleToCreate));
How to add a style to project
//For ArcGIS Pro system styles, just pass in the name of the style to add to the projectawaitQueuedTask.Run(()=>StyleHelper.AddStyle(Project.Current,"3D Vehicles"));//For custom styles, pass in the full path to the style file on diskstringcustomStyleToAdd=@"C:\Temp\CustomStyle.stylx";awaitQueuedTask.Run(()=>StyleHelper.AddStyle(Project.Current,customStyleToAdd));
How to remove a style from project
//For ArcGIS Pro system styles, just pass in the name of the style to remove from the projectawaitQueuedTask.Run(()=>StyleHelper.RemoveStyle(Project.Current,"3D Vehicles"));//For custom styles, pass in the full path to the style file on diskstringcustomStyleToAdd=@"C:\Temp\CustomStyle.stylx";awaitQueuedTask.Run(()=>StyleHelper.RemoveStyle(Project.Current,customStyleToAdd));
How to add a style item to a style
publicTaskAddStyleItemAsync(StyleProjectItemstyle,StyleItemitemToAdd){returnQueuedTask.Run(()=>{if(style==null||itemToAdd==null)thrownewSystem.ArgumentNullException();//Add the item to stylestyle.AddItem(itemToAdd);});}
How to remove a style item from a style
publicTaskRemoveStyleItemAsync(StyleProjectItemstyle,StyleItemitemToRemove){returnQueuedTask.Run(()=>{if(style==null||itemToRemove==null)thrownewSystem.ArgumentNullException();//Remove the item from stylestyle.RemoveItem(itemToRemove);});}
How to determine if a style can be upgraded
//Pass in the full path to the style file on diskpublicasyncTask<bool>CanUpgradeStyleAsync(stringstylePath){//Add the style to the current projectawaitQueuedTask.Run(()=>StyleHelper.AddStyle(Project.Current,stylePath));StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//returns true if style can be upgradedreturnstyle.CanUpgrade;}
How to determine if a style is read-only
//Pass in the full path to the style file on diskpublicasyncTask<bool>IsReadOnly(stringstylePath){//Add the style to the current projectawaitQueuedTask.Run(()=>StyleHelper.AddStyle(Project.Current,stylePath));StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//returns true if style is read-onlyreturnstyle.IsReadOnly;}
How to determine if a style is current
//Pass in the full path to the style file on diskpublicasyncTask<bool>IsCurrent(stringstylePath){//Add the style to the current projectawaitQueuedTask.Run(()=>StyleHelper.AddStyle(Project.Current,stylePath));StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//returns true if style matches the current Pro versionreturnstyle.IsCurrent;}
How to upgrade a style
//Pass in the full path to the style file on diskpublicasyncTask<bool>UpgradeStyleAsync(stringstylePath){boolsuccess=false;//Add the style to the current projectawaitQueuedTask.Run(()=>StyleHelper.AddStyle(Project.Current,stylePath));StyleProjectItemstyle=Project.Current.GetItems<StyleProjectItem>().First(x =>x.Path==stylePath);//Verify that style can be upgradedif(style.CanUpgrade){success=awaitQueuedTask.Run(()=>StyleHelper.UpgradeStyle(style));}//return true if style was upgradedreturnsuccess;}
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, GIFCIMMarkermarkerFromFile=awaitQueuedTask.Run(()=>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 imageImagenewImage=Image.FromFile(@"C:\PathToImage\Image.png");varstream=newSystem.IO.MemoryStream();newImage.Save(stream,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 circle markers on the line ends
//These methods must be called within the lambda passed to QueuedTask.RunvarlineStrokeRed=SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB,4.0);varmarkerCircle=SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB,12,SimpleMarkerStyle.Circle);markerCircle.MarkerPlacement=newCIMMarkerPlacementOnVertices(){AngleToLine=true,PlaceOnEndPoints=true,Offset=0};varlineSymbolWithCircles=newCIMLineSymbol(){SymbolLayers=newCIMSymbolLayer[2]{markerCircle,lineStrokeRed}};
How to construct a multilayer line symbol with an arrow head on the end
//These methods must be called within the lambda passed to QueuedTask.RunvarmarkerTriangle=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
CIMPolygonSymbolsymbol=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB);//Get symbol reference from the symbolCIMSymbolReferencesymbolReference=symbol.MakeSymbolReference();
Modify a point symbol created from a character marker
//create marker from the Font, char index,size,colorvarcimMarker=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);
Create a Swatch for a given symbol
//Note: call within QueuedTask.Run()CIMSymbolsymbol=SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB,1.0,SimpleMarkerStyle.Circle);//You can generate a swatch for a text symbols also.varsi=newSymbolStyleItem(){Symbol=symbol,PatchHeight=64,PatchWidth=64};returnsi.PreviewImage;
Lookup Symbol
//Note: Run within QueuedTask.Run//Get the selectionvarselection=featureLayer.GetSelection();//Get the first Object IDvarfirstOID=selection.GetObjectIDs().FirstOrDefault();//Determine whether the layer's renderer type supports symbol lookup.if(featureLayer.CanLookupSymbol()){//Looks up the symbol for the corresponding feature identified by the object id.varsymbol=featureLayer.LookupSymbol(firstOID,MapView.Active);varjSon=symbol.ToJson();//Create a JSON encoding of the symbol//Do something with symbol}
Symbol search
How to search for a specific item in a style
publicTask<SymbolStyleItem>GetSymbolFromStyleAsync(StyleProjectItemstyle,stringkey){returnQueuedTask.Run(()=>{if(style==null)thrownewSystem.ArgumentNullException();//Search for a specific point symbol in styleSymbolStyleItemitem=(SymbolStyleItem)style.LookupItem(StyleItemType.PointSymbol,key);returnitem;});}
How to search for point symbols in a style
publicTask<IList<SymbolStyleItem>>GetPointSymbolsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for point symbolsreturnQueuedTask.Run(()=>style.SearchSymbols(StyleItemType.PointSymbol,searchString));}
How to search for line symbols in a style
publicTask<IList<SymbolStyleItem>>GetLineSymbolsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for line symbolsreturnQueuedTask.Run(()=>style.SearchSymbols(StyleItemType.LineSymbol,searchString));}
How to search for polygon symbols in a style
publicasyncTask<IList<SymbolStyleItem>>GetPolygonSymbolsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for polygon symbolsreturnawaitQueuedTask.Run(()=>style.SearchSymbols(StyleItemType.PolygonSymbol,searchString));}
How to search for colors in a style
publicasyncTask<IList<ColorStyleItem>>GetColorsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for colorsreturnawaitQueuedTask.Run(()=>style.SearchColors(searchString));}
How to search for color ramps in a style
publicasyncTask<IList<ColorRampStyleItem>>GetColorRampsFromStyleAsync(StyleProjectItemstyle,stringsearchString){//StyleProjectItem can be "ColorBrewer Schemes (RGB)", "ArcGIS 2D"...if(style==null)thrownewSystem.ArgumentNullException();//Search for color ramps//Color Ramp searchString can be "Spectral (7 Classes)", "Pastel 1 (3 Classes)", "Red-Gray (10 Classes)"..returnawaitQueuedTask.Run(()=>style.SearchColorRamps(searchString));}
How to search for north arrows in a style
publicTask<IList<NorthArrowStyleItem>>GetNorthArrowsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for north arrowsreturnQueuedTask.Run(()=>style.SearchNorthArrows(searchString));}
How to search for scale bars in a style
publicTask<IList<ScaleBarStyleItem>>GetScaleBarsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for scale barsreturnQueuedTask.Run(()=>style.SearchScaleBars(searchString));}
How to search for label placements in a style
publicTask<IList<LabelPlacementStyleItem>>GetLabelPlacementsFromStyleAsync(StyleProjectItemstyle,stringsearchString){if(style==null)thrownewSystem.ArgumentNullException();//Search for standard label placementreturnQueuedTask.Run(()=>style.SearchLabelPlacements(StyleItemType.StandardLabelPlacement,searchString));}
Feature Layer Symbology
How to set symbol for a feature layer symbolized with simple renderer
publicTaskSetFeatureLayerSymbolAsync(FeatureLayerftrLayer,CIMSymbolsymbolToApply){if(ftrLayer==null||symbolToApply==null)thrownewSystem.ArgumentNullException();returnQueuedTask.Run(()=>{//Get simple renderer from the feature layerCIMSimpleRenderercurrentRenderer=ftrLayer.GetRenderer()asCIMSimpleRenderer;if(currentRenderer==null)return;//Set symbol's real world setting to be the same as that of the feature layersymbolToApply.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);//Update the symbol of the current simple renderercurrentRenderer.Symbol=symbolToApply.MakeSymbolReference();//Update the feature layer rendererftrLayer.SetRenderer(currentRenderer);});}
How to apply a symbol from style to a feature layer
publicTaskSetFeatureLayerSymbolFromStyleItemAsync(FeatureLayerftrLayer,SymbolStyleItemsymbolItem){if(ftrLayer==null||symbolItem==null)thrownewSystem.ArgumentNullException();returnQueuedTask.Run(()=>{//Get simple renderer from the feature layerCIMSimpleRenderercurrentRenderer=ftrLayer.GetRenderer()asCIMSimpleRenderer;if(currentRenderer==null)return;//Get symbol from the SymbolStyleItemCIMSymbolsymbol=symbolItem.Symbol;//Set symbol's real world setting to be the same as that of the feature layersymbol.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);//Update the symbol of the current simple renderercurrentRenderer.Symbol=symbol.MakeSymbolReference();//Update the feature layer rendererftrLayer.SetRenderer(currentRenderer);});}
How to apply a point symbol from a style to a feature layer
// var map = MapView.Active.Map;// if (map == null)// return;// var pointFeatureLayer =// map.GetLayersAsFlattenedList()// .OfType<FeatureLayer>()// .Where(fl => fl.ShapeType == esriGeometryType.esriGeometryPoint);// await ApplySymbolToFeatureLayerAsync(pointFeatureLayer.FirstOrDefault(), "Fire Station");publicTaskApplySymbolToFeatureLayerAsync(FeatureLayerfeatureLayer,stringsymbolName){returnQueuedTask.Run(async()=>{//Get the ArcGIS 2D System style from the ProjectvararcGIS2DStyle=Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s =>s.Name=="ArcGIS 2D");//Search for the symbolName style items within the ArcGIS 2D style project item.varitems=awaitQueuedTask.Run(()=>arcGIS2DStyle.SearchSymbols(StyleItemType.PointSymbol,symbolName));//Gets the CIMSymbolCIMSymbolsymbol=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 layersymbol.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);//Apply the symbol to the feature layer's current rendererrenderer.Symbol=symbol.MakeSymbolReference();//Appy the renderer to the feature layerfeatureLayer.SetRenderer(renderer);});}
How to apply a color ramp from a style to a feature layer