{
//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;
}
{
ProApp.Panes.OfType<IMapPane>().OrderBy((mp) => mp.MapView.Map.URI ?? mp.MapView.Map.Name);
}
{
//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);
}
}
{
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);
});
}
{
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)");
}
{
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;
}
// 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);
}
{
await QueuedTask.Run(() =>
{
//Create a point
var pt = MapPointBuilderEx.CreateMapPoint(x, y, spatialReference);
//Buffer it - for purpose of zoom
var poly = GeometryEngine.Instance.Buffer(pt, buffer_size);
//do we need to project the buffer polygon?
if (!mapView.Map.SpatialReference.IsEqual(poly.SpatialReference))
{
//project the polygon
poly = GeometryEngine.Instance.Project(poly, mapView.Map.SpatialReference);
}
//Zoom - add in a delay for animation effect
mapView.ZoomTo(poly, new TimeSpan(0, 0, 0, 3));
});
}
{
await QueuedTask.Run(() =>
{
//Get the first bookmark with the given name.
var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
{
// Manage the error - bookmark not found
}
//Zoom the view to the bookmark.
mapView.ZoomTo(bookmark);
});
}
{
await QueuedTask.Run(() =>
{
//Get the first bookmark with the given name.
var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
{
// Manage the error - bookmark not found
}
//Zoom the view to the bookmark.
mapView.ZoomToAsync(bookmark, TimeSpan.FromSeconds(2));
});
}
{
await QueuedTask.Run(() =>
{
//Zoom to all visible layers in the map.
var visibleLayers = mapView.Map.Layers.Where(l => l.IsVisible);
mapView.ZoomTo(visibleLayers);
});
}
{
await QueuedTask.Run(() =>
{
//Get the first bookmark with the given name.
var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
{
// Manage the error - bookmark not found
}
//Pan the view to the bookmark.
mapView.PanTo(bookmark);
});
}
{
//Get the first bookmark with the given name.
var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
{
// Manage the error - bookmark not found
}
//Pan the view to the bookmark.
mapView.PanToAsync(bookmark, TimeSpan.FromSeconds(2));
}
{
await QueuedTask.Run(() =>
{
//Pan to all visible layers in the map.
var visibleLayers = mapView.Map.Layers.Where(l => l.IsVisible);
mapView.PanTo(visibleLayers);
});
}
{
//Return the name of the map currently displayed in the active map view.
var result = mapView.Map.Name;
// Use the result variable as needed
}
{
await QueuedTask.Run(() =>
{
mapView.Map?.SetSelection(null);
});
}
{
//Selection tolerance for the map in pixels
var selectionTolerance = SelectionEnvironment.SelectionTolerance;
await QueuedTask.Run(() =>
{
//Get the map center
var mapExtent = mapView.Map.GetDefaultExtent();
var mapPoint = mapExtent.Center;
//Map center as screen point
var screenPoint = mapView.MapToScreen(mapPoint);
//Add selection tolerance pixels to get a "radius".
var radiusScreenPoint = new System.Windows.Point(screenPoint.X + selectionTolerance, screenPoint.Y);
var radiusMapPoint = mapView.ScreenToMap(radiusScreenPoint);
//Calculate the selection tolerance distance in map units.
var searchRadius = GeometryEngine.Instance.Distance(mapPoint, radiusMapPoint);
});
}
{
//Zoom to the selected layers in the TOC
var featureLayers = mapView.Map.Layers.OfType<FeatureLayer>();
mapView.SelectLayers(featureLayers.ToList());
}
{
await QueuedTask.Run(() =>
{
//Get the selected features from the map and filter out the standalone table selection.
var selectedFeatures = mapView.Map.GetSelection();
//Flash the collection of features.
mapView.FlashFeature(selectedFeatures);
});
}
{
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);
}
{
await QueuedTask.Run(() =>
{
//Get the layer to be masked
var lineLyrToBeMasked = mapView.Map.Layers.FirstOrDefault(lyr => lyr.Name == "TestLine") as FeatureLayer;
//Get the layer's definition
var lyrDefn = lineLyrToBeMasked.GetDefinition();
//Create an array of Masking layers (polygon only)
//Set the LayerMasks property of the Masked layer
lyrDefn.LayerMasks = ["CIMPATH=map3/testpoly.xml"];
//Re-set the Masked layer's definition
lineLyrToBeMasked.SetDefinition(lyrDefn);
});
}
{
await QueuedTask.Run(() =>
{
//Adding a new bookmark using the active view.
mapView.Map.AddBookmark(mapView, bookmarkName);
});
}
{
await QueuedTask.Run(() =>
{
//Set properties for Camera
CIMViewCamera cimCamera = new()
{
X = camera.X,
Y = camera.Y,
Z = camera.Z,
Scale = camera.Scale,
Pitch = camera.Pitch,
Heading = camera.Heading,
Roll = camera.Roll
};
//Create new CIM bookmark and populate its properties
var cimBookmark = new CIMBookmark() { Camera = cimCamera, Name = cameraName, ThumbnailImagePath = "" };
//Add a new bookmark for the active map.
mapView.Map.AddBookmark(cimBookmark);
});
}
{
await QueuedTask.Run(() =>
{
//Return the collection of bookmarks for the map.
var result = mapView.Map.GetBookmarks();
// Use the bookmarks (if any)
});
}
{
await QueuedTask.Run(() =>
{
var map = mapView.Map;
//Find the first bookmark with the name
var bookmark = map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
{
//Bookmark not found
}
//Move the bookmark to the top of the list
map.MoveBookmark(bookmark, 0);
});
}
{
oldBookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
oldBookmark.Rename(newBookmarkName);
}
{
await QueuedTask.Run(() =>
{
//Find the first bookmark with the name
var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
if (bookmark == null)
{
//Bookmark not found
}
//Remove the bookmark
mapView.Map.RemoveBookmark(bookmark);
});
}
{
var animation = mapView.Map.Animation;
var duration = animation.Duration;
if (duration == TimeSpan.Zero)
{
return;
}
var factor = length.TotalSeconds / duration.TotalSeconds;
animation.ScaleDuration(factor);
}
{
var animation = mapView.Map.Animation;
var duration = animation.Duration;
if (duration == TimeSpan.Zero || duration <= afterTime)
{
// Nothing to scale, leave
}
var factor = length.TotalSeconds / (duration.TotalSeconds - afterTime.TotalSeconds);
animation.ScaleDuration(afterTime, duration, factor);
}
{
var animation = mapView.Map.Animation;
var cameraTrack = animation.Tracks.OfType<CameraTrack>().First(); //There will always be only 1 CameraTrack in the animation.
var result = cameraTrack.Keyframes.OfType<CameraKeyframe>().ToList();
//Use the camera keyframes (if any)
}
{
//Return the collection representing the camera for each frame in animation.
await QueuedTask.Run(() =>
{
var animation = mapView.Map.Animation;
var cameras = new List<Camera>();
//We will use ticks here rather than milliseconds to get the highest precision possible.
var ticksPerFrame = Convert.ToInt64(animation.Duration.Ticks / (animation.NumberOfFrames - 1));
for (int i = 0; i < animation.NumberOfFrames; i++)
{
var time = TimeSpan.FromTicks(i * ticksPerFrame);
//Because of rounding for ticks the last calculated time may be greater than the duration.
if (time > animation.Duration)
{
time = animation.Duration;
}
cameras.Add(mapView.Animation.GetCameraAtTime(time));
}
// Use cameras
});
}
{
//Return the collection representing the map time for each frame in animation.
await QueuedTask.Run(() =>
{
var animation = mapView.Map.Animation;
var timeRanges = new List<TimeRange>();
//We will use ticks here rather than milliseconds to get the highest precision possible.
var ticksPerFrame = Convert.ToInt64(animation.Duration.Ticks / (animation.NumberOfFrames - 1));
for (int i = 0; i < animation.NumberOfFrames; i++)
{
var time = TimeSpan.FromTicks(i * ticksPerFrame);
//Because of rounding for ticks the last calculated time may be greater than the duration.
if (time > animation.Duration)
{
time = animation.Duration;
}
timeRanges.Add(mapView.Animation.GetCurrentTimeAtTime(time));
}
// Use timeRanges;
});
}
{
//Return the collection representing the map time for each frame in animation.
await QueuedTask.Run(() =>
{
var animation = mapView.Map.Animation;
var ranges = new List<ArcGIS.Desktop.Mapping.Range>();
//We will use ticks here rather than milliseconds to get the highest precision possible.
var ticksPerFrame = Convert.ToInt64(animation.Duration.Ticks / (animation.NumberOfFrames - 1));
for (int i = 0; i < animation.NumberOfFrames; i++)
{
var time = TimeSpan.FromTicks(i * ticksPerFrame);
//Because of rounding for ticks the last calculated time may be greeting than the duration.
if (time > animation.Duration)
{
time = animation.Duration;
}
ranges.Add(mapView.Animation.GetCurrentRangeAtTime(time));
}
// Use ranges
});
}
{
var animation = mapView.Map.Animation;
var cameraTrack = animation.Tracks.OfType<CameraTrack>().First(); //There will always be only 1 CameraTrack in the animation.
cameraTrack.CreateKeyframe(mapView.Camera, atTime, AnimationTransition.FixedArc);
}
{
var animation = mapView.Map.Animation;
var timeTrack = animation.Tracks.OfType<TimeTrack>().First(); //There will always be only 1 TimeTrack in the animation.
timeTrack.CreateKeyframe(mapView.Time, atTime, AnimationTransition.Linear);
}
{
var animation = mapView.Map.Animation;
var rangeTrack = animation.Tracks.OfType<RangeTrack>().First(); //There will always be only 1 RangeTrack in the animation.
rangeTrack.CreateKeyframe(range, atTime, AnimationTransition.Linear);
}
{
var animation = mapView.Map.Animation;
var layerTrack = animation.Tracks.OfType<LayerTrack>().First(); //There will always be only 1 LayerTrack in the animation.
layerTrack.CreateKeyframe(layer, atTime, true, transparency, AnimationTransition.Linear);
}
{
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);
}
});
}
{
// find the first TIN layer
tinLayer = mapView.Map.GetLayersAsFlattenedList().OfType<TinLayer>().FirstOrDefault();
// find the first Terrain layer
terrainLayer = mapView.Map.GetLayersAsFlattenedList().OfType<TerrainLayer>().FirstOrDefault();
// find the first LAS dataset layer
lasDatasetLayer = mapView.Map.GetLayersAsFlattenedList().OfType<LasDatasetLayer>().FirstOrDefault();
// find the first surface layer
surfaceLayer = mapView.Map.GetLayersAsFlattenedList().OfType<SurfaceLayer>().FirstOrDefault();
}
{
var tinCP_renderers = new TinLayerCreationParams(tinDataset)
{
Name = "My TIN layer",
IsVisible = true
};
// define the node renderer - use defaults
var node_rd = new TinNodeRendererDefinition();
// define the face/surface renderer
var face_rd = new TinFaceClassBreaksRendererDefinition();
face_rd.ClassificationMethod = ClassificationMethod.NaturalBreaks;
// accept default color ramp, breakCount
// set up the renderer dictionary
var rendererDict = new Dictionary<SurfaceRendererTarget, TinRendererDefinition>
{
{ SurfaceRendererTarget.Points, node_rd },
{ SurfaceRendererTarget.Surface, face_rd }
};
// assign the dictionary to the creation params
tinCP_renderers.RendererDefinitions = rendererDict;
await QueuedTask.Run(() =>
{
// create the layer
var tinLayer_rd = LayerFactory.Instance.CreateLayer<TinLayer>(tinCP_renderers, mapView.Map);
});
}
{
tinLayer = null;
MapPoint observerPoint = null;
MapPoint targetPoint = null;
CIMPointSymbol obstructionPointSymbol = null;
CIMLineSymbol visibleLineSymbol = null;
CIMLineSymbol invisibleLineSymbol = null;
var losParams = new LineOfSightParams();
losParams.ObserverPoint = observerPoint;
losParams.TargetPoint = targetPoint;
// add offsets if appropriate
// losParams.ObserverHeightOffset = observerOffset;
// losParams.TargetHeightOffset = targerOffset;
// add obstruction feature class if appropriate (multipatch)
//losParams.ObstructionsMultipatchFeatureClass = obsFeatureClass;
// set output spatial reference
losParams.OutputSpatialReference = mapView.Map.SpatialReference;
LineOfSightResult results = null;
try
{
await QueuedTask.Run(() =>
{
if (tinLayer.CanGetLineOfSight(losParams))
{
results = tinLayer.GetLineOfSight(losParams);
}
});
}
catch (Exception)
{
// handle exception
}
if (results != null)
{
bool targetIsVisibleFromObserverPoint = results.IsTargetVisibleFromObserverPoint;
//These properties are not used. They will always be false
// results.IsTargetVisibleFromVisibleLine;
// results.IsTargetVisibleFromInvisibleLine;
if (results.VisibleLine != null)
{
mapView.AddOverlay(results.VisibleLine, visibleLineSymbol.MakeSymbolReference());
}
if (results.InvisibleLine != null)
{
mapView.AddOverlay(results.VisibleLine, invisibleLineSymbol.MakeSymbolReference());
}
if (results.ObstructionPoint != null)
{
mapView.AddOverlay(results.ObstructionPoint, obstructionPointSymbol.MakeSymbolReference());
}
}
}
{
//Point Feature layer to convert into graphics
var lyr = mapView?.Map?.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault(s => s.ShapeType == esriGeometryType.esriGeometryPoint);
if (lyr == null)
{
return;
}
await QueuedTask.Run(() =>
{
//Point symbol for graphics
var pointSymbol = SymbolFactory.Instance.ConstructPointSymbol(CIMColor.CreateRGBColor(100, 255, 40), 10, SimpleMarkerStyle.Circle);
//Collection to hold the point graphics
var listGraphicElements = new List<CIMGraphic>();
//Iterate through each point feature in the feature layer
using (RowCursor rows = lyr.Search()) //execute
{
int i = 0;
while (rows.MoveNext())
{
using var feature = rows.Current as Feature;
//Create a point graphic for the feature
var crimePt = feature.GetShape() as MapPoint;
if (crimePt != null)
{
var cimGraphicElement = new CIMPointGraphic
{
Location = crimePt, //MapPoint
Symbol = pointSymbol.MakeSymbolReference()
};
//Add the point feature to the collection
listGraphicElements.Add(cimGraphicElement);
i++;
}
}
}
//Magic happens...Add all the features to the Graphics layer
graphicsLayer.AddElements(listGraphicElements);
});
}
{
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;
}
{
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();
}
{
//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;
}
}
}
Target Platforms: Windows 11 Home, Pro, Enterprise (64 bit)