{
//feature layer from the active map
var lookupMapView = MapView.Active;
var featureLayerLookUp = lookupMapView.Map.GetLayersAsFlattenedList()
.OfType<FeatureLayer>()
.FirstOrDefault();
await QueuedTask.Run(() =>
{
//Get the selection
var selection = featureLayerLookUp.GetSelection();
//Get the first Object ID
var firstOID = selection.GetObjectIDs().FirstOrDefault();
//Determine whether the layer's renderer type supports symbol lookup.
if (featureLayerLookUp.CanLookupSymbol())
{
//Looks up the symbol for the corresponding feature identified by the object id.
var lookupSymbol = featureLayerLookUp.LookupSymbol(firstOID, lookupMapView);
var jSon = lookupSymbol.ToJson(); //Create a JSON encoding of the symbol
//Do something with symbol
}
});
}
{
//This is how you get the active map
var mapToGet = MapView.Active?.Map;
}
{
var activeMap = MapView.Active?.Map;
await QueuedTask.Run(() => activeMap?.SetName("Test"));
ProApp.Panes.ActivePane.Caption = "Caption";
}
{
var mapToClip = MapView.Active.Map;
await QueuedTask.Run(() =>
{
//A layer to use for the clip extent
var lyrOfInterest = mapToClip.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(l => l.Name == "TestPoly").FirstOrDefault();
//Get the polygon to use to clip the map
var extent = lyrOfInterest.QueryExtent();
var polygonForClipping = PolygonBuilderEx.CreatePolygon(extent);
//Clip the map using the layer's extent
mapToClip.SetClipGeometry(polygonForClipping,
SymbolFactory.Instance.ConstructLineSymbol(
SymbolFactory.Instance.ConstructStroke(
ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Dash)));
});
}
{
var mapWithClip = MapView.Active.Map;
//Clear the Map clip.
//If no clipping is set then this is a no-op.
mapWithClip.ClearClipGeometry();
}
{
var mapWithClip = MapView.Active.Map;
await QueuedTask.Run(() =>
{
//If clipping is set to ArcGIS.Core.CIM.ClippingMode.None or ArcGIS.Core.CIM.ClippingMode.MapSeries null is returned
//If clipping is set to ArcGIS.Core.CIM.ClippingMode.MapExtent the ArcGIS.Core.CIM.CIMMap.CustomFullExtent is returned.
//Otherwise, if clipping is set to ArcGIS.Core.CIM.ClippingMode.CustomShape the custom clip polygon is returned.
var poly = mapWithClip.GetClipGeometry();
//You can use the polygon returned
//For example: We make a polygon graphic element and add it to a Graphics Layer.
var gl = mapWithClip.GetLayersAsFlattenedList().OfType<GraphicsLayer>().FirstOrDefault();
if (gl == null)
{
return;
}
var polygonSymbol = SymbolFactory.Instance.ConstructPolygonSymbol(CIMColor.CreateRGBColor(255, 255, 0));
var cimGraphicElement = new CIMPolygonGraphic
{
Polygon = poly,
Symbol = polygonSymbol.MakeSymbolReference()
};
gl.AddElement(cimGraphicElement);
});
}
{
var gridOptionsMapView = MapView.Active;
if (gridOptionsMapView == null)
return;
await QueuedTask.Run(() =>
{
//Does the 'map' currently have any options?
var hasOptions = GridOptionsEnvironment.Instance.HasGridOptions(map);
//If grid options have not been set for the map, then default grid options are added
//for the map otherwise the existing gridoptions are returned.
//NOTE: Grid options are returned by value meaning a copy is always returned. Any changes made to the
//grid options need to be -set- back on the map using SetGridOptions for the changes to persist.
var gridOptions = GridOptionsEnvironment.Instance.GetGridOptions(
gridOptionsMapView.Map);
//Only return grid options if grid options have previously been set:
var gridOptions2 = GridOptionsEnvironment.Instance.GetGridOptions(
gridOptionsMapView.Map, false);
});
}
{
//Does the map have any exportable raster content?
var canExport = GenerateOfflineMap.Instance.GetCanExportRasterTileCache(map);
var rasterTileExtent = MapView.Active.Extent;
if (canExport)
{
//Check the available LOD scale ranges
var scales = GenerateOfflineMap.Instance.GetExportRasterTileCacheScales(map, rasterTileExtent);
//Pick the desired LOD scale
var max_scale = scales[scales.Count() / 2];
//Configure the export parameters
var export_params = new ExportTileCacheParams()
{
Extent = rasterTileExtent,//Use same extent as was used to retrieve scales
MaximumUserDefinedScale = max_scale
//DestinationFolder = .... (optional)
};
//If DestinationFolder is not set, output defaults to project
//offline maps location set in the project properties. If that is
//not set, output defaults to the current project folder location.
//Do the export. Depending on the MaximumUserDefinedScale and the
//area of the extent requested, this can take minutes for tile packages
//over 1 GB or less if your network speed is slow...
GenerateOfflineMap.Instance.ExportRasterTileCache(map, export_params);
}
}
{
var mapVectorTileExtent = MapView.Active.Extent;
//Does the map have any exportable vector tile content?
var canExport = GenerateOfflineMap.Instance.GetCanExportVectorTileCache(map);
if (canExport)
{
//Check the available LOD scale ranges
var scales = GenerateOfflineMap.Instance.GetExportVectorTileCacheScales(map, mapVectorTileExtent);
//Pick the desired LOD scale
var max_scale = scales[scales.Count() / 2];
//Configure the export parameters
var export_params = new ExportTileCacheParams()
{
Extent = mapVectorTileExtent,//Use same extent as was used to retrieve scales
MaximumUserDefinedScale = max_scale,
DestinationFolder = @"C:\Data\Offline"
};
//If DestinationFolder is not set, output defaults to project
//offline maps location set in the project properties. If that is
//not set, output defaults to the current project folder location.
//Do the export. Depending on the MaximumUserDefinedScale and the
//area of the extent requested, this can take minutes for tile packages
//over 1 GB or less if your network speed is slow...
GenerateOfflineMap.Instance.ExportVectorTileCache(map, export_params);
}
}
{
IEnumerable<FeatureLayer> featureLayers = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>()
.Where(l => l.ShapeType == esriGeometryType.esriGeometryPoint);
var layerFile = @"C:\Data\SDK\UniqueValuePointLayer.lyrx";
foreach (var featureLayerToSymbolize in featureLayers)
{
//Get the Layer Document from the lyrx file
var lyrDocFromLyrxFile = new LayerDocument(layerFile);
var cimLyrDoc = lyrDocFromLyrxFile.GetCIMLayerDocument();
//Get the renderer from the layer file
var rendererFromLayerFile = ((CIMFeatureLayer)cimLyrDoc.LayerDefinitions[0]).Renderer as CIMUniqueValueRenderer;
//Apply the renderer to the feature layer
//Note: If working with a raster layer, use the SetColorizer method.
featureLayerToSymbolize?.SetRenderer(rendererFromLayerFile);
}
}
{
//Get an existing Layer. This layer has a symbol you want to use in a new layer.
var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>()
.Where(l => l.ShapeType == esriGeometryType.esriGeometryPoint).FirstOrDefault();
}
{
//Finds layers by name and returns a read only list of Layers
IReadOnlyList<Layer> layers = map.FindLayers("cities", true);
//Finds a layer using a URI.
//The Layer URI you pass in helps you search for a specific layer in a 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)");
}
{
// get the layers selected in the TOC
var selectedLayers = MapView.Active.GetSelectedLayers();
// get the standalonetables elected in the TOC
var selectedTables = MapView.Active.GetSelectedStandaloneTables();
var selectedMMs = new List<MapMember>(selectedLayers);
selectedMMs.AddRange(selectedTables);
// create the LayerDocument
LayerDocument layerDocument = new LayerDocument(selectedMMs);
await QueuedTask.Run(() => layerDocument.Save(@"c:\Data\MyLayerDocument.lyrx"));
}
{
var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();
var noFeaturesSelected = lyr.SelectionCount;
}
{
var container = MapView.Active.Map;
//the map standalone table collection
var table = container.GetStandaloneTablesAsFlattenedList()
.FirstOrDefault(tbl => tbl.Name == "EarthquakeDamage");
//or from a group layer
var grp_layer = MapView.Active.Map.FindLayers("GroupLayer1").First() as GroupLayer;
var table2 = grp_layer.FindStandaloneTables("EarthquakeDamage").First();
//or grp_layer.GetStandaloneTablesAsFlattenedList().First()
//or grp_layer.StandaloneTables.Where(...).First(), etc.
//show the table in a table view
//use FrameworkApplication.Current.Dispatcher.BeginInvoke if not on the UI thread
FrameworkApplication.Panes.OpenTablePane(table2);
}
{
//get the first group layer that has at least one table
var grp_layer = MapView.Active.Map.GetLayersAsFlattenedList()
.OfType<GroupLayer>().First(g => g.StandaloneTables.Count > 0);
grp_layer.MoveStandaloneTable(grp_layer.StandaloneTables.First(), -1);
//move the last table in the map standalone tables to a group
//layer and place it at position 3. If 3 is invalid, the table
//will be placed at the bottom of the target container
//assumes the map has at least one standalone table...
var table = map.StandaloneTables.Last();
map.MoveStandaloneTable(table, grp_layer, 3);
//move a table from a group layer to the map standalone tables
//collection - assumes a table called 'Earthquakes' exists
var table2 = grp_layer.FindStandaloneTables("Earthquakes").First();
//move to the map container
map.MoveStandaloneTable(table2, 0);//will be placed at the top
}
{
// get map selection
var mapSelSet = MapView.Active.Map.GetSelection();
// create a selectionSet
var selDict = new Dictionary<MapMember, List<long>>();
selDict.Add(featureLayer, new List<long> { 1506, 2696, 2246, 1647, 948 });
var layerSelSet = ArcGIS.Desktop.Mapping.SelectionSet.FromDictionary(selDict);
// test for equality - use Equals method
var isEquals = mapSelSet.Equals(layerSelSet);
// test for equality - use operators
var equals = mapSelSet == layerSelSet;
var notEquals = mapSelSet != layerSelSet;
}
{
// get the elevation profile for a polyline / set of polylines
Polyline polyline = PolylineBuilderEx.CreatePolyline();
MapPoint mapPoint = MapPointBuilderEx.CreateMapPoint(34, -118, SpatialReferences.WGS84);
List<MapPoint> mapPoints = new List<MapPoint> { mapPoint };
var result = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync([polyline]);
if (result.Status == SurfaceZsResultStatus.Ok)
{
var polylineZ = result.Polyline;
// process the polylineZ
// get the elevation profile for a set of points
result = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync(mapPoints);
if (result.Status == SurfaceZsResultStatus.Ok)
{
polylineZ = result.Polyline;
// process the polylineZ
}
}
}
{
// find a specific elevation surface layer
var eleLayer = MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l => l.Name == "TIN");
Polyline polyline = PolylineBuilderEx.CreatePolyline();
MapPoint mapPoint = MapPointBuilderEx.CreateMapPoint(34, -118, SpatialReferences.WGS84);
List<MapPoint> mapPoints = new List<MapPoint> { mapPoint };
// get the elevation profile for a polyline / set of polylines
// use the specific elevation surface layer
var zResult = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync([polyline], eleLayer);
if (zResult.Status == SurfaceZsResultStatus.Ok)
{
var polylineZ = zResult.Polyline;
// process the polylineZ
}
// get the elevation profile for a set of points
// use the specific elevation surface layer
zResult = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync(mapPoints, eleLayer);
if (zResult.Status == SurfaceZsResultStatus.Ok)
{
var polylineZ = zResult.Polyline;
// process the polylineZ
}
}
{
int numPoints = 20;//Or any number of points you want to interpolate
// use a specific elevation surface
var eleLayer = MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l => l.Name == "TIN");
// use the default ground elevation surface
MapPoint startPt = MapPointBuilderEx.CreateMapPoint(-130, 20, SpatialReferences.WGS84);
MapPoint endPt = MapPointBuilderEx.CreateMapPoint(-100, 50, SpatialReferences.WGS84);
var result = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync(startPt, endPt, numPoints);
if (result.Status == SurfaceZsResultStatus.Ok)
{
var polylineZ = result.Polyline;
// process the polylineZ
}
// use a specific elevation surface
result = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync(startPt, endPt, numPoints, eleLayer);
if (result.Status == SurfaceZsResultStatus.Ok)
{
var polylineZ = result.Polyline;
// process the polylineZ
}
}
{
if (!MapView.Active.CanShowElevationProfileGraph())
{
return;
}
// show the elevation profile for a polyline
// use the default ground surface layer
Polyline polyline = PolylineBuilderEx.CreatePolyline();
MapView.Active.ShowElevationProfileGraph([polyline]);
// show the elevation profile for a set of points
// use the default ground surface layer
//Some points
MapPoint mapPoint = MapPointBuilderEx.CreateMapPoint(34, -118, SpatialReferences.WGS84);
List<MapPoint> mapPoints = new List<MapPoint> { mapPoint };
MapView.Active.ShowElevationProfileGraph(mapPoints);
}
{
if (!MapView.Active.CanShowElevationProfileGraph())
{
return;
}
// use a specific elevation surface
var eleLayer = MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l => l.Name == "TIN");
// set up the parameters
var profileParams = new ElevationProfileParameters();
profileParams.SurfaceLayer = eleLayer;
profileParams.Densify = true;
// show the elevation profile for a polyline using the params
//Any line
Polyline polyline = PolylineBuilderEx.CreatePolyline();
MapView.Active.ShowElevationProfileGraph([polyline], profileParams);
// show the elevation profile for a set of points using the params
//Some points
MapPoint mapPoint = MapPointBuilderEx.CreateMapPoint(34, -118, SpatialReferences.WGS84);
List<MapPoint> mapPoints = new List<MapPoint> { mapPoint };
MapView.Active.ShowElevationProfileGraph(mapPoints, profileParams);
}
{
int numPoints = 20;
if (!MapView.Active.CanShowElevationProfileGraph())
{
return;
}
// show the elevation profile
// use the default ground elevation surface
MapPoint startPt = MapPointBuilderEx.CreateMapPoint(-130, 20, SpatialReferences.WGS84);
MapPoint endPt = MapPointBuilderEx.CreateMapPoint(-100, 50, SpatialReferences.WGS84);
MapView.Active.ShowElevationProfileGraph(startPt, endPt, numPoints);
// find a specific elevation surface layer
var tinLayer = MapView.Active.Map.GetElevationSurfaceLayers().FirstOrDefault(l => l.Name == "TIN");
// set up the params
var elevProfileParams = new ElevationProfileParameters();
elevProfileParams.SurfaceLayer = tinLayer;
elevProfileParams.Densify = false;
// show the elevation profile using the params
MapView.Active.ShowElevationProfileGraph(startPt, endPt, numPoints, elevProfileParams);
}
{
MapPoint startPt = MapPointBuilderEx.CreateMapPoint(-130, 20, SpatialReferences.WGS84);
MapPoint endPt = MapPointBuilderEx.CreateMapPoint(-100, 50, SpatialReferences.WGS84);
var elevProfileResult = await MapView.Active.Map.GetElevationProfileFromSurfaceAsync(startPt, endPt, 10);
if (elevProfileResult.Status != SurfaceZsResultStatus.Ok)
{
return;
}
if (!MapView.Active.CanShowElevationProfileGraph())
{
return;
}
// show the elevation profile using the result
MapView.Active.ShowElevationProfileGraph(elevProfileResult);
}
{
// subscribe to the Added, Removed events for the elevation profile graph
mapView.ElevationProfileGraphAdded += Mv_ElevationProfileGraphAdded;
mapView.ElevationProfileGraphRemoved += Mv_ElevationProfileGraphRemoved;
//Handles the event triggered when an elevation profile graph is removed.
void Mv_ElevationProfileGraphRemoved(object sender, EventArgs e)
{
//TODO: handle the removal of the elevation profile graph
}
//Handles the event triggered when an elevation profile graph is added to the active map view.
void Mv_ElevationProfileGraphAdded(object sender, EventArgs e)
{
// get the elevation profile graph from the view
// this will be non-null since we are in a ElevationProfileGraphAdded handler
var mv = MapView.Active;
var graph = mv.GetElevationProfileGraph();
// subscribe to the ContentLoaded event
graph.ContentLoaded += Graph_ContentLoaded;
}
// Handles the event triggered when the elevation profile graph content is loaded.
void Graph_ContentLoaded(object sender, EventArgs e)
{
// get the elevation profile graph
var graph = sender as ArcGIS.Desktop.Mapping.ElevationProfileGraph;
// get the elevation profile geometry
var polyline = graph.Geometry;
// get the elevation profile statistics
var stats = graph.ElevationProfileStatistics;
}
}
{
var elevProfileGraph = MapView.Active.GetElevationProfileGraph();
// Elevation profile graph will be null if no profile graph is displayed
if (elevProfileGraph == null)
{
return;
}
// get the elevation profile geometry and stats
var polyline = elevProfileGraph.Geometry;
var stats = elevProfileGraph.ElevationProfileStatistics;
// reverse the graph
elevProfileGraph.IsReversed = !elevProfileGraph.IsReversed;
// collapse the graph
elevProfileGraph.IsExpanded = false;
}
{
var elevProfileGraph = MapView.Active.GetElevationProfileGraph();
// Elevation profile graph will be null if no profile graph is displayed
if (elevProfileGraph == null)
{
return;
}
if (elevProfileGraph.CanExport)
{
elevProfileGraph.ExportToImage("c:\\temp\\myprofileImage.png");
elevProfileGraph.ExportToCSV("c:\\temp\\myprofile.csv");
}
}
{
if (featureLayer == null)
{
return;
}
var mv = MapView.Active;
await QueuedTask.Run(() =>
{
using (var table = featureLayer.GetTable())
{
using (var rc = table.Search())
{
//get the first feature...
//...assuming at least one feature gets retrieved
rc.MoveNext();
var oid = rc.Current.GetObjectID();
//Use DrawingOutlineType.BoundingEnvelope to retrieve a generalized
//mask geometry or "Box". The mask will be in the same SpatRef as the map
var mask_geom = featureLayer.GetDrawingOutline(oid, mv, DrawingOutlineType.Exact);
//TODO - use the mask geometry...
}
}
});
}
{
//Get the current active TOC content type for the map view
var mapTOCContentType = MapView.Active.CurrentMapTOCContent;
}
{
//Get the current active TOC content type for the map view
var mapTOCContentType = (int)MapView.Active.CurrentMapTOCContent;
//increment to the next tab whatever it is
mapTOCContentType++;
//Can we set this type on the TOC?
if (MapView.Active.CanSetMapTOCContent((MapTOCContentType)mapTOCContentType))
{
//Set it - must be on the UI! - No QueuedTask
MapView.Active.SetMapTOCContentAsync((MapTOCContentType)mapTOCContentType);
}
else
{
mapTOCContentType = (int)MapTOCContentType.DrawingOrder;
//Set it - must be on the UI! - No QueuedTask
MapView.Active.SetMapTOCContentAsync((MapTOCContentType)mapTOCContentType);
}
}
{
// Validate the current active view. Only a local scene can be exported.
bool CanExportScene3DObjects = MapView.Active?.ViewingMode == MapViewingMode.SceneLocal;
if (CanExportScene3DObjects)
{
// Create a scene content export format, export the scene context as a glTF file
var exportFormat = new ExportSceneContentsFormat()
{
Extent = mapView.Extent, // sets Extent property
FolderPath = @"C:\Temp", // sets FolderPath property
//sets FileName property.The export format is determined by the output file extension (e.g.,.stl, .gltf)
FileName = "my-3d-objects.gltf",
IsSingleFileOutput = true, // sets whether to export to one single file
SaveTextures = true //sets whether to save textures
};
// Export the scene content as 3D objects
mapView.ExportScene3DObjects(exportFormat);
}
}
{
using var rowCursor = featureLayer.Search();
var objectIds = new List<long>();
while (rowCursor.MoveNext())
{
using var feature = rowCursor.Current as Feature;
objectIds.Add(feature.GetObjectID());
}
if (objectIds.Count > 0)
{
MapView.Active.ZoomTo(featureLayer, objectIds, TimeSpan.FromSeconds(2));
}
}
{
//Create a Progress Bar user control
System.Windows.Controls.ProgressBar progressBarControl = new()
{
//Configure the progress bar
Minimum = 0,
Maximum = 100,
IsIndeterminate = true,
Width = 300,
Value = 10,
Height = 25,
Visibility = System.Windows.Visibility.Visible
};
//Create a MapViewOverlayControl.
var mapViewOverlayControl = new MapViewOverlayControl(progressBarControl, true, true, true, OverlayControlRelativePosition.BottomCenter, .5, .8);
//Add to the active map
MapView.Active.AddOverlayControl(mapViewOverlayControl);
await QueuedTask.Run(() =>
{
//Wait 3 seconds to remove the progress bar from the map.
Thread.Sleep(3000);
});
//Remove from active map
MapView.Active.RemoveOverlayControl(mapViewOverlayControl);
}
{
// select it in the TOC
List<Layer> layersToSelect = [featureLayer];
MapView.Active.SelectLayers(layersToSelect);
// now execute the layer properties command
var wrapper = FrameworkApplication.GetPlugInWrapper("esri_mapping_selectedLayerPropertiesButton");
var command = wrapper as ICommand;
if (command == null)
{
// the command is not found, leave
}
// execute the command
if (command.CanExecute(null))
{
command.Execute(null);
}
}
{
mapMember = MapView.Active.Map.GetLayersAsFlattenedList().OfType<MapMember>().FirstOrDefault();
//Gets or creates the CIMMapTableView for a MapMember.
var mapTableView = FrameworkApplication.Panes.GetMapTableView(mapMember);
//Configure the table view
mapTableView.DisplaySubtypeDomainDescriptions = false;
mapTableView.SelectionMode = false;
mapTableView.ShowOnlyContingentValueFields = true;
mapTableView.HighlightInvalidContingentValueFields = true;
//Open the table pane using the configured tableView. If a table pane is already open it will be activated.
//You must be on the UI thread to call this function.
var tablePane = FrameworkApplication.Panes.OpenTablePane(mapTableView);
}
{
MapView.Active.Time.Start = null;
MapView.Active.Time.End = null;
}
public static void ShowDynamicPopup(MapMember mapMember, List<long> objectIDs) { MapView mapView = MapView.Active; if (mapView == null) { return; } //Create popup whose content is created the first time the item is requested. var popups = new List<PopupContent>(); foreach (var id in objectIDs) { popups.Add(new DynamicPopupContent(mapMember, id)); } mapView.ShowCustomPopup(popups); } internal class DynamicPopupContent : PopupContent { public DynamicPopupContent(MapMember mapMember, long objectID) { MapMember = mapMember; IDString = objectID.ToString(); IsDynamicContent = true; } //Called when the pop-up is loaded in the window. protected override Task<string> OnCreateHtmlContent() { return QueuedTask.Run(() => string.Format("<b>Map Member: {0}, ID: {1}</b>", MapMember, IDString)); } }
{
UriBuilder searchURL = new UriBuilder(ArcGISPortalManager.Current.GetActivePortal().PortalUri)
{
Path = "sharing/rest/search"
};
string layers = "(type:\"Map Service\" OR type:\"Image Service\" OR type:\"Feature Service\" OR type:\"WMS\" OR type:\"KML\")";
//any public layer content
searchURL.Query = string.Format("q={0}&f=json", layers);
EsriHttpClient httpClient = new EsriHttpClient();
var searchResponse = httpClient.Get(searchURL.Uri.ToString());
dynamic resultItems = JObject.Parse(await searchResponse.Content.ReadAsStringAsync());
long numberOfTotalItems = resultItems.total.Value;
if (numberOfTotalItems == 0)
{
return;
}
List<dynamic> resultItemList = new List<dynamic>();
resultItemList.AddRange(resultItems.results);
//get the first result
dynamic item = resultItemList[0];
string itemID = item.id;
Item currentItem = ItemFactory.Instance.Create(itemID, ItemFactory.ItemType.PortalItem);
var mapView = MapView.Active;
if (mapView == null)
return;
await QueuedTask.Run(() =>
{
//Create a LayerCreationParam
var layerParam = new LayerCreationParams(currentItem);
// if we have an item that can be turned into a layer
// add it to the map
if (LayerFactory.Instance.CanCreateLayerFrom(currentItem))
{
LayerFactory.Instance.CreateLayer<FeatureLayer>(layerParam, mapView.Map);
}
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Get the active map's definition - CIMMap.
var cimMap = map.GetDefinition();
//Get the labeling engine from the map definition
CIMGeneralPlacementProperties labelEngine = cimMap.GeneralPlacementProperties;
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Get the active map's definition - CIMMap.
var cimMap = map.GetDefinition();
//Get the labeling engine from the map definition
var cimGeneralPlacement = cimMap.GeneralPlacementProperties;
if (cimGeneralPlacement is CIMMaplexGeneralPlacementProperties)
{
//Current labeling engine is Maplex labeling engine
//Create a new standard label engine properties
var cimStandardPlacementProperties = new CIMStandardGeneralPlacementProperties();
//Set the CIMMap's GeneralPlacementProperties to the new label engine
cimMap.GeneralPlacementProperties = cimStandardPlacementProperties;
}
else
{
//Current labeling engine is Standard labeling engine
//Create a new Maplex label engine properties
var cimMaplexGeneralPlacementProperties = new CIMMaplexGeneralPlacementProperties();
//Set the CIMMap's GeneralPlacementProperties to the new label engine
cimMap.GeneralPlacementProperties = cimMaplexGeneralPlacementProperties;
}
//Set the map's definition
map.SetDefinition(cimMap);
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//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
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine =
map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
//Current labeling engine is Standard labeling engine
var lineLablePosition = new CIMStandardLineLabelPosition
{
Perpendicular = true,
Parallel = false,
ProduceCurvedLabels = false,
Horizontal = false,
OnTop = true
};
theLabelClass.StandardLabelPlacementProperties.LineLabelPosition =
lineLablePosition;
}
else //Current labeling engine is Maplex labeling engine
{
theLabelClass.MaplexLabelPlacementProperties.LinePlacementMethod =
MaplexLinePlacementMethod.CenteredPerpendicularOnLine;
theLabelClass.MaplexLabelPlacementProperties.LineFeatureType =
MaplexLineFeatureType.General;
}
//theLabelClass.MaplexLabelPlacementProperties.LinePlacementMethod = MaplexLinePlacementMethod.CenteredPerpendicularOnLine;
lyrDefn.LabelClasses = listLabelClasses.ToArray(); //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//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
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine = map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
//Current labeling engine is Standard Labeling engine
theLabelClass.StandardLabelPlacementProperties.PolygonPlacementMethod =
StandardPolygonPlacementMethod.AlwaysHorizontal;
theLabelClass.StandardLabelPlacementProperties.PlaceOnlyInsidePolygon = true;
}
else
{
//Current labeling engine is Maplex labeling engine
theLabelClass.MaplexLabelPlacementProperties.PolygonFeatureType =
MaplexPolygonFeatureType.LandParcel;
theLabelClass.MaplexLabelPlacementProperties.AvoidPolygonHoles = true;
theLabelClass.MaplexLabelPlacementProperties.PolygonPlacementMethod =
MaplexPolygonPlacementMethod.HorizontalInPolygon;
theLabelClass.MaplexLabelPlacementProperties.CanPlaceLabelOutsidePolygon = true;
}
lyrDefn.LabelClasses = listLabelClasses.ToArray(); //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
//set the label's visiblity
featureLayer.SetLabelVisibility(true);
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine = map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
return;
}
//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 Orientation
theLabelClass.MaplexLabelPlacementProperties.GraticuleAlignment = true;
theLabelClass.MaplexLabelPlacementProperties.GraticuleAlignmentType = MaplexGraticuleAlignmentType.Curved;
lyrDefn.LabelClasses = listLabelClasses.ToArray(); //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine = map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
return;
}
//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 Orientation
theLabelClass.MaplexLabelPlacementProperties.AlignLabelToLineDirection = true;
lyrDefn.LabelClasses = listLabelClasses.ToArray(); //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine = map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
return;
}
//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 Rotation
CIMMaplexRotationProperties rotationProperties = new CIMMaplexRotationProperties
{
Enable = true, //Enable rotation
RotationField = "ELEVATION", //Field that is used to define rotation angle
AdditionalAngle = 15, //Additional rotation
RotationType = MaplexLabelRotationType.Arithmetic,
AlignmentType = MaplexRotationAlignmentType.Perpendicular,
AlignLabelToAngle = true
};
theLabelClass.MaplexLabelPlacementProperties.RotationProperties = rotationProperties;
lyrDefn.LabelClasses = listLabelClasses.ToArray(); //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine = map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
return;
}
//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();
//Spread Labels (words and characters to fill feature)
// Spread words to fill feature
theLabelClass.MaplexLabelPlacementProperties.SpreadWords = true;
//Spread Characters to a fixed limit of 50%
theLabelClass.MaplexLabelPlacementProperties.SpreadCharacters = true;
theLabelClass.MaplexLabelPlacementProperties.MaximumCharacterSpacing = 50.0;
lyrDefn.LabelClasses = listLabelClasses.ToArray(); //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Check if the label engine is Maplex or standard.
CIMGeneralPlacementProperties labelEngine = map.GetDefinition().GeneralPlacementProperties;
if (labelEngine is CIMStandardGeneralPlacementProperties)
{
return;
}
//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();
//If TextSymbol is a call-out the leader line anchor point can be modified
theLabelClass.MaplexLabelPlacementProperties.PolygonAnchorPointType = MaplexAnchorPointType.Perimeter;
lyrDefn.LabelClasses = [.. listLabelClasses]; //Set the labelClasses back
featureLayer.SetDefinition(lyrDefn); //set the layer's definition
});
}
{
var map = MapView.Active?.Map;
if (map == null)
return;
await QueuedTask.Run(() =>
{
//Create with initial visibility set to false. Add to current scene
var createparams = new LayerCreationParams(new Uri(sceneLayerUrl, UriKind.Absolute))
{
IsVisible = false
};
//cast to specific type of scene layer being created - in this case FeatureSceneLayer
var sceneLayer = LayerFactory.Instance.CreateLayer<Layer>(
createparams, map) as FeatureSceneLayer;
//or...specify the cast directly
var sceneLayer2 = LayerFactory.Instance.CreateLayer<FeatureSceneLayer>(
createparams, map);
//ditto for BuildingSceneLayer, PointCloudSceneLayer, IntegratedMeshSceneLayer
//...
});
}
{
var bsl_discipline = MapView.Active.Map.GetLayersAsFlattenedList().OfType<BuildingDisciplineSceneLayer>().FirstOrDefault(l => l.Name == "Architectural");
var disciplineName = bsl_discipline.GetDiscipline();
}
{
var bldgLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<BuildingSceneLayer>().First();
var disciplines = new Dictionary<string, BuildingDisciplineSceneLayer>();
//A Building layer has two children - Overview and FullModel
//Overview is a FeatureSceneLayer
//Full Model is a BuildingDisciplineSceneLayer that contains the disciplines
var fullModel = bldgLayer.FindLayers("Full Model").First()
as BuildingDisciplineSceneLayer;
//collect information on the disciplines
var name = fullModel.Name;
var discipline = fullModel.GetDiscipline();
//etc
//TODO - use collected information
disciplines.Add(discipline, fullModel);
//Discipline layers are composite layers too
foreach (var childDiscipline in fullModel.Layers
.OfType<BuildingDisciplineSceneLayer>())
{
//Discipline layers can also contain FeatureSceneLayers that render the
//individual full model contents
var content_names = string.Join(", ", childDiscipline.Layers
.OfType<FeatureSceneLayer>().Select(fl => fl.Name));
// Recursively call this "function" to go deeper
}
}
{
bsl = MapView.Active.Map.GetLayersAsFlattenedList()
.OfType<BuildingSceneLayer>().FirstOrDefault();
var scenelayerName = bsl.Name;
}
{
featSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList()
.OfType<FeatureSceneLayer>().FirstOrDefault();
if (!featSceneLayer.HasAssociatedFeatureService ||
!featSceneLayer.IsEditable)
{
//not supported - exit the function
}
//TODO continue editing here...
}
{
featSceneLayer = MapView.Active.Map.GetLayersAsFlattenedList()
.OfType<FeatureSceneLayer>().FirstOrDefault();
var scenelayerName = featSceneLayer?.Name;
}
{
//assume the geometry used in SelectFeaturesEx() is coming from a
//map tool...
//SketchType = SketchGeometryType.Rectangle;
//SketchOutputMode = SketchOutputMode.Screen;
var mapView = MapView.Active;
if (mapView == null)
return;
await QueuedTask.Run(() =>
{
var result = mapView.SelectFeaturesEx(geometry);
//Get scene layers with selections
var scene_layers = result.ToDictionary<FeatureSceneLayer>();
foreach (var kvp in scene_layers)
{
var scene_layer = kvp.Key as FeatureSceneLayer;
var sel_oids = kvp.Value;
//If there are attributes then get them
if (scene_layer.HasAssociatedFeatureService)
{
var insp = new Inspector();
foreach (var objectid in sel_oids)
{
insp.Load(scene_layer, objectid);
//TODO something with retrieved attributes
}
}
}
});
}
{
var sname = featSceneLayer.Name;
var mapView = MapView.Active;
if (mapView == null)
return;
await QueuedTask.Run(() =>
{
//Select all features within the current map view
var sz = mapView.GetViewSize();
var c_ll = new Coordinate2D(0, 0);
var c_ur = new Coordinate2D(sz.Width, sz.Height);
//Use screen coordinates for 3D selection on MapView
var env = EnvelopeBuilderEx.CreateEnvelope(c_ll, c_ur);
//HasAssociatedFeatureService does not matter for SelectFeaturesEx
//or GetFeaturesEx
var result = mapView.SelectFeaturesEx(env);
//var result = mapView.GetFeaturesEx(env);
//The list of object ids from SelectFeaturesEx
var oids1 = result.ToDictionary().Where(kvp => kvp.Key.Name == sname).First().Value;
//TODO - use the object ids
mapView.Map.ClearSelection();
});
}
{
var mapView = MapView.Active;
if (mapView == null)
return;
await QueuedTask.Run(() =>
{
if (!featSceneLayer.HasAssociatedFeatureService)
{
return;//no search or select
}
//Select all features within the current map view
var sz = mapView.GetViewSize();
var map_pt1 = mapView.ClientToMap(new System.Windows.Point(0, sz.Height));
var map_pt2 = mapView.ClientToMap(new System.Windows.Point(sz.Width, 0));
//Convert to an envelope
var temp_env = EnvelopeBuilderEx.CreateEnvelope(map_pt1, map_pt2, mapView.Map.SpatialReference);
//Project if needed to the layer spatial ref
SpatialReference sr = null;
using (var fc = featSceneLayer.GetFeatureClass())
using (var fdef = fc.GetDefinition())
{
sr = fdef.GetSpatialReference();
}
var env = GeometryEngine.Instance.Project(temp_env, sr) as Envelope;
//Set up a query filter
var sf = new SpatialQueryFilter()
{
FilterGeometry = env,
SpatialRelationship = SpatialRelationship.Intersects,
SubFields = "*"
};
//Select against the feature service
var select = featSceneLayer.Select(sf);
if (select.GetCount() > 0)
{
//enumerate over the selected features
using (var rc = select.Search())
{
while (rc.MoveNext())
{
using (var feature = rc.Current as Feature)
{
oid = feature.GetObjectID();
//etc.
}
}
}
}
mapView.Map.ClearSelection();
});
}
{
var trackAwareLayers = MapView.Active.Map.GetLayersAsFlattenedList()
.OfType<StreamLayer>().Where(sl => sl.IsTrackAware)?.ToList();
}
{
//Map must be a local scene
bool canCreateVoxel = (MapView.Active.ViewingMode == MapViewingMode.SceneLocal);
if (canCreateVoxel)
{
//TODO - use the voxel api methods
}
}
{
//Get selected layer if a voxel layer is selected
voxelLayer = MapView.Active.GetSelectedLayers().OfType<VoxelLayer>().FirstOrDefault();
if (voxelLayer == null)
{
//just get the first voxel layer in the TOC
voxelLayer = MapView.Active.Map.GetLayersAsFlattenedList().OfType<VoxelLayer>().FirstOrDefault();
if (voxelLayer == null)
{
return;
}
}
}
{
var surfaces = MapView.Active.GetSelectedIsosurfaces();
//set selected w/ MapView.Active.SelectVoxelIsosurface(isoSurface)
var slices = MapView.Active.GetSelectedSlices();
//set selected w/ MapView.Active.SelectVoxelSlice(slice)
var sections = MapView.Active.GetSelectedSections();
//set selected w/ MapView.Active.SelectVoxelSection(section)
var locked_sections = MapView.Active.GetSelectedLockedSections();
//set selected w/ MapView.Active.SelectVoxelLockedSection(locked_section)
}
{
MapMemberPropertiesChangedEvent.Subscribe((args) =>
{
var voxel = args.MapMembers.OfType<VoxelLayer>().FirstOrDefault();
if (voxel == null)
{
return;
}
//Anything changed on a voxel layer?
if (args.EventHints.Any(hint => hint == MapMemberEventHint.VoxelSelectedVariable))
{
//Voxel variable profile selection changed
var changed_variable_name = voxel.SelectedVariableProfile.Variable;
//TODO respond to change, use QueuedTask if needed
}
else if (args.EventHints.Any(hint => hint == MapMemberEventHint.Renderer))
{
//This can fire when a renderer becomes ready on a new layer; the selected variable profile
//is changed; visualization is changed, etc.
var renderer = voxel.SelectedVariableProfile.Renderer;
//TODO respond to change, use QueuedTask if needed
}
});
VoxelAssetChangedEvent.Subscribe((args) =>
{
//An asset changed on a voxel layer
System.Diagnostics.Debug.WriteLine("");
System.Diagnostics.Debug.WriteLine("VoxelAssetChangedEvent");
System.Diagnostics.Debug.WriteLine($" AssetType: {args.AssetType}, ChangeType: {args.ChangeType}");
if (args.ChangeType == VoxelAssetEventArgs.VoxelAssetChangeType.Remove)
{
return;
}
//Get "what"changed - add or update
//eg IsoSurface
VoxelLayer voxelLayer = null;
if (args.AssetType == VoxelAssetEventArgs.VoxelAssetType.Isosurface)
{
var surface = MapView.Active.GetSelectedIsosurfaces().FirstOrDefault();
//there will only be one selected...
if (surface != null)
{
voxelLayer = surface.Layer;
//TODO respond to change, use QueuedTask if needed
}
}
//Repeat for Slices, Sections, LockedSections...
//GetSelectedSlices(), GetSelectedSections(), GetSelectedLockedSections();
});
}
{
var mapView = MapView.Active;
await QueuedTask.Run(() =>
{
var slice = mapView?.GetSelectedSlices()?.FirstOrDefault();
if (slice != null)
{
//Do something with the slice
}
});
}
{
var mapView = MapView.Active;
await QueuedTask.Run(() =>
{
voxelLayer = null;
var slice = mapView?.GetSelectedSlices()?.FirstOrDefault();
if (slice != null)
{
voxelLayer = slice.Layer;
//TODO - use the layer
}
});
}
{
var section = MapView.Active?.GetSelectedSections()?.FirstOrDefault();
if (section != null)
{
//Do something with the section
}
}
{
voxelLayer = null;
var section = MapView.Active?.GetSelectedSections()?.FirstOrDefault();
if (section != null)
{
voxelLayer = section.Layer;
//TODO - use the layer
}
}
{
var locked_section = MapView.Active?.GetSelectedLockedSections()?.FirstOrDefault();
if (locked_section != null)
{
// Use the locked section
}
}
{
var locked_section = MapView.Active?.GetSelectedLockedSections()?.FirstOrDefault();
if (locked_section != null)
{
voxelLayer = locked_section.Layer;
//TODO - use the layer
}
}
{
var mapView = MapView.Active;
await QueuedTask.Run(() =>
{
var locked_section = mapView?.GetSelectedLockedSections()?.FirstOrDefault();
if (locked_section != null)
{
var variable = locked_section.Layer.GetVariableProfile(locked_section.VariableName);
locked_section.Layer.SetSelectedVariableProfile(variable);
}
});
}
{
var mapView = MapView.Active;
await QueuedTask.Run(() =>
{
if (voxelLayer.Visualization != VoxelVisualization.Surface)
{
voxelLayer.SetVisualization(VoxelVisualization.Surface);
}
voxelLayer.SetSectionContainerExpanded(true);
voxelLayer.SetLockedSectionContainerExpanded(true);
voxelLayer.SetLockedSectionContainerVisibility(true);
//Use the SelectedVariableProfile to get the sections
//via its associated volume
var volume = voxelLayer.SelectedVariableProfile.Volume;
//get the selected section
var section = mapView.GetSelectedSections().FirstOrDefault();
if (section == null)
{
section = volume.GetSections().FirstOrDefault();
}
if (section == null)
{
return;
}
//Lock the section (Creates a locked section, deletes
//the section)
//if (voxelLayer.CanLockSection(section))
// voxelLayer.LockSection(section);
if (volume.CanLockSection(section))
{
volume.LockSection(section);
}
});
}
{
var mapView = MapView.Active;
await QueuedTask.Run(() =>
{
if (voxelLayer.Visualization != VoxelVisualization.Surface)
{
voxelLayer.SetVisualization(VoxelVisualization.Surface);
}
voxelLayer.SetSectionContainerExpanded(true);
voxelLayer.SetSectionContainerVisibility(true);
voxelLayer.SetLockedSectionContainerExpanded(true);
//get the selected locked section
var locked_section = mapView.GetSelectedLockedSections().FirstOrDefault();
if (locked_section == null)
{
locked_section = voxelLayer.GetLockedSections().FirstOrDefault();
}
if (locked_section == null)
{
return;
}
//Unlock the locked section (Deletes the locked section, creates
//a section)
if (voxelLayer.CanUnlockSection(locked_section))
{
voxelLayer.UnlockSection(locked_section);
}
});
}
Target Platforms: Windows 11 Home, Pro, Enterprise (64 bit)