-
Notifications
You must be signed in to change notification settings - Fork 120
ProSnippets MapAuthoring
Uma Harano edited this page Jan 25, 2019
·
22 revisions
Language: C#
Subject: MapAuthoring
Contributor: ArcGIS Pro SDK Team <[email protected]>
Organization: esri, http://www.esri.com
Date: 1/23/2019
ArcGIS Pro: 2.3
Visual Studio: 2015, 2017
.NET Target Framework: 4.6.1
Map map = MapView.Active.Map;
await QueuedTask.Run(() =>
{
var map = MapFactory.Instance.CreateMap(mapName, basemap: Basemap.ProjectDefault);
//TODO: use the map...
});
public static async Task<Map> FindOpenExistingMapAsync(string mapName)
{
return await QueuedTask.Run(async () =>
{
Map map = null;
Project proj = Project.Current;
//Finding the first project item with name matches with mapName
MapProjectItem mpi =
proj.GetItems<MapProjectItem>()
.FirstOrDefault(m => m.Name.Equals(mapName, StringComparison.CurrentCultureIgnoreCase));
if (mpi != null)
{
map = mpi.GetMap();
//Opening the map in a mapview
await ProApp.Panes.CreateMapPaneAsync(map);
}
return map;
});
}
Map map = null;
//Assume we get the selected webmap from the Project pane's Portal tab
if (Project.Current.SelectedItems.Count > 0)
{
if (MapFactory.Instance.CanCreateMapFrom(Project.Current.SelectedItems[0]))
{
map = MapFactory.Instance.CreateMapFromItem(Project.Current.SelectedItems[0]);
await ProApp.Panes.CreateMapPaneAsync(map);
}
}
public static IEnumerable<IMapPane> GetMapPanes()
{
//Sorted by Map Uri
return ProApp.Panes.OfType<IMapPane>().OrderBy((mp) => mp.MapView.Map.URI ?? mp.MapView.Map.Name);
}
public static IReadOnlyList<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.
var mapPanes = ProApp.Panes.OfType<IMapPane>()
.GroupBy((mp) => mp.MapView.Map.URI).Select(grp => grp.FirstOrDefault());
List<Map> uniqueMaps = new List<Map>();
foreach (var pane in mapPanes)
uniqueMaps.Add(pane.MapView.Map);
return uniqueMaps;
}
MapView.Active.Map.SetName("Test");
ProApp.Panes.ActivePane.Caption = "Caption";
Map map = MapView.Active.Map;
IEnumerable<Layer> matches = map.GetLayersAsFlattenedList().Where(l => l.Name.IndexOf(partialName, StringComparison.CurrentCultureIgnoreCase) >= 0);
/*
* 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 = @"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
*/
string url = @"c:\data\project.gdb\roads"; //FeatureClass of a FileGeodatabase
Uri uri = new Uri(url);
await QueuedTask.Run(() => LayerFactory.Instance.CreateLayer(uri, MapView.Active.Map));
// Create a connection to the WMS server
var serverConnection = new CIMInternetServerConnection { URL = "URL of the WMS service" };
var connection = new CIMWMSServiceConnection { ServerConnection = serverConnection };
// Add a new layer to the map
await QueuedTask.Run(() =>
{
var layer = LayerFactory.Instance.CreateLayer(connection, MapView.Active.Map);
});
CIMStandardDataConnection cIMStandardDataConnection = new CIMStandardDataConnection()
{
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 map
await QueuedTask.Run(() =>
{
Layer layer = LayerFactory.Instance.CreateLayer(cIMStandardDataConnection, MapView.Active.Map);
});
//The layer in the 2D group to move to the 3D Group in a Local Scene
var layer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
QueuedTask.Run(() => {
//Get the layer's definition
var lyrDefn = layer.GetDefinition() as CIMBasicFeatureLayer;
//setting this property moves the layer to 3D group in a scene
lyrDefn.IsFlattened = false;
//Set the definition back to the layer
layer.SetDefinition(lyrDefn);
});
//Note: Run within the context of QueuedTask.Run
var localScene = MapFactory.Instance.CreateMap("3DMap", MapType.Scene, MapViewingMode.SceneLocal, basemap: Basemap.None);
//Get all the layers in the Active map you want to move over to the local scene
var lyrs = MapView.Active.Map.GetLayersAsFlattenedList();
//Move each of these layers to the new local scene
foreach (var lyr in lyrs)
{
LayerFactory.Instance.CopyLayer(lyr, localScene);
}
//Set all the layers in the scene to be in the 3D group
foreach (var sceneLyr in localScene.GetLayersAsFlattenedList().OfType<FeatureLayer>())
{
var lyrDefn = sceneLyr.GetDefinition() as CIMBasicFeatureLayer;
//setting this property moves the layer to 3D group in a scene
lyrDefn.IsFlattened = false;
//Set the definition back to the layer
sceneLyr.SetDefinition(lyrDefn);
}
//Note: call within QueuedTask.Run()
//Define a ServiceConnection to use for the new Elevation surface
var serverConnection = new CIMInternetServerConnection
{
Anonymous = true,
HideUserProperty = true,
URL = "https://elevation.arcgis.com/arcgis/services"
};
CIMAGSServiceConnection serviceConnection = new CIMAGSServiceConnection
{
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
var newElevationSource = new ArcGIS.Core.CIM.CIMElevationSource
{
VerticalUnit = ArcGIS.Core.Geometry.LinearUnit.Meters,
DataConnection = serviceConnection,
Name = "WorldElevation/Terrain",
Visibility = true
};
//The elevation surface
var newElevationSurface = new ArcGIS.Core.CIM.CIMMapElevationSurface
{
Name = "New Elevation Surface",
BaseSources = new ArcGIS.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 map
var map = MapView.Active.Map;
//Get the active map's definition
var definition = map.GetDefinition();
//Get the elevation surfaces defined in the map
var listOfElevationSurfaces = 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 definition
map.SetDefinition(definition);
//Define the custom elevation surface to use
var layerElevationSurface = new CIMLayerElevationSurface
{
MapElevationID = "{3DEC3CC5-7C69-4132-A700-DCD5BDED14D6}"
};
//Get the layer's definition
var lyrDefn = featureLayer.GetDefinition() as CIMBasicFeatureLayer;
//Set the layer's elevation surface
lyrDefn.LayerElevation = layerElevationSurface;
//Set the layer's definition
featureLayer.SetDefinition(lyrDefn);
var geometry = await QueuedTask.Run<Geometry>(() => {
Geometry mapCentergeometry = MapView.Active.Map.CalculateFullExtent().Center;
return mapCentergeometry;
});
//Pass any Geometry type to GetZsFromSurfaceAsync
var surfaceZResult = await MapView.Active.Map.GetZsFromSurfaceAsync(geometry);
return surfaceZResult;
await QueuedTask.Run(() =>
LayerFactory.Instance.CreateFeatureLayer(
new Uri(@"c:\data\countydata.gdb\counties"),
MapView.Active.Map,
layerName: "Population Density (sq mi) Year 2010",
rendererDefinition: new GraduatedColorsRendererDefinition("POP10_SQMI")
)
);
string colorBrewerSchemesName = "ColorBrewer Schemes (RGB)";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Greens (Continuous)";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];
await QueuedTask.Run(() =>
{
GraduatedColorsRendererDefinition gcDef = new GraduatedColorsRendererDefinition()
{
ClassificationField = "CROP_ACR07",
ClassificationMethod = ArcGIS.Core.CIM.ClassificationMethod.NaturalBreaks,
BreakCount = 6,
ColorRamp = colorRamp.ColorRamp,
SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol(
ColorFactory.Instance.GreenRGB, SimpleFillStyle.Solid, null).MakeSymbolReference(),
ExclusionClause = "CROP_ACR07 = -99",
ExclusionSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(
ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, null).MakeSymbolReference(),
ExclusionLabel = "No yield",
};
LayerFactory.Instance.CreateFeatureLayer(new Uri(@"c:\Data\CountyData.gdb\Counties"),
MapView.Active.Map, layerName: "Crop", rendererDefinition: gcDef);
});
await QueuedTask.Run(() =>
{
String[] fields = new string[] { "Type" }; //field to be used to retrieve unique values
CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(
ColorFactory.Instance.GreenRGB, 16.0, SimpleMarkerStyle.Pushpin); //constructing a point symbol as a template symbol
CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();
//constructing renderer definition for unique value renderer
UniqueValueRendererDefinition uniqueValueRendererDef = new UniqueValueRendererDefinition(fields, symbolPointTemplate);
//creating a unique value renderer
var flyr = MapView.Active.GetSelectedLayers()[0] as FeatureLayer;
CIMUniqueValueRenderer uniqueValueRenderer = (CIMUniqueValueRenderer)flyr.CreateRenderer(uniqueValueRendererDef);
//setting the renderer to the feature layer
flyr.SetRenderer(uniqueValueRenderer);
});
return QueuedTask.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 = new List<CIMUniqueValue> { new CIMUniqueValue { FieldValues = new string[] { "Alabama" } } };
CIMUniqueValueClass alabamaUniqueValueClass = new CIMUniqueValueClass
{
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 = new List<CIMUniqueValue> { new CIMUniqueValue { FieldValues = new string[] { "California" } } };
CIMUniqueValueClass californiaUniqueValueClass = new CIMUniqueValueClass
{
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 CIMUniqueValueClasses
List<CIMUniqueValueClass> listUniqueValueClasses = new List<CIMUniqueValueClass>
{
alabamaUniqueValueClass, californiaUniqueValueClass
};
//Create a list of CIMUniqueValueGroup
CIMUniqueValueGroup uvg = new CIMUniqueValueGroup
{
Classes = listUniqueValueClasses.ToArray(),
};
List<CIMUniqueValueGroup> listUniqueValueGroups = new List<CIMUniqueValueGroup> { uvg };
//Create the CIMUniqueValueRenderer
CIMUniqueValueRenderer uvr = new CIMUniqueValueRenderer
{
UseDefaultSymbol = true,
DefaultLabel = "all other values",
DefaultSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreyRGB).MakeSymbolReference(),
Groups = listUniqueValueGroups.ToArray(),
Fields = new string[] { "STATE_NAME" }
};
//Set the feature layer's renderer.
featureLayer.SetRenderer(uvr);
});
await QueuedTask.Run(() =>
{
Map map = MapView.Active.Map;
Geodatabase geodatabase = new Geodatabase(new DatabaseConnectionFile(new Uri(@"C:\Connections\mySDE.sde")));
CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection()
{
WorkspaceConnectionString = geodatabase.GetConnectionString(),
GeometryType = esriGeometryType.esriGeometryPolygon,
OIDFields = "OBJECTID",
Srid = "102008",
SqlQuery = "select * from MySDE.dbo.STATES",
Dataset = "States"
};
FeatureLayer flyr = (FeatureLayer)LayerFactory.Instance.CreateLayer(sqldc, map, layerName: "States");
});
CIMStandardDataConnection dataConnection = dataConnectionLayer.GetDataConnection() as CIMStandardDataConnection;
dataConnection.WorkspaceConnectionString = newConnectionString;
dataConnectionLayer.SetDataConnection(dataConnection);
await QueuedTask.Run(() =>
{
//Getting the current version name from the first feature layer of the map
FeatureLayer flyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(); //first feature layer
Datastore dataStore = flyr.GetFeatureClass().GetDatastore(); //getting datasource
Geodatabase geodatabase = dataStore as Geodatabase; //casting to Geodatabase
if (geodatabase == null)
return;
VersionManager versionManager = geodatabase.GetVersionManager();
ArcGIS.Core.Data.Version currentVersion = versionManager.GetCurrentVersion();
//Getting all available versions except the current one
IEnumerable<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 list
ArcGIS.Core.Data.Version toVersion = versions.FirstOrDefault();
if (toVersion != null)
{
//Changing version
MapView.Active.Map.ChangeVersion(currentVersion, toVersion);
}
});
var count = await QueuedTask.Run(() =>
{
QueryFilter qf = new QueryFilter()
{
WhereClause = "Class = 'city'"
};
//Getting the first selected feature layer of the map view
var flyr = (FeatureLayer)MapView.Active.GetSelectedLayers().OfType<FeatureLayer>().FirstOrDefault();
RowCursor rows = flyr.Search(qf);//execute
//Looping through to count
int i = 0;
while (rows.MoveNext()) i++;
return i;
});
MessageBox.Show(String.Format("Total features that matched the search criteria: {0}", count));
string url = @"C:\Images\Italy.tif";
await QueuedTask.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(new Uri(url), aMap);
});
await QueuedTask.Run(() =>
{
// Get the colorizer from the raster layer.
CIMRasterColorizer rasterColorizer = 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);
});
await QueuedTask.Run(() =>
{
// Get the colorizer from the raster layer.
CIMRasterColorizer rColorizer = rasterLayer.GetColorizer();
// Check if the colorizer is an RGB colorizer.
if (rColorizer is CIMRasterRGBColorizer)
{
CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)rColorizer;
// Update RGB colorizer properties.
rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
// Update the raster layer with the changed colorizer.
rasterLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
}
});
await QueuedTask.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.
bool isTrue_ContainTheColorizerType =
applicableColorizerList.Contains(RasterColorizerType.RGBColorizer);
});
await QueuedTask.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.
StretchColorizerDefinition stretchColorizerDef_default = new StretchColorizerDefinition();
// Create a new Stretch colorizer using the colorizer definition created above.
CIMRasterStretchColorizer newStretchColorizer_default =
await rasterLayer.CreateColorizerAsync(stretchColorizerDef_default) as CIMRasterStretchColorizer;
// Set the new colorizer on the raster layer.
rasterLayer.SetColorizer(newStretchColorizer_default);
}
});
await QueuedTask.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.
StretchColorizerDefinition stretchColorizerDef_custom =
new StretchColorizerDefinition(1, RasterStretchType.ESRI, 2, colorRamp);
// Create a new stretch colorizer using the colorizer definition created above.
CIMRasterStretchColorizer newStretchColorizer_custom =
await rasterLayer.CreateColorizerAsync(stretchColorizerDef_custom) as CIMRasterStretchColorizer;
// Set the new colorizer on the raster layer.
rasterLayer.SetColorizer(newStretchColorizer_custom);
}
});
// Create a new stretch colorizer definition using default constructor.
StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition();
await QueuedTask.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.
RasterLayer rasterLayerfromURL =
LayerFactory.Instance.CreateRasterLayer(new Uri(url), aMap, 0, layerName, stretchColorizerDef) as RasterLayer;
});
MosaicLayer mosaicLayer = null;
string url = @"C:\Images\countries.gdb\Italy";
await QueuedTask.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(new Uri(url), aMap);
});
await QueuedTask.Run(() =>
{
// Get the image sub-layer from the mosaic layer.
ImageMosaicSubLayer mosaicImageSubLayer = mosaicLayer.GetImageLayer();
// Get the colorizer from the image sub-layer.
CIMRasterColorizer rasterColorizer = 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);
});
await QueuedTask.Run(() =>
{
// Get the image sub-layer from the mosaic layer.
ImageMosaicSubLayer mosaicImageSubLayer = mosaicLayer.GetImageLayer();
// Get the colorizer from the image sub-layer.
CIMRasterColorizer rColorizer = mosaicImageSubLayer.GetColorizer();
// Check if the colorizer is an RGB colorizer.
if (rColorizer is CIMRasterRGBColorizer)
{
// Cast colorizer type from CIMRasterColorizer into CIMRasterRGBColorizer.
CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)rColorizer;
// Update RGB colorizer properties.
rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
// Update the image sub-layer with the changed colorizer.
mosaicImageSubLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
}
});
await QueuedTask.Run(() =>
{
// Get the image sub-layer from the mosaic layer.
ImageMosaicSubLayer mosaicImageSubLayer = 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.
bool isTrue_ContainTheColorizerType =
applicableColorizerList.Contains(RasterColorizerType.RGBColorizer);
});
await QueuedTask.Run(async () =>
{
// Get the image sub-layer from the mosaic layer.
ImageMosaicSubLayer mosaicImageSubLayer = 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.
StretchColorizerDefinition stretchColorizerDef_default = new StretchColorizerDefinition();
// Create a new Stretch colorizer using the colorizer definition created above.
CIMRasterStretchColorizer newStretchColorizer_default =
await mosaicImageSubLayer.CreateColorizerAsync(stretchColorizerDef_default) as CIMRasterStretchColorizer;
// Set the new colorizer on the image sub-layer.
mosaicImageSubLayer.SetColorizer(newStretchColorizer_default);
}
});
await QueuedTask.Run(async () =>
{
// Get the image sub-layer from the mosaic layer.
ImageMosaicSubLayer mosaicImageSubLayer = 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.
StretchColorizerDefinition stretchColorizerDef_custom =
new StretchColorizerDefinition(1, RasterStretchType.ESRI, 2, colorRamp);
// Create a new stretch colorizer using the colorizer definition created above.
CIMRasterStretchColorizer newStretchColorizer_custom =
await mosaicImageSubLayer.CreateColorizerAsync(stretchColorizerDef_custom) as CIMRasterStretchColorizer;
// Set the new colorizer on the image sub-layer.
mosaicImageSubLayer.SetColorizer(newStretchColorizer_custom);
}
});
// Create a new colorizer definition using default constructor.
StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition();
await QueuedTask.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.
MosaicLayer newMosaicLayer =
LayerFactory.Instance.CreateMosaicLayer(new Uri(url), aMap, 0, layerName, stretchColorizerDef) as MosaicLayer;
});
await QueuedTask.Run(() =>
{
// Get the image sub-layer from the mosaic layer.
ImageServiceLayer mosaicImageSubLayer = (ImageServiceLayer)mosaicLayer.GetImageLayer();
// Get the mosaic rule.
CIMMosaicRule mosaicingRule = mosaicImageSubLayer.GetMosaicRule();
// Set the Mosaic Method to Center.
mosaicingRule.MosaicMethod = RasterMosaicMethod.Center;
// Update the mosaic with the changed mosaic rule.
mosaicImageSubLayer.SetMosaicRule(mosaicingRule);
});
await QueuedTask.Run(() =>
{
// Get the image sub-layer from the mosaic layer.
ImageServiceLayer mosaicImageSublayer = (ImageServiceLayer)mosaicLayer.GetImageLayer();
// Get the mosaic rule.
CIMMosaicRule mosaicRule = mosaicImageSublayer.GetMosaicRule();
// Set the Mosaic Operator to Mean.
mosaicRule.MosaicOperatorType = RasterMosaicOperatorType.Mean;
// Update the mosaic with the changed mosaic rule.
mosaicImageSublayer.SetMosaicRule(mosaicRule);
});
ImageServiceLayer isLayer = null;
string url =
@"http://imagery.arcgisonline.com/arcgis/services/LandsatGLS/GLS2010_Enhanced/ImageServer";
await QueuedTask.Run(() =>
{
// Create an image service layer using the url for an image service.
isLayer = (ImageServiceLayer)LayerFactory.Instance.CreateLayer(new Uri(url), aMap);
});
await QueuedTask.Run(() =>
{
// Get the colorizer from the image service layer.
CIMRasterColorizer rasterColorizer = 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);
});
await QueuedTask.Run(() =>
{
// Get the colorizer from the image service layer.
CIMRasterColorizer rColorizer = isLayer.GetColorizer();
// Check if the colorizer is an RGB colorizer.
if (rColorizer is CIMRasterRGBColorizer)
{
// Cast colorizer type from CIMRasterColorizer to CIMRasterRGBColorizer.
CIMRasterRGBColorizer rasterRGBColorizer = (CIMRasterRGBColorizer)rColorizer;
// Update RGB colorizer properties.
rasterRGBColorizer.StretchType = RasterStretchType.ESRI;
// Update the image service layer with the changed colorizer.
isLayer.SetColorizer((CIMRasterColorizer)rasterRGBColorizer);
}
});
await QueuedTask.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.
bool isTrue_ContainTheColorizerType =
applicableColorizerList.Contains(RasterColorizerType.RGBColorizer);
});
Create a new colorizer based on a default colorizer definition and apply it to the image service layer
await QueuedTask.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.
StretchColorizerDefinition stretchColorizerDef_default = new StretchColorizerDefinition();
// Create a new Stretch colorizer using the colorizer definition created above.
CIMRasterStretchColorizer newStretchColorizer_default =
await isLayer.CreateColorizerAsync(stretchColorizerDef_default) as CIMRasterStretchColorizer;
// 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
await QueuedTask.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.
StretchColorizerDefinition stretchColorizerDef_custom =
new StretchColorizerDefinition(1, RasterStretchType.ESRI, 2, colorRamp);
// Create a new stretch colorizer using the colorizer definition created above.
CIMRasterStretchColorizer newStretchColorizer_custom =
await isLayer.CreateColorizerAsync(stretchColorizerDef_custom) as CIMRasterStretchColorizer;
// Set the new colorizer on the image service layer.
isLayer.SetColorizer(newStretchColorizer_custom);
}
});
// Create a new colorizer definition using default constructor.
StretchColorizerDefinition stretchColorizerDef = new StretchColorizerDefinition();
await QueuedTask.Run(() =>
{
// Create an image service layer using the colorizer definition created above.
ImageServiceLayer imageServiceLayer =
LayerFactory.Instance.CreateRasterLayer(new Uri(url), aMap, 0, layerName, stretchColorizerDef) as ImageServiceLayer;
});
await QueuedTask.Run(() =>
{
// Get the mosaic rule of the image service.
CIMMosaicRule mosaicRule = isLayer.GetMosaicRule();
// Set the Mosaic Method to Center.
mosaicRule.MosaicMethod = RasterMosaicMethod.Center;
// Update the image service with the changed mosaic rule.
isLayer.SetMosaicRule(mosaicRule);
});
await QueuedTask.Run(() =>
{
// Get the mosaic rule of the image service.
CIMMosaicRule mosaicingRule = isLayer.GetMosaicRule();
// Set the Mosaic Operator to Mean.
mosaicingRule.MosaicOperatorType = RasterMosaicOperatorType.Mean;
// Update the image service with the changed mosaic rule.
isLayer.SetMosaicRule(mosaicingRule);
});
string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];
await QueuedTask.Run(() =>
{
//defining a heatmap renderer that uses values from Population field as the weights
HeatMapRendererDefinition heatMapDef = new HeatMapRendererDefinition()
{
Radius = 20,
WeightField = "Population",
ColorRamp = colorRamp.ColorRamp,
RendereringQuality = 8,
UpperLabel = "High Density",
LowerLabel = "Low Density"
};
FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
CIMHeatMapRenderer heatMapRndr = (CIMHeatMapRenderer)flyr.CreateRenderer(heatMapDef);
flyr.SetRenderer(heatMapRndr);
});
string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];
await QueuedTask.Run(() =>
{
CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 16.0, SimpleMarkerStyle.Diamond);
CIMSymbolReference symbolPointTemplate = 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 ramp
UnclassedColorsRendererDefinition unclassRndrDef = new UnclassedColorsRendererDefinition
("Population", symbolPointTemplate, colorRamp.ColorRamp, "Highest", "Lowest", 5000000, 50000)
{
//drawing features with null values with a different symbol
ShowNullValues = true,
NullValueLabel = "Unknown"
};
CIMPointSymbol nullSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 16.0, SimpleMarkerStyle.Circle);
unclassRndrDef.NullValueSymbol = nullSym.MakeSymbolReference();
FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
CIMClassBreaksRenderer cbRndr = (CIMClassBreaksRenderer)flyr.CreateRenderer(unclassRndrDef);
flyr.SetRenderer(cbRndr);
});
//create marker from the Font, char index,size,color
var cimMarker = SymbolFactory.Instance.ConstructMarker(125, "Wingdings 3", "Regular", 6, ColorFactory.Instance.BlueRGB) as CIMCharacterMarker;
var polygonMarker = cimMarker.Symbol;
//modifying the polygon's outline and fill
//This is the outline
polygonMarker.SymbolLayers[0] = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.GreenRGB, 2, SimpleLineStyle.Solid);
//This is the fill
polygonMarker.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.
var pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(cimMarker);
//Note: call within QueuedTask.Run()
CIMSymbol symbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
//You can generate a swatch for a text symbols also.
var si = new SymbolStyleItem()
{
Symbol = symbol,
PatchHeight = 64,
PatchWidth = 64
};
return si.PreviewImage;
string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];
await QueuedTask.Run(() =>
{
CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();
//minimum symbol size is capped to 4 point while the maximum symbol size is set to 50 point
ProportionalRendererDefinition prDef = new ProportionalRendererDefinition("POPULATION", symbolPointTemplate, 4, 50, true)
{
//setting upper and lower size stops to stop symbols growing or shrinking beyond those thresholds
UpperSizeStop = 5000000, //features with values >= 5,000,000 will be drawn with maximum symbol size
LowerSizeStop = 50000 //features with values <= 50,000 will be drawn with minimum symbol size
};
FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
CIMProportionalRenderer propRndr = (CIMProportionalRenderer)flyr.CreateRenderer(prDef);
flyr.SetRenderer(propRndr);
});
string colorBrewerSchemesName = "ArcGIS Colors";
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == colorBrewerSchemesName);
string colorRampName = "Heat Map 4 - Semitransparent";
IList<ColorRampStyleItem> colorRampList = await QueuedTask.Run(() =>
{
return style.SearchColorRamps(colorRampName);
});
ColorRampStyleItem colorRamp = colorRampList[0];
await QueuedTask.Run(() =>
{
CIMPointSymbol pointSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.GreenRGB, 1.0, SimpleMarkerStyle.Circle);
CIMSymbolReference symbolPointTemplate = pointSym.MakeSymbolReference();
//Defining proportional renderer where size of symbol will be same as its value in field used in the renderer.
ProportionalRendererDefinition prDef = new ProportionalRendererDefinition("POPULATION", esriUnits.esriMeters, symbolPointTemplate, SymbolShapes.Square, ValueRepresentations.Radius);
FeatureLayer flyr = MapView.Active.Map.Layers[0] as FeatureLayer;
CIMProportionalRenderer propRndr = (CIMProportionalRenderer)flyr.CreateRenderer(prDef);
flyr.SetRenderer(propRndr);
});
var lyr = 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)
var uvRenderer = lyr.GetRenderer() as CIMUniqueValueRenderer;
if (uvRenderer == null) return;
//layer has STATE_NAME field
//community sample Data\Admin\AdminSample.aprx
string expression = "if ($view.scale > 21000000) { return $feature.STATE_NAME } else { return 'All' }";
CIMExpressionInfo updatedExpressionInfo = new CIMExpressionInfo
{
Expression = expression,
Title = "Custom" // can be any string used for UI purpose.
};
//set the renderer's expression
uvRenderer.ValueExpressionInfo = updatedExpressionInfo;
//SetRenderer on Layer
lyr.SetRenderer(uvRenderer);
});
var lyr = 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.aprx
var lyrDefn = lyr.GetDefinition() as CIMFeatureLayer;
if (lyrDefn == null) return;
//Get the label classes - we need the first one
var listLabelClasses = lyrDefn.LabelClasses.ToList();
var theLabelClass = listLabelClasses.FirstOrDefault();
//set the label class Expression to use the Arcade expression
theLabelClass.Expression = "return $feature.STATE_NAME + TextFormatting.NewLine + $feature.POP2000;";
//Set the label definition back to the layer.
lyr.SetDefinition(lyrDefn);
});
aMap.SetBasemapLayers(Basemap.Gray);
aMap.SetBasemapLayers(Basemap.None);
//Finds layers by name and returns a read only list of Layers
IReadOnlyList<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 map
var lyrFindLayer = 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.
var lyrExists = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Any(f => f.Name == "U.S. States (Generalized)");
var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
var noFeaturesSelected = lyr.SelectionCount;
List<FeatureLayer> featureLayerList = aMap.GetLayersAsFlattenedList().OfType<FeatureLayer>().ToList();
IReadOnlyList<StandaloneTable> tables = aMap.FindStandaloneTables("addresses");
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
QueuedTask.Run(() =>
{
var cimRenderer = featureLayer.GetRenderer() as CIMUniqueValueRenderer;
var cimRotationVariable = cimRenderer.VisualVariables.OfType<CIMRotationVisualVariable>().FirstOrDefault();
var rotationInfoZ = cimRotationVariable.VisualVariableInfoZ;
var rotationExpression = rotationInfoZ.ValueExpressionInfo.Expression; // this expression stores the field name
});
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
// toggle the label visibility
featureLayer.SetLabelVisibility(!featureLayer.IsLabelVisible);
});
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
// get the CIM definition from the layer
var cimFeatureDefinition = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMBasicFeatureLayer;
// get the view of the source table underlying the layer
var cimDisplayTable = cimFeatureDefinition.FeatureTable;
// this field is used as the 'label' to represent the row
var displayField = cimDisplayTable.DisplayField;
});
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
// get the CIM renderer from the layer
var cimRenderer = featureLayer.GetRenderer() as ArcGIS.Core.CIM.CIMSimpleRenderer;
// get the collection of connected attributes for rotation
var cimRotationVariable = cimRenderer.VisualVariables.OfType<ArcGIS.Core.CIM.CIMRotationVisualVariable>().FirstOrDefault();
// the z direction is describing the heading rotation
var rotationInfoZ = cimRotationVariable.VisualVariableInfoZ;
var rotationExpression = rotationInfoZ.Expression; // this expression stores the field name
});
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
// get the CIM layer definition
var cimFeatureLayer = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMFeatureLayer;
// turn on the option to scale the symbols in this layer based in the map's reference scale
cimFeatureLayer.ScaleSymbols = true;
});
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
// change the layer cache type to maximum age
featureLayer.SetDisplayCacheType(ArcGIS.Core.CIM.DisplayCacheType.MaxAge);
// change from the default 5 min to 2 min
featureLayer.SetDisplayCacheMaxAge(TimeSpan.FromMinutes(2));
});
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
{
// get the CIM definition of the layer
var layerDef = featureLayer.GetDefinition() as ArcGIS.Core.CIM.CIMBasicFeatureLayer;
// disable the default symbol
layerDef.UseSelectionSymbol = false;
// assign a new color
layerDef.SelectionColor = ColorFactory.Instance.RedRGB;
// apply the definition to the layer
featureLayer.SetDefinition(layerDef);
if (!featureLayer.IsVisible) featureLayer.SetVisibility(true);
//Do a selection
MapView.Active.SelectFeatures(MapView.Active.Extent);
});
var map = MapView.Active.Map;
if (map == null)
return;
//Get the group layers first
IReadOnlyList<GroupLayer> groupLayers = map.Layers.OfType<GroupLayer>().ToList();
//Iterate and remove the layers within the group layers that are unchecked.
foreach (var groupLayer in groupLayers)
{
//Get layers that not visible within the group
var layers = groupLayer.Layers.Where(l => l.IsVisible == false).ToList();
//Remove all the layers that are not visible within the group
await QueuedTask.Run(() => map.RemoveLayers(layers));
}
//Group Layers that are empty and are unchecked
foreach (var group in groupLayers)
{
if (group.Layers.Count == 0 && group.IsVisible == false) //No layers in the group
{
//remove the group
await QueuedTask.Run(() => map.RemoveLayer(group));
}
}
//Get Layers that are NOT Group layers and are unchecked
var notAGroupAndUnCheckedLayers = map.Layers.Where(l => !(l is GroupLayer) && l.IsVisible == false).ToList();
//Remove all the non group layers that are not visible
await QueuedTask.Run(() => map.RemoveLayers(notAGroupAndUnCheckedLayers));
var map = MapView.Active.Map;
if (map == null)
return;
//Get the group layers
IReadOnlyList<GroupLayer> groupLayers = map.Layers.OfType<GroupLayer>().ToList();
foreach (var group in groupLayers)
{
if (group.Layers.Count == 0) //No layers in the group
{
//remove the group
await QueuedTask.Run(() => map.RemoveLayer(group));
}
}
public static void CreateDictionary()
{
//Get the map's defintion
var mapDefn = MapView.Active.Map.GetDefinition();
//Get the Map's Maplex labelling engine properties
var mapDefnPlacementProps = mapDefn.GeneralPlacementProperties as CIMMaplexGeneralPlacementProperties;
//Define the abbreaviations we need in an array
List<CIMMaplexDictionaryEntry> abbreviationDictionary = new List<CIMMaplexDictionaryEntry>
{
new CIMMaplexDictionaryEntry {
Abbreviation = "Hts",
Text = "Heights",
MaplexAbbreviationType = MaplexAbbreviationType.Ending
},
new CIMMaplexDictionaryEntry
{
Abbreviation = "Ct",
Text = "Text",
MaplexAbbreviationType = MaplexAbbreviationType.Ending
}
//etc
};
//The Maplex Dictionary - can hold multiple Abbreviation collections
var maplexDictionary = new List<CIMMaplexDictionary>
{
new CIMMaplexDictionary {
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);
}
private static void ApplyDictionary()
{
var featureLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().First();
QueuedTask.Run(() => {
//Creates Abbreviation dictionary and adds to Map Defintion
CreateDictionary();
//Get the layer's definition
var lyrDefn = featureLayer.GetDefinition() as CIMFeatureLayer;
//Get the label classes - we need the first one
var listLabelClasses = lyrDefn.LabelClasses.ToList();
var theLabelClass = listLabelClasses.FirstOrDefault();
//Modify label Placement props to use abbreviation dictionary
CIMGeneralPlacementProperties labelEngine = MapView.Active.Map.GetDefinition().GeneralPlacementProperties;
theLabelClass.MaplexLabelPlacementProperties.DictionaryName = "NameEndingsAbbreviations";
theLabelClass.MaplexLabelPlacementProperties.CanAbbreviateLabel = true;
theLabelClass.MaplexLabelPlacementProperties.CanStackLabel = false;
//Set the labelClasses back
lyrDefn.LabelClasses = listLabelClasses.ToArray();
//set the layer's definition
featureLayer.SetDefinition(lyrDefn);
});
}
//Get all styles in the project
var ProjectStyles = Project.Current.GetItems<StyleProjectItem>();
//Get a specific style in the project by name
StyleProjectItem style = ProjectStyles.First(x => x.Name == "NameOfTheStyle");
//Full path for the new style file (.stylx) to be created
string styleToCreate = @"C:\Temp\NewStyle.stylx";
await QueuedTask.Run(() => StyleHelper.CreateStyle(Project.Current, styleToCreate));
//For ArcGIS Pro system styles, just pass in the name of the style to add to the project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, "3D Vehicles"));
//For custom styles, pass in the full path to the style file on disk
string customStyleToAdd = @"C:\Temp\CustomStyle.stylx";
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, customStyleToAdd));
//For ArcGIS Pro system styles, just pass in the name of the style to remove from the project
await QueuedTask.Run(() => StyleHelper.RemoveStyle(Project.Current, "3D Vehicles"));
//For custom styles, pass in the full path to the style file on disk
string customStyleToAdd = @"C:\Temp\CustomStyle.stylx";
await QueuedTask.Run(() => StyleHelper.RemoveStyle(Project.Current, customStyleToAdd));
public Task AddStyleItemAsync(StyleProjectItem style, StyleItem itemToAdd)
{
return QueuedTask.Run(() =>
{
if (style == null || itemToAdd == null)
throw new System.ArgumentNullException();
//Add the item to style
style.AddItem(itemToAdd);
});
}
public Task RemoveStyleItemAsync(StyleProjectItem style, StyleItem itemToRemove)
{
return QueuedTask.Run(() =>
{
if (style == null || itemToRemove == null)
throw new System.ArgumentNullException();
//Remove the item from style
style.RemoveItem(itemToRemove);
});
}
//Pass in the full path to the style file on disk
public async Task<bool> CanUpgradeStyleAsync(string stylePath)
{
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//returns true if style can be upgraded
return style.CanUpgrade;
}
//Pass in the full path to the style file on disk
public async Task<bool> IsReadOnly(string stylePath)
{
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//returns true if style is read-only
return style.IsReadOnly;
}
//Pass in the full path to the style file on disk
public async Task<bool> IsCurrent(string stylePath)
{
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//returns true if style matches the current Pro version
return style.IsCurrent;
}
//Pass in the full path to the style file on disk
public async Task<bool> UpgradeStyleAsync(string stylePath)
{
bool success = false;
//Add the style to the current project
await QueuedTask.Run(() => StyleHelper.AddStyle(Project.Current, stylePath));
StyleProjectItem style = Project.Current.GetItems<StyleProjectItem>().First(x => x.Path == stylePath);
//Verify that style can be upgraded
if (style.CanUpgrade)
{
success = await QueuedTask.Run(() => StyleHelper.UpgradeStyle(style));
}
//return true if style was upgraded
return success;
}
await QueuedTask.Run(() =>
{
CIMPointSymbol pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 10.0);
});
await QueuedTask.Run(() =>
{
CIMPointSymbol starPointSymbol = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 10.0, SimpleMarkerStyle.Star);
});
await QueuedTask.Run(() =>
{
CIMMarker marker = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.GreenRGB, 8.0, SimpleMarkerStyle.Pushpin);
CIMPointSymbol pointSymbolFromMarker = SymbolFactory.Instance.ConstructPointSymbol(marker);
});
//The following file formats can be used to create the marker: DAE, 3DS, FLT, EMF, JPG, PNG, BMP, GIF
CIMMarker markerFromFile = await QueuedTask.Run(() => SymbolFactory.Instance.ConstructMarkerFromFile(@"C:\Temp\fileName.dae"));
CIMPointSymbol pointSymbolFromFile = SymbolFactory.Instance.ConstructPointSymbol(markerFromFile);
CIMPolygonSymbol polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid);
CIMStroke outline = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid);
CIMPolygonSymbol fillWithOutline = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, outline);
CIMPolygonSymbol fillWithoutOutline = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB, SimpleFillStyle.Solid, null);
CIMLineSymbol lineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.BlueRGB, 4.0, SimpleLineStyle.Solid);
CIMStroke stroke = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 2.0);
CIMLineSymbol lineSymbolFromStroke = SymbolFactory.Instance.ConstructLineSymbol(stroke);
//These methods must be called within the lambda passed to QueuedTask.Run
var lineStrokeRed = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 4.0);
var markerCircle = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Circle);
markerCircle.MarkerPlacement = new CIMMarkerPlacementOnVertices()
{
AngleToLine = true,
PlaceOnEndPoints = true,
Offset = 0
};
var lineSymbolWithCircles = new CIMLineSymbol()
{
SymbolLayers = new CIMSymbolLayer[2] { markerCircle, lineStrokeRed }
};
//These methods must be called within the lambda passed to QueuedTask.Run
var markerTriangle = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Triangle);
markerTriangle.Rotation = -90; // or -90
markerTriangle.MarkerPlacement = new CIMMarkerPlacementOnLine() { AngleToLine = true, RelativeTo = PlacementOnLineRelativeTo.LineEnd };
var lineSymbolWithArrow = new CIMLineSymbol()
{
SymbolLayers = new CIMSymbolLayer[2] { markerTriangle,
SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 2)
}
};
CIMPolygonSymbol symbol = SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.RedRGB);
//Get symbol reference from the symbol
CIMSymbolReference symbolReference = symbol.MakeSymbolReference();
public Task<SymbolStyleItem> GetSymbolFromStyleAsync(StyleProjectItem style, string key)
{
return QueuedTask.Run(() =>
{
if (style == null)
throw new System.ArgumentNullException();
//Search for a specific point symbol in style
SymbolStyleItem item = (SymbolStyleItem)style.LookupItem(StyleItemType.PointSymbol, key);
return item;
});
}
public Task<IList<SymbolStyleItem>> GetPointSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for point symbols
return QueuedTask.Run(() => style.SearchSymbols(StyleItemType.PointSymbol, searchString));
}
public Task<IList<SymbolStyleItem>> GetLineSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for line symbols
return QueuedTask.Run(() => style.SearchSymbols(StyleItemType.LineSymbol, searchString));
}
public async Task<IList<SymbolStyleItem>> GetPolygonSymbolsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for polygon symbols
return await QueuedTask.Run(() => style.SearchSymbols(StyleItemType.PolygonSymbol, searchString));
}
public async Task<IList<ColorStyleItem>> GetColorsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for colors
return await QueuedTask.Run(() => style.SearchColors(searchString));
}
public async Task<IList<ColorRampStyleItem>> GetColorRampsFromStyleAsync(StyleProjectItem style, string searchString)
{
//StyleProjectItem can be "ColorBrewer Schemes (RGB)", "ArcGIS 2D"...
if (style == null)
throw new System.ArgumentNullException();
//Search for color ramps
//Color Ramp searchString can be "Spectral (7 Classes)", "Pastel 1 (3 Classes)", "Red-Gray (10 Classes)"..
return await QueuedTask.Run(() => style.SearchColorRamps(searchString));
}
public Task<IList<NorthArrowStyleItem>> GetNorthArrowsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for north arrows
return QueuedTask.Run(() => style.SearchNorthArrows(searchString));
}
public Task<IList<ScaleBarStyleItem>> GetScaleBarsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for scale bars
return QueuedTask.Run(() => style.SearchScaleBars(searchString));
}
public Task<IList<LabelPlacementStyleItem>> GetLabelPlacementsFromStyleAsync(StyleProjectItem style, string searchString)
{
if (style == null)
throw new System.ArgumentNullException();
//Search for standard label placement
return QueuedTask.Run(() => style.SearchLabelPlacements(StyleItemType.StandardLabelPlacement, searchString));
}
public Task SetFeatureLayerSymbolAsync(FeatureLayer ftrLayer, CIMSymbol symbolToApply)
{
if (ftrLayer == null || symbolToApply == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() =>
{
//Get simple renderer from the feature layer
CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;
if (currentRenderer == null)
return;
//Set symbol's real world setting to be the same as that of the feature layer
symbolToApply.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);
//Update the symbol of the current simple renderer
currentRenderer.Symbol = symbolToApply.MakeSymbolReference();
//Update the feature layer renderer
ftrLayer.SetRenderer(currentRenderer);
});
}
public Task SetFeatureLayerSymbolFromStyleItemAsync(FeatureLayer ftrLayer, SymbolStyleItem symbolItem)
{
if (ftrLayer == null || symbolItem == null)
throw new System.ArgumentNullException();
return QueuedTask.Run(() =>
{
//Get simple renderer from the feature layer
CIMSimpleRenderer currentRenderer = ftrLayer.GetRenderer() as CIMSimpleRenderer;
if (currentRenderer == null)
return;
//Get symbol from the SymbolStyleItem
CIMSymbol symbol = symbolItem.Symbol;
//Set symbol's real world setting to be the same as that of the feature layer
symbol.SetRealWorldUnits(ftrLayer.UsesRealWorldSymbolSizes);
//Update the symbol of the current simple renderer
currentRenderer.Symbol = symbol.MakeSymbolReference();
//Update the feature layer renderer
ftrLayer.SetRenderer(currentRenderer);
});
}
// 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");
public Task ApplySymbolToFeatureLayerAsync(FeatureLayer featureLayer, string symbolName)
{
return QueuedTask.Run(async () =>
{
//Get the ArcGIS 2D System style from the Project
var arcGIS2DStyle = Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ArcGIS 2D");
//Search for the symbolName style items within the ArcGIS 2D style project item.
var items = await QueuedTask.Run(() => arcGIS2DStyle.SearchSymbols(StyleItemType.PointSymbol, symbolName));
//Gets the CIMSymbol
CIMSymbol symbol = items.FirstOrDefault().Symbol;
//Get the renderer of the point feature layer
CIMSimpleRenderer renderer = featureLayer.GetRenderer() as CIMSimpleRenderer;
//Set symbol's real world setting to be the same as that of the feature layer
symbol.SetRealWorldUnits(featureLayer.UsesRealWorldSymbolSizes);
//Apply the symbol to the feature layer's current renderer
renderer.Symbol = symbol.MakeSymbolReference();
//Appy the renderer to the feature layer
featureLayer.SetRenderer(renderer);
});
}
public async Task ApplyColorRampAsync(FeatureLayer featureLayer, string[] fields)
{
StyleProjectItem style =
Project.Current.GetItems<StyleProjectItem>().FirstOrDefault(s => s.Name == "ColorBrewer Schemes (RGB)");
if (style == null) return;
var colorRampList = await QueuedTask.Run(() => style.SearchColorRamps("Red-Gray (10 Classes)"));
if (colorRampList == null || colorRampList.Count == 0) return;
CIMColorRamp cimColorRamp = null;
CIMRenderer renderer = null;
await QueuedTask.Run(() =>
{
cimColorRamp = colorRampList[0].ColorRamp;
var rendererDef = new UniqueValueRendererDefinition(fields, null, cimColorRamp);
renderer = featureLayer?.CreateRenderer(rendererDef);
featureLayer?.SetRenderer(renderer);
});
}
Home | API Reference | Requirements | Download | Samples
-
Get a style in project by name
-
Create a new style
-
Add a style to project
-
Remove a style from project
-
Add a style item to a style
-
Remove a style item from a style
-
Determine if a style can be upgraded
-
Determine if a style is read-only
-
Determine if a style is current
-
Upgrade a style
-
Construct a point symbol of a specific color and size
-
Construct a point symbol of a specific color, size and shape
-
Construct a point symbol from a marker
-
Construct a point symbol from a file on disk
-
Construct a point symbol from a in memory graphic
-
Construct a polygon symbol of specific color and fill style
-
Construct a polygon symbol of specific color, fill style and outline
-
Construct a polygon symbol without an outline
-
Construct a line symbol of specific color, size and line style
-
Construct a line symbol from a stroke
-
Construct a multilayer line symbol with circle markers on the line ends
-
Construct a multilayer line symbol with an arrow head on the end
-
Get symbol reference from a symbol
-
Modify a point symbol created from a character marker
-
Get a List of Available Fonts
-
Get/Set Default Font
-
Construct a Text Symbol With Options
-
Create a Swatch for a given symbol
-
Convert Point Symbol to SVG
-
Convert Point Symbol to PNG
-
Lookup Symbol
-
Search for a specific item in a style
-
Search for point symbols in a style
-
Search for line symbols in a style
-
Search for polygon symbols in a style
-
Search for colors in a style
-
Search for color ramps in a style
-
Search for north arrows in a style
-
Search for scale bars in a style
-
Search for label placements in a style
-
Search for legends in a style
-
Search for legend items in a style
-
Search for grids in a style
-
Search for map surrounds in a style
-
Search for table frames in a style
-
Search for table frame fields in a style
-
Set symbol for a feature layer symbolized with simple renderer
-
Apply a symbol from style to a feature layer
-
Apply a point symbol from a style to a feature layer
-
Apply a color ramp from a style to a feature layer
-
Get the active map
-
Create a new map with a default basemap layer
-
Find a map within a project and open it
-
Open a webmap
-
Get Map Panes
-
Get the Unique List of Maps From the Map Panes
-
Change the Map name
-
Renames the caption of the pane
-
Convert Map to Local Scene
-
Get Basemaps
-
Save Map as MapX
-
Save 2D Map as WebMap on Disk
-
Clip Map to the provided clip polygon
-
Clear the current map clip geometry
-
Get the map clipping geometry
-
Get the Current Map Location Unit
-
Get the Available List of Map Location Units
-
Format a Location Using the Current Map Location Unit
-
Set the Location Unit for the Current Map
-
Get the Current Map Elevation Unit
-
Get the Available List of Map Elevation Units
-
Format an Elevation Using the Current Map Elevation Unit
-
Set the Elevation Unit for the Current Map
-
Check Map Has Sync-Enabled Content
-
Generate Replicas for Sync-Enabled Content
-
Check Map Has Local Syncable Content
-
Synchronize Replicas for Syncable Content
-
Remove Replicas for Syncable Content
-
Export Map Raster Tile Cache Content
-
Export Map Vector Tile Cache Content
-
Create and add a layer to the active map
-
Create layer with create-params
-
Create FeatureLayer and add to Map using LayerCreationParams
-
Create FeatureLayer and set to not display in Map.
-
Create FeatureLayer with a Renderer
-
Create FeatureLayer with a Query Definition
-
Create multiple layers
-
Create mutliple layers with BulkLayerCreationParams
-
Add a GeoPackage to the Map
-
Create TopologyLayer with an Uri pointing to a Topology dataset
-
Create Topology Layer using Topology dataset
-
Create Catalog Layer using Uri to a Catalag Feature Class
-
Create Catalog Layer using CatalogDataset
-
Add MapNotes to the active map
-
Apply Symbology from a Layer in the TOC
-
Create a new SubTypeGroupLayer
-
Create layer from a lyrx file
-
Apply Symbology to a layer from a Layer file
-
Add a WMS service
-
Add a WFS Service
-
Adding and changing styles for WMS Service Layer
-
Create a query layer
-
Create a feature layer with class breaks renderer with defaults
-
Create a feature layer with class breaks renderer
-
Get a list of layers filtered by layer type from a map
-
Get a layer of a certain geometry type
-
Find a layer
-
Find a standalone table
-
Find a layer using partial name search
-
Change layer visibility, editability, snappability
-
Create a Lyrx file
-
Count the features selected on a layer
-
Access the display field for a layer
-
Enable labeling on a layer
-
Set Elevation Mode for a layer
-
Move a layer in the 2D group to the 3D Group in a Local Scene
-
Reset the URL of a feature service layer
-
Change the underlying data source of a feature layer - same workspace type
-
Change Geodatabase Version of layers off a specified version in a map
-
Querying a feature layer
-
Querying a feature layer with a spatial filter
-
Apply A Definition Query Filter to a Feature Layer
-
Apply A Definition Query Filter With a Filter Geometry to a Feature Layer
-
Apply A Definition Query Filter to a Feature Layer2
-
Retrieve the Definition Query Filters for a Feature Layer
-
Get Feature Outlines from a Feature Layer
-
Get the attribute rotation field of a layer
-
Find connected attribute field for rotation
-
Toggle "Scale layer symbols when reference scale is set"
-
Set the layer cache
-
Change the layer selection color
-
Removes all layers that are unchecked
-
Remove empty groups
-
Create and apply Abbreviation Dictionary in the Map Definition to a layer
-
Set zoom level for Attribute Table
-
Retrieve the values of selected cell in the attribute table
-
Move to a particular row
-
Set unique value renderer to the selected feature layer of the active map
-
Create a UniqueValueRenderer to specify symbols to values
-
Create a Heatmap Renderer
-
Create an Unclassed Renderer
-
Create a Proportion Renderer with max and min symbol size capped
-
Create a True Proportion Renderer
-
Create a scene with a ground surface layer
-
Create a New Elevation Surface
-
Set a custom elevation surface to a Z-Aware layer
-
Add an elevation source to an existing elevation surface layer
-
Get the elevation surface layers and elevation source layers from a map
-
Find an elevation surface layer
-
Remove elevation surface layers
-
Get Z values from the default ground surface
-
Get Z values from a specific surface
-
Get Z values from a layer
-
Create a raster layer
-
Update the raster colorizer on a raster layer
-
Update the RGB colorizer on a raster layer
-
Check if a certain colorizer can be applied to a raster layer
-
Create a new colorizer based on a default colorizer definition and apply it to the raster layer
-
Create a new colorizer based on a custom colorizer definition and apply it to the raster layer
-
Create a raster layer with a new colorizer definition
-
Create a mosaic layer
-
Update the raster colorizer on a mosaic layer
-
Update the RGB colorizer on a mosaic layer
-
Check if a certain colorizer can be applied to a mosaic layer
-
Create a new colorizer based on a default colorizer definition and apply it to the mosaic layer
-
Create a new colorizer based on a custom colorizer definition and apply it to the mosaic layer
-
Create a mosaic layer with a new colorizer definition
-
Update the sort order - mosaic method on a mosaic layer
-
Update the resolve overlap - mosaic operator on a mosaic layer
-
Create an image service layer
-
Update the raster colorizer on an image service layer
-
Update the RGB colorizer on an image service layer
-
Check if a certain colorizer can be applied to an image service layer
-
Create a new colorizer based on a default colorizer definition and apply it to the image service layer
-
Create a new colorizer based on a custom colorizer definition and apply it to the image service layer
-
Create an image service layer with a new colorizer definition
-
Update the sort order - mosaic method on an image service layer
-
Update the resolve overlap - mosaic operator on an image service layer
-
Create a StandaloneTable
-
Retrieve a table from its container
-
Move a Standalone table
-
Remove a Standalone table
-
Translate From Dictionary to SelectionSet
-
Translate from SelectionSet to Dictionary
-
Get OIDS from a SelectionSet for a given MapMember
-
Get OIDS from a SelectionSet for a given MapMember by Name
-
Get Elevation profile from the default ground surface
-
Get Elevation profile from a specific surface
-
Interpolate a line between two points and calculate the elevation profile
-
Show Elevation profile graph with the default ground surface
-
Show Elevation profile graph with a specific surface
-
Show Elevation profile graph between two points
-
Show Elevation profile graph using an ElevationProfileResult
-
Access the ElevationProfileGraph when added
-
Access the ElevationProfileGraph
-
Export Elevation Profile Graph
-
Customize Elevation Profile Graph Display
-
Connect to a Device Location Source
-
Get the Current Device Location Source
-
Close the Current Device Location Source
-
Get Current Device Location Source and Properties
-
Update Properties on the Current Device Location Source
-
Subscribe to DeviceLocationPropertiesUpdated event
-
Subscribe to DeviceLocationSourceChanged event
-
Enable/Disable Current Device Location Source For the Map
-
Get Current Map Device Location Options
-
Check if The Current Device Location Is Enabled On The Map
-
Set Current Map Device Location Options
-
Zoom/Pan The Map To The Most Recent Location
-
Add the Most Recent Location To A Graphics Layer
-
Set map view to always be centered on the device location
-
Subscribe to Location Snapshot event