//Get the current active TOC content type for the map view varmapTOCContentType=MapView.Active.CurrentMapTOCContent;
Set the Active Map TOC content type
//Get the current active TOC content type for the map view varmapTOCContentType=(int)MapView.Active.CurrentMapTOCContent;//increment to the next tab whatever it ismapTOCContentType++;//Can we set this type on the TOC?if(MapView.Active.CanSetMapTOCContent((MapTOCContentType)mapTOCContentType))//Set it - must be on the UI! - No QueuedTaskMapView.Active.SetMapTOCContentAsync((MapTOCContentType)mapTOCContentType);else{mapTOCContentType=(int)MapTOCContentType.DrawingOrder;//Set it - must be on the UI! - No QueuedTaskMapView.Active.SetMapTOCContentAsync((MapTOCContentType)mapTOCContentType);}
Find a MapView by its Caption
stringmapPaneCaption="USNationalParks";IMapPanemapViewPane=FrameworkApplication.Panes.OfType<IMapPane>().FirstOrDefault((p)=>p.Caption==mapPaneCaption);mapView=null;if(mapViewPane!=null){// activate the MapPane(mapViewPaneasPane).Activate();if(mapView!=null){// get the layers selected in the map's TOCvarselectedLayers=mapView.GetSelectedLayers();}}
Test if the view is 3D
//Determine whether the viewing mode is SceneLocal or SceneGlobalvarresult=mapView.ViewingMode==MapViewingMode.SceneLocal||mapView.ViewingMode==MapViewingMode.SceneGlobal;// Use the result variable as needed
Set ViewingMode
//Check if the view can be set to SceneLocal and if it can set it.varresult=mapView.CanSetViewingMode(MapViewingMode.SceneLocal);if(result)mapView.SetViewingModeAsync(MapViewingMode.SceneLocal);
Enable View Linking
//Set the view linking mode to Center and Scale.MapView.LinkMode=LinkMode.Center|LinkMode.Scale;
Export the contents of a scene to an exchange format such as glTF and STL.
// Validate the current active view. Only a local scene can be exported.boolCanExportScene3DObjects=MapView.Active?.ViewingMode==MapViewingMode.SceneLocal;if(CanExportScene3DObjects){// Create a scene content export format, export the scene context as a glTF filevarexportFormat=newExportSceneContentsFormat(){Extent=mapView.Extent,// sets Extent propertyFolderPath=@"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 fileSaveTextures=true//sets whether to save textures};// Export the scene content as 3D objectsmapView.ExportScene3DObjects(exportFormat);}
Update MapView Extent (Zoom, Pan etc)
Go To Previous Camera
//Zoom to the selected layers in the TOCif(mapView.HasPreviousCamera())mapView.PreviousCameraAsync();
Go To Next Camera
//Zoom to the selected layers in the TOCif(mapView.HasNextCamera())mapView.NextCameraAsync();
Zoom To Full Extent
// Note: Needs QueuedTask to run{//Zoom to the map's full extentmapView.ZoomToFullExtent();}
Zoom To Full Extent Async
//Zoom to the map's full extentmapView.ZoomToFullExtentAsync(TimeSpan.FromSeconds(2));
Fixed Zoom In
// Note: Needs QueuedTask to run{//Zoom in the map view by a fixed amount.mapView.ZoomInFixed();}
Fixed Zoom In Async
//Zoom in the map view by a fixed amount.mapView.ZoomInFixedAsync();
Fixed Zoom Out
// Note: Needs QueuedTask to run{//Zoom out in the map view by a fixed amount.mapView.ZoomOutFixed();}
Fixed Zoom Out Async
//Zoom in the map view by a fixed amount.mapView.ZoomOutFixedAsync();
Zoom To an Extent
envelope=EnvelopeBuilderEx.CreateEnvelope(xMin,yMin,xMax,yMax,spatialReference);//Zoom the view to a given extent.mapView.ZoomToAsync(envelope,TimeSpan.FromSeconds(2));
Zoom To a Point
// Note: Needs QueuedTask to run{//Create a pointvarpt=MapPointBuilderEx.CreateMapPoint(x,y,spatialReference);//Buffer it - for purpose of zoomvarpoly=GeometryEngine.Instance.Buffer(pt,buffer_size);//do we need to project the buffer polygon?if(!MapView.Active.Map.SpatialReference.IsEqual(poly.SpatialReference)){//project the polygonpoly=GeometryEngine.Instance.Project(poly,MapView.Active.Map.SpatialReference);}//Zoom - add in a delay for animation effectmapView.ZoomTo(poly,newTimeSpan(0,0,0,3));}
Zoom To Selected Features with a timespan
// Note: Needs QueuedTask to run{//Zoom to the map's selected features.mapView.ZoomToSelected(TimeSpan.FromSeconds(3));}
Zoom Async To Selected Features with a timespan
//Zoom to the map's selected features.mapView.ZoomToSelectedAsync(TimeSpan.FromSeconds(2));
Zoom To Bookmark by name
// Note: Needs QueuedTask to run{//Get the first bookmark with the given name.varbookmark=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);}
Zoom Async To Bookmark by name
// Note: Needs QueuedTask to run//Get the first bookmark with the given name.varbookmark=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));
Zoom To Visible Layers
// Note: Needs QueuedTask to run{//Zoom to all visible layers in the map.varvisibleLayers=mapView.Map.Layers.Where(l =>l.IsVisible);mapView.ZoomTo(visibleLayers);}
Zoom To Selected Layers
//Zoom to the selected layers in the TOCvarselectedLayers=mapView.GetSelectedLayers();mapView.ZoomToAsync(selectedLayers);
// Note: Needs QueuedTask to run{//Pan the view to a given extent.envelope=EnvelopeBuilderEx.CreateEnvelope(xMin,yMin,xMax,yMax,spatialReference);mapView.PanTo(envelope);}
Pan Async To an Extent
//Create the envelopeenvelope=EnvelopeBuilderEx.CreateEnvelope(xMin,yMin,xMax,yMax,spatialReference);//Pan the view to a given extent.mapView.PanToAsync(envelope,TimeSpan.FromSeconds(2));
Pan To Selected Features
// Note: Needs QueuedTask to run{//Pan to the map's selected features.mapView.PanToSelected();}
Pan AsyncTo Selected Features
//Pan to the map's selected features.mapView.PanToSelectedAsync(TimeSpan.FromSeconds(2));
Pan To Bookmark
//Note: Needs QueuedTask to run{//Get the first bookmark with the given name.varbookmark=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);}
Pan To Bookmark Async
//Get the first bookmark with the given name.varbookmark=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));
Pan To Visible Layers
// Note: Needs QueuedTask to run{//Pan to all visible layers in the map.varvisibleLayers=mapView.Map.Layers.Where(l =>l.IsVisible);mapView.PanTo(visibleLayers);}
Pan To Selected Layers Asynchronous
//Pan to the selected layers in the TOCvarselectedLayers=mapView.GetSelectedLayers();mapView.PanToAsync(selectedLayers);
Rotate the map view
//Get the camera for the view, adjust the heading and zoom to the new camera position.camera=mapView.Camera;camera.Heading=heading;awaitmapView.ZoomToAsync(camera,TimeSpan.Zero);//Or synchronouslymapView.ZoomTo(camera,TimeSpan.Zero);
Expand Extent
//Note: Needs QueuedTask to run{//Expand the current extent by the given ratio.varextent=mapView.Extent;varnewExtent=GeometryEngine.Instance.Expand(extent,dx,dy,true);mapView.ZoomTo(newExtent);}
Maps
Get the active map's name
//Return the name of the map currently displayed in the active map view.varresult=mapView.Map.Name;// Use the result variable as needed
Clear all selection in an Active map
// Note: Needs QueuedTask to run{MapView.Active.Map?.SetSelection(null);}
Calculate Selection tolerance in map units
//Selection tolerance for the map in pixelsvarselectionTolerance=SelectionEnvironment.SelectionTolerance;// Note: Needs QueuedTask to run{//Get the map centervarmapExtent=MapView.Active.Map.GetDefaultExtent();varmapPoint=mapExtent.Center;//Map center as screen pointvarscreenPoint=MapView.Active.MapToScreen(mapPoint);//Add selection tolerance pixels to get a "radius".varradiusScreenPoint=newSystem.Windows.Point(screenPoint.X+selectionTolerance,screenPoint.Y);varradiusMapPoint=MapView.Active.ScreenToMap(radiusScreenPoint);//Calculate the selection tolerance distance in map units.varsearchRadius=GeometryEngine.Instance.Distance(mapPoint,radiusMapPoint);}
MapView Overlay Control
//Create a Progress Bar user controlSystem.Windows.Controls.ProgressBarprogressBarControl=new(){//Configure the progress barMinimum=0,Maximum=100,IsIndeterminate=true,Width=300,Value=10,Height=25,Visibility=System.Windows.Visibility.Visible};//Create a MapViewOverlayControl. varmapViewOverlayControl=newMapViewOverlayControl(progressBarControl,true,true,true,OverlayControlRelativePosition.BottomCenter,.5,.8);//Add to the active mapMapView.Active.AddOverlayControl(mapViewOverlayControl);// Note: Needs QueuedTask to run{//Wait 3 seconds to remove the progress bar from the map.Thread.Sleep(3000);}//Remove from active mapMapView.Active.RemoveOverlayControl(mapViewOverlayControl);
Layers
Select all feature layers in TOC
//Zoom to the selected layers in the TOCvarfeatureLayers=mapView.Map.Layers.OfType<FeatureLayer>();mapView.SelectLayers(featureLayers.ToList());
Flash selected features
// Note: Needs QueuedTask to run{//Get the selected features from the map and filter out the standalone table selection.varselectedFeatures=mapView.Map.GetSelection();//Flash the collection of features.mapView.FlashFeature(selectedFeatures);}
Check if layer is visible in the current map view
if(layer==null){// no layers in the map, leave}if(mapView==null){// no active map view, leave}boolisLayerVisibleInView=layer.IsVisibleInView(mapView);if(isLayerVisibleInView){//Do Something}
Select a layer and open its layer properties page
// select it in the TOCList<Layer>layersToSelect=[featureLayer];MapView.Active.SelectLayers(layersToSelect);// now execute the layer properties commandvarwrapper=FrameworkApplication.GetPlugInWrapper("esri_mapping_selectedLayerPropertiesButton");varcommand=wrapperasICommand;if(command==null){// the command is not found, leave}// execute the commandif(command.CanExecute(null))command.Execute(null);
Clear selection for a specific layer
if(featureLayer!=null){// Note: Needs QueuedTask to run{featureLayer.ClearSelection();}}
Display Table pane for Map Member
mapMember=MapView.Active.Map.GetLayersAsFlattenedList().OfType<MapMember>().FirstOrDefault();//Gets or creates the CIMMapTableView for a MapMember.varmapTableView=FrameworkApplication.Panes.GetMapTableView(mapMember);//Configure the table viewmapTableView.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.vartablePane=FrameworkApplication.Panes.OpenTablePane(mapTableView);
TableView
Set Table ViewingMode
// change to "selected record" modetableView.SetViewMode(TableViewMode.eSelectedRecords);
// set the valuetableView.ShowFieldAlias=true;// OR toggle itif(tableView.CanToggleFieldAlias)tableView.ToggleFieldAlias();
Toggle Subtype Descriptions
// set the valuetableView.ShowSubtypeDomainDescriptions=true;// OR toggle itif(tableView.CanToggleSubtypeDomainDescriptions)tableView.ToggleSubtypeDomainDescriptionsAsync();
Get the active row
// get the active row indexintrowIndex=tableView.ActiveRowIndex;
Change the active row
// get the active row indexintrowIndex=tableView.ActiveRowIndex;// move to a different rowvarnewIndex=10+rowIndex;tableView.BringIntoView(newIndex);
Get the active object ID
// get the active objectIDlong?OID=tableView.ActiveObjectId;
Translate between rowIndex and objectID
// get the active row indexintrowIndex=tableView.ActiveRowIndex;// increaseintnewIndex=rowIndex+10;// get the objectIDlongnewOID=tableView.GetObjectIdAsync(newIndex).Result;// get the rowIndex for a specific objectID// 2nd parameter indicates if the search only occurs for the pages loaded// if pass false, then in the worst case, a full table scan will occur to // find the objectID.longOID=100;varidx=tableView.GetRowIndexAsync(OID,true);
Get selected rows or row indexes
// Note: Needs QueuedTask to run{// get the set of selected objectIDs varselOids=tableView.GetSelectedObjectIds();// get the set of selected row indexesvarselRows=tableView.GetSelectedRowIndexes();}
Change selected rows
// Note: Needs QueuedTask to run{// set of selected OIDSvarnewoids=newList<long>();newoids.AddRange([10,15,17]);tableView.Select(newoids,true);// add to set of selected row indexesvarselRows=tableView.GetSelectedRowIndexes();varnewRows=newList<long>(selRows);newRows.AddRange([21,35]);tableView.Select(newRows,false);}
Select all rows
if(tableView.CanSelectAll)tableView.SelectAll();
Toggle, Switch, Clear Selection
// toggle the active rows selectionif(tableView.CanToggleRowSelection)tableView.ToggleRowSelection();// switch the selectionif(tableView.CanSwitchSelection)tableView.SwitchSelection();// clear the selectionif(tableView.CanClearSelection)tableView.ClearSelection();
// Note: Needs QueuedTask to run{IReadOnlyList<long>highlightedOIDs=null;if(tableView.CanGetHighlightedObjectIds)// get the set of selected objectIDs highlightedOIDs=tableView.GetHighlightedObjectIds();}
Change highlighted rows
// Note: Needs QueuedTask to run{// get list of current selected objectIDsIReadOnlyList<long>selectedObjectIds=tableView.GetSelectedObjectIds();List<long>idsToHighlight=[];// add the first two selected objectIds to highlightif(selectedObjectIds.Count>=2){idsToHighlight.Add(selectedObjectIds[0]);idsToHighlight.Add(selectedObjectIds[1]);}// highlightif(tableView.CanHighlight)tableView.Highlight(idsToHighlight,true);}
Toggle, Switch, Clear Highlights
// toggle the active rows selectionif(tableView.CanToggleRowHighlight)tableView.ToggleRowHighlight();// switch highlighted rowsif(tableView.CanSwitchHighlight)tableView.SwitchHighlight();// clear the highlightsif(tableView.CanClearHighlighted)tableView.ClearHighlighted();
// field accessvarflds=tableView.GetFields();varfldIdx=tableView.GetFieldIndex("STATE_NAME");varfldDesc=tableView.GetField(fldIdx);
Get or set the Active Field
// get active field, active field namevaractiveFieldIdx=tableView.ActiveFieldIndex;varfldDesc=tableView.GetField(activeFieldIdx);varfldName=fldDesc.Name;// set active field by nametableView.SetActiveField("STATE_NAME");// or set active field by indextableView.SetActiveField(3);
Select Fields
// get selected fieldsvarselectedfields=tableView.GetSelectedFields();// set selected fieldstableView.SetSelectedFields(["CITY_FIPS","STATE_FIPS"]);
// get list of hidden fieldsvarhiddenFields=tableView.GetHiddenFields();// show all fieldsif(tableView.CanShowAllFields)tableView.ShowAllFields();// hide only "CITY_FIPS", "STATE_FIPS"if(tableView.CanShowAllFields){// show all fieldstableView.ShowAllFields();tableView.SetHiddenFields(["CITY_FIPS","STATE_FIPS"]);}// add "STATE_NAME to set of hidden fieldstableView.SetHiddenFields(["STATE_NAME"]);// hide selected fieldsif(tableView.CanHideSelectedFields)tableView.HideSelectedFields();
Freeze Fields
// get list of frozen fieldsvarfrozenfields=tableView.GetFrozenFields();// unfreeze all fieldstableView.ClearAllFrozenFieldsAsync();// freeze a set of fieldstableView.SetFrozenFieldsAsync(["CITY_FIPS","STATE_FIPS"]);
Sort
// sort the active field descendingif(tableView.CanSortDescending)tableView.SortDescending();// sort the active field ascendingif(tableView.CanSortAscending)tableView.SortAscending();// perform a custom sort programmaticallyif(tableView.CanCustomSort){// sort fieldsDictionary<string,FieldSortInfo>dict=new(){{"STATE_NAME",FieldSortInfo.Asc},{"CITY_NAME",FieldSortInfo.Desc}};tableView.SortAsync(dict);}// perform a custom sort via the UIif(tableView.CanCustomSort)tableView.CustomSort();
Find and Replace
// launch the find UIif(tableView.CanFind)tableView.Find();// or launch the find and replace UIif(tableView.CanFindAndReplace)tableView.FindAndReplace();
GoTo TableView
// launch the GoTo UIif(tableView.CanGoTo)tableView.GoTo();
// find all the table panes (table panes hosting map data)vartablePanes=FrameworkApplication.Panes.OfType<ITablePane>();vartablePane=tablePanes.FirstOrDefault(p =>pisITablePaneEx{Caption:"oldCaption"});if(tablePaneisITablePaneExtablePaneEx)tablePaneEx.Caption="newCaption";// find all the external table panes (table panes hosting external data)varexternalPanes=FrameworkApplication.Panes.OfType<IExternalTablePane>();varexternalTablePane=externalPanes.FirstOrDefault(p =>p.Caption=="oldCaption");if(externalTablePane!=null)externalTablePane.Caption="newCaption";
Get TableView from table pane
// find all the table panes (table panes hosting map data)vartablePanes=FrameworkApplication.Panes.OfType<ITablePane>();vartablePane=tablePanes.FirstOrDefault(p =>pisITablePaneEx{Caption:"caption"});if(tablePaneisITablePaneExtablePaneEx)tableView=tablePaneEx.TableView;// if it's not found, maybe it's an external table paneif(tableView==null){// find all the external table panes (table panes hosting external data)varexternalPanes=FrameworkApplication.Panes.OfType<IExternalTablePane>();varexternalTablePane=externalPanes.FirstOrDefault(p =>p.Caption=="caption");if(externalTablePane!=null)tableView=externalTablePane.TableView;}
Features
Mask feature
// Note: Needs QueuedTask to run{//Get the layer to be maskedvarlineLyrToBeMasked=MapView.Active.Map.Layers.FirstOrDefault(lyr =>lyr.Name=="TestLine")asFeatureLayer;//Get the layer's definitionvarlyrDefn=lineLyrToBeMasked.GetDefinition();//Create an array of Masking layers (polygon only)//Set the LayerMasks property of the Masked layerlyrDefn.LayerMasks=["CIMPATH=map3/testpoly.xml"];//Re-set the Masked layer's definitionlineLyrToBeMasked.SetDefinition(lyrDefn);}
Bookmarks
Create a new bookmark using the active map view
// Note: Needs QueuedTask to run{//Adding a new bookmark using the active view.mapView.Map.AddBookmark(mapView,bookmarkName);}
Add New Bookmark from CIMBookmark
// Note: Needs QueuedTask to run{//Set properties for CameraCIMViewCameracimCamera=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 propertiesvarcimBookmark=newCIMBookmark(){Camera=cimCamera,Name=cameraName,ThumbnailImagePath=""};//Add a new bookmark for the active map.mapView.Map.AddBookmark(cimBookmark);}
Get the collection of bookmarks for the project
//Get the collection of bookmarks for the project.varresult=Project.Current.GetBookmarks();// Use the bookmarks (if any)
Get Map Bookmarks
// Note: Needs QueuedTask to run{//Return the collection of bookmarks for the map.varresult=mapView.Map.GetBookmarks();// Use the bookmarks (if any)}
Move Bookmark to the Top
// Note: Needs QueuedTask to run{varmap=mapView.Map;//Find the first bookmark with the namevarbookmark=map.GetBookmarks().FirstOrDefault(b =>b.Name==bookmarkName);if(bookmark==null){//Bookmark not found}//Move the bookmark to the top of the listmap.MoveBookmark(bookmark,0);}
// Note: Needs QueuedTask to run{//Find the first bookmark with the namevarbookmark=mapView.Map.GetBookmarks().FirstOrDefault(b =>b.Name==bookmarkName);if(bookmark==null){//Bookmark not found}//Remove the bookmarkmapView.Map.RemoveBookmark(bookmark);}
Change the thumbnail for a bookmark
//Set the thumbnail to an image on disk, i.e. C:\Pictures\MyPicture.png.BitmapImageimage=new(newUri(imagePath,UriKind.RelativeOrAbsolute));oldBookmark.SetThumbnail(image);
Update Bookmark
// Note: Needs QueuedTask to run{//Update the bookmark using the active map view.oldBookmark.Update(mapView);}
Update Extent for a Bookmark
// Note : Needs QueuedTask to run{//Get the bookmark's definitionvarbookmarkDef=oldBookmark.GetDefinition();//Modify the bookmark's locationbookmarkDef.Location=envelope;//Clear the camera as it is no longer valid.bookmarkDef.Camera=null;//Set the bookmark definitionoldBookmark.SetDefinition(bookmarkDef);}
Time
Step forward in time by 1 month
//Step current map time forward by 1 monthTimeDeltatimeDelta=new(1,TimeUnit.Months);mapView.Time=mapView.Time.Offset(timeDelta);
varanimation=mapView.Map.Animation;varduration=animation.Duration;if(duration==TimeSpan.Zero||duration<=afterTime){// Nothing to scale, leave}varfactor=length.TotalSeconds/(duration.TotalSeconds-afterTime.TotalSeconds);animation.ScaleDuration(afterTime,duration,factor);
Camera Keyframes
varanimation=mapView.Map.Animation;varcameraTrack=animation.Tracks.OfType<CameraTrack>().First();//There will always be only 1 CameraTrack in the animation.varresult=cameraTrack.Keyframes.OfType<CameraKeyframe>().ToList();//Use the camera keyframes (if any)
Interpolate Camera
//Return the collection representing the camera for each frame in animation.// Note: Needs QueuedTask to run{varanimation=mapView.Map.Animation;varcameras=newList<Camera>();//We will use ticks here rather than milliseconds to get the highest precision possible.varticksPerFrame=Convert.ToInt64(animation.Duration.Ticks/(animation.NumberOfFrames-1));for(inti=0;i<animation.NumberOfFrames;i++){vartime=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}
Interpolate Time
//Return the collection representing the map time for each frame in animation.// Note: Needs QueuedTask to run{varanimation=mapView.Map.Animation;vartimeRanges=newList<TimeRange>();//We will use ticks here rather than milliseconds to get the highest precision possible.varticksPerFrame=Convert.ToInt64(animation.Duration.Ticks/(animation.NumberOfFrames-1));for(inti=0;i<animation.NumberOfFrames;i++){vartime=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;}
Interpolate Range
//Return the collection representing the map time for each frame in animation.// Note: Needs QueuedTask to run{varanimation=mapView.Map.Animation;varranges=newList<ArcGIS.Desktop.Mapping.Range>();//We will use ticks here rather than milliseconds to get the highest precision possible.varticksPerFrame=Convert.ToInt64(animation.Duration.Ticks/(animation.NumberOfFrames-1));for(inti=0;i<animation.NumberOfFrames;i++){vartime=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}
Create Camera Keyframe
varanimation=mapView.Map.Animation;varcameraTrack=animation.Tracks.OfType<CameraTrack>().First();//There will always be only 1 CameraTrack in the animation.cameraTrack.CreateKeyframe(mapView.Camera,atTime,AnimationTransition.FixedArc);
Create Time Keyframe
varanimation=mapView.Map.Animation;vartimeTrack=animation.Tracks.OfType<TimeTrack>().First();//There will always be only 1 TimeTrack in the animation.timeTrack.CreateKeyframe(mapView.Time,atTime,AnimationTransition.Linear);
Create Range Keyframe
varanimation=mapView.Map.Animation;varrangeTrack=animation.Tracks.OfType<RangeTrack>().First();//There will always be only 1 RangeTrack in the animation.rangeTrack.CreateKeyframe(range,atTime,AnimationTransition.Linear);
Create Layer Keyframe
varanimation=mapView.Map.Animation;varlayerTrack=animation.Tracks.OfType<LayerTrack>().First();//There will always be only 1 LayerTrack in the animation.layerTrack.CreateKeyframe(layer,atTime,true,transparency,AnimationTransition.Linear);
Graphic overlay
Graphic Overlay
// get the current MapView and pointvarmyextent=mapView.Extent;varpoint=myextent.Center;IDisposable_graphic=null;// add point graphic to the overlay at the center of the mapView// Note: Needs QueuedTask to run_graphic=mapView.AddOverlay(point,SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB,30.0,SimpleMarkerStyle.Star).MakeSymbolReference());// update the overlay with new point graphic symbolMessageBox.Show("Now to update the overlay...");// Note: Needs QueuedTask to run{mapView.UpdateOverlay(_graphic,point,SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.BlueRGB,20.0,SimpleMarkerStyle.Circle).MakeSymbolReference());}// clear the overlay display by disposing of the graphicMessageBox.Show("Now to clear the overlay...");_graphic.Dispose();
Graphic Overlay with CIMPictureGraphic
// Use SourceURL for the URL to the image content. For// a local file, use a file path. For a web/internet file// location, use its URL//// Supported image types are:// png, jpg, tiff, bmp, gif, svgvarpictureGraphic=newCIMPictureGraphic{SourceURL=@"C:\Images\MyImage.png",Shape=envelope};IDisposable_graphic=mapView.AddOverlay(pictureGraphic);}// cref: ArcGIS.Desktop.Mapping.MapTool.AddOverlayAsync(ArcGIS.Core.Geometry.Geometry, ArcGIS.Core.CIM.CIMSymbolReference, System.Double, System.Double)// cref: ArcGIS.Desktop.Mapping.MappingExtensions.AddOverlay(ArcGIS.Desktop.Mapping.MapView, ArcGIS.Core.CIM.CIMGraphic, System.Double)
#region Add overlay graphic with text
{IDisposable_graphic=null;//define the text symbolvartextSymbol=newCIMTextSymbol();//define the text graphicvartextGraphic=newCIMTextGraphic();// Note: Needs QueuedTask to run{//Create a simple text symboltextSymbol=SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB,8.5,"Corbel","Regular");//Sets the geometry of the text graphictextGraphic.Shape=geometry;//Sets the text string to use in the text graphictextGraphic.Text="This is my line";//Sets symbol to use to draw the text graphictextGraphic.Symbol=textSymbol.MakeSymbolReference();//Draw the overlay text graphic_graphic=MapView.Active.AddOverlay(textGraphic);}
Mapping Options
Get/Set Selection Options
varoptions=ApplicationOptions.SelectionOptions;// Note: Needs QueuedTask to run{vardefaultColor=options.DefaultSelectionColor;varcolor=options.SelectionColorasCIMRGBColor;options.SetSelectionColor(ColorFactory.Instance.CreateRGBColor(255,0,0));vardefaultFill=options.DefaultSelectionFillColor;varfill=options.SelectionFillColor;varisHatched=options.IsSelectionFillHatched;options.SetSelectionFillColor(ColorFactory.Instance.CreateRGBColor(100,100,0));if(!isHatched)options.SetSelectionFillIsHatched(true);varshowSelectionChip=options.ShowSelectionChip;options.SetShowSelectionChip(!showSelectionChip);varshowSelectionGraphic=options.ShowSelectionGraphic;options.SetShowSelectionGraphic(!showSelectionGraphic);varsaveSelection=options.SaveSelection;options.SetSaveSelection(!saveSelection);vardefaultTol=options.DefaultSelectionTolerance;vartol=options.SelectionTolerance;options.SetSelectionTolerance(2*defaultTol);// extension methods available varselMethod=options.SelectionMethod;options.SetSelectionMethod(SelectionMethod.Contains);varcombMethod=options.CombinationMethod;options.SetCombinationMethod(SelectionCombinationMethod.Add);// note that the following SelectionCombinationMethod is not supported//options.SetCombinationMethod(SelectionCombinationMethod.XOR);}
Get/Set Table Options
varoptions=ApplicationOptions.TableOptions;varhideAddNewRow=options.HideAddNewRow;options.HideAddNewRow=!hideAddNewRow;varoverrides=options.HonorSelectionColorOverrides;options.HonorSelectionColorOverrides=!overrides;varactivateMapView=options.ActivateMapViewAfterOperations;options.ActivateMapViewAfterOperations=!activateMapView;vardefaultFontTName=options.DefaultFontName;varfontName=options.FontName;if(options.IsValidFontName("Arial"))options.FontName="Arial";vardefaultFontSize=options.DefaultFontSize;varfontSize=options.FontSize;if(options.IsValidFontSize(10))options.FontSize=10;varheightType=options.ColumnHeaderHeightType;options.ColumnHeaderHeightType=TableRowHeightType.Double;varrowHeightType=options.RowHeightType;options.RowHeightType=TableRowHeightType.Single;vardefaultColor=options.DefaultHighlightColor;varcolor=options.HighlightColor;// Note: Needs QueuedTask to runoptions.SetHighlightColor(ColorFactory.Instance.CreateRGBColor(0,0,255));
Popups
Show a pop-up for a feature
mapView.ShowPopup(mapMember,objectID);
Show a custom pop-up
//Create custom popup contentList<PopupContent>popups=[new("<b>This text is bold.</b>","Custom tooltip from HTML string"),new(newUri("https://www.esri.com/"),"Custom tooltip from Uri")];mapView.ShowCustomPopup(popups);
Show a pop-up for a feature using pop-up window properties
if(mapView==null)return;// Sample code: https://github.com/Esri/arcgis-pro-sdk-community-samples/blob/master/Map-Exploration/CustomIdentify/CustomIdentify.csvartopLeftCornerPoint=newSystem.Windows.Point(200,200);varpopupDef=newPopupDefinition(){Append=true,// if true new record is appended to existing (if any)Dockable=true,// if true popup is dockable - if false Append is not applicablePosition=topLeftCornerPoint,// Position of top left corner of the popup (in pixels)Size=newSystem.Windows.Size(200,400)// size of the popup (in pixels)};mapView.ShowPopup(mapMember,objectID,popupDef);
Show a custom pop-up using pop-up window properties
if(mapView==null)return;//Create custom popup contentList<PopupContent>popups=[new("<b>This text is bold.</b>","Custom tooltip from HTML string"),new(newUri("https://www.esri.com/"),"Custom tooltip from Uri")];// Sample code: https://github.com/Esri/arcgis-pro-sdk-community-samples/blob/master/Framework/DynamicMenu/DynamicFeatureSelectionMenu.csvartopLeftCornerPoint=newSystem.Windows.Point(200,200);varpopupDef=newPopupDefinition(){Append=true,// if true new record is appended to existing (if any)Dockable=true,// if true popup is dockable - if false Append is not applicablePosition=topLeftCornerPoint,// Position of top left corner of the popup (in pixels)Size=newSystem.Windows.Size(200,400)// size of the popup (in pixels)};mapView.ShowCustomPopup(popups,null,true,popupDef);
Show A pop-up With Custom Commands
//Create custom popup content from existing map member and object idList<PopupContent>popups=[newPopupContent(mapMember,objectID)];//Create a new custom command to add to the popup windowList<PopupCommand>commands=[newPopupCommand(
p =>MessageBox.Show(string.Format("Map Member: {0}, ID: {1}",p.MapMember,p.IDString)),
p =>{returnp!=null;},"My custom command",System.Windows.Application.Current.Resources["GenericCheckMark16"]asImageSource),];mapView.ShowCustomPopup(popups,commands,true);
Show A Dynamic Pop-up
publicstaticvoidShowDynamicPopup(MapMembermapMember,List<long>objectIDs){MapViewmapView=MapView.Active;if(mapView==null)return;//Create popup whose content is created the first time the item is requested.varpopups=newList<PopupContent>();foreach(varidinobjectIDs){popups.Add(newDynamicPopupContent(mapMember,id));}mapView.ShowCustomPopup(popups);}internalclassDynamicPopupContent:PopupContent{publicDynamicPopupContent(MapMembermapMember,longobjectID){MapMember=mapMember;IDString=objectID.ToString();IsDynamicContent=true;}//Called when the pop-up is loaded in the window.protectedoverrideTask<string>OnCreateHtmlContent(){returnQueuedTask.Run(()=>string.Format("<b>Map Member: {0}, ID: {1}</b>",MapMember,IDString));}}
Tools
Change symbol for a sketch tool
internalclassSketchTool_WithSymbol:MapTool{publicSketchTool_WithSymbol(){IsSketchTool=true;SketchOutputMode=SketchOutputMode.Map;//Changing the Sketch Symbol is only supported with map sketches.SketchType=SketchGeometryType.Rectangle;}protectedoverrideTaskOnToolActivateAsync(boolhasMapViewChanged){returnQueuedTask.Run(()=>{//Set the Sketch Symbol if it hasn't already been set.if(SketchSymbol!=null)return;varpolygonSymbol=SymbolFactory.Instance.ConstructPolygonSymbol(ColorFactory.Instance.CreateRGBColor(24,69,59),SimpleFillStyle.Solid,SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB,1.0,SimpleLineStyle.Dash));SketchSymbol=polygonSymbol.MakeSymbolReference();});}}
Create a tool to the return coordinates of the point clicked in the map
internalclassGetMapCoordinates:MapTool{protectedoverridevoidOnToolMouseDown(MapViewMouseButtonEventArgse){if(e.ChangedButton==System.Windows.Input.MouseButton.Left)e.Handled=true;//Handle the event args to get the call to the corresponding async method}protectedoverrideTaskHandleMouseDownAsync(MapViewMouseButtonEventArgse){returnQueuedTask.Run(()=>{//Convert the clicked point in client coordinates to the corresponding map coordinates.varmapPoint=MapView.Active.ClientToMap(e.ClientPoint);ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(string.Format("X: {0} Y: {1} Z: {2}",mapPoint.X,mapPoint.Y,mapPoint.Z),"Map Coordinates");});}}
Create a tool to identify the features that intersect the sketch geometry
internalclassCustomIdentify:MapTool{publicCustomIdentify(){IsSketchTool=true;SketchType=SketchGeometryType.Rectangle;//To perform a interactive selection or identify in 3D or 2D, sketch must be created in screen coordinates.SketchOutputMode=SketchOutputMode.Screen;}protectedoverrideTask<bool>OnSketchCompleteAsync(ArcGIS.Core.Geometry.Geometrygeometry){returnQueuedTask.Run(()=>{varmapView=MapView.Active;if(mapView==null)returntrue;//Get all the features that intersect the sketch geometry and flash them in the view. varresults=mapView.GetFeatures(geometry);mapView.FlashFeature(results);vardebug=System.String.Join("\n",results.ToDictionary().Select(kvp =>System.String.Format("{0}: {1}",kvp.Key.Name,kvp.Value.Count())));System.Diagnostics.Debug.WriteLine(debug);returntrue;});}}
Change the cursor of a Tool
internalclassCustomMapTool:MapTool{publicCustomMapTool(){IsSketchTool=true;SketchType=SketchGeometryType.Rectangle;SketchOutputMode=SketchOutputMode.Map;//A custom cursor file as an embedded resourcevarcursorEmbeddedResource=newCursor(newMemoryStream(Resource1.red_cursor));//A built in system cursorvarsystemCursor=System.Windows.Input.Cursors.ArrowCD;//Set the "CustomMapTool's" Cursor property to either one of the cursors defined aboveCursor=cursorEmbeddedResource;//orCursor=systemCursor;}}
Tool with an Embeddable Control
// Using the Visual Studio SDK templates, add a MapTool and an EmbeddableControl// The EmbeddableControl is registered in the "esri_embeddableControls" category in the config.daml file// // <categories>// <updateCategory refID = "esri_embeddableControls" >// <insertComponent id="mapTool_EmbeddableControl" className="EmbeddableControl1ViewModel">// <content className = "EmbeddableControl1View" />// </insertComponent>// <updateCategory>// </categories>internalclassMapTool_WithControl:MapTool{publicMapTool_WithControl(){// substitute this string with the daml ID of the embeddable control you addedControlID="mapTool_EmbeddableControl";}protectedoverridevoidOnToolMouseDown(MapViewMouseButtonEventArgse){e.Handled=true;}protectedoverrideTaskHandleMouseDownAsync(MapViewMouseButtonEventArgse){//Get the instance of the ViewModelvarvm=EmbeddableControl;if(vm==null)returnTask.FromResult(0);// cast vm to your viewModel in order to access your properties//Get the map coordinates from the click point and set the property on the ViewMode.returnQueuedTask.Run(()=>{varmapPoint=MapView.Active.ClientToMap(e.ClientPoint);stringclickText=string.Format("X: {0}, Y: {1}, Z: {2}",mapPoint.X,mapPoint.Y,mapPoint.Z);});}}
Tool with an Overlay Embeddable Control
// Using the Visual Studio SDK templates, add a MapTool and an EmbeddableControl// The EmbeddableControl is registered in the "esri_embeddableControls" category in the config.daml file// // <categories>// <updateCategory refID = "esri_embeddableControls" >// <insertComponent id="mapTool_EmbeddableControl" className="EmbeddableControl1ViewModel">// <content className = "EmbeddableControl1View" />// </insertComponent>// <updateCategory>// </categories>internalclassMapTool_WithOverlayControl:MapTool{publicMapTool_WithOverlayControl(){// substitute this string with the daml ID of the embeddable control you addedOverlayControlID="mapTool_EmbeddableControl";}protectedoverridevoidOnToolMouseDown(MapViewMouseButtonEventArgse){e.Handled=true;}protectedoverrideTaskHandleMouseDownAsync(MapViewMouseButtonEventArgse){//Get the instance of the ViewModelvarvm=OverlayEmbeddableControl;if(vm==null)returnTask.FromResult(0);// cast vm to your viewModel in order to access your properties//Get the map coordinates from the click point and set the property on the ViewMode.returnQueuedTask.Run(()=>{varmapPoint=MapView.Active.ClientToMap(e.ClientPoint);stringclickText=string.Format("X: {0}, Y: {1}, Z: {2}",mapPoint.X,mapPoint.Y,mapPoint.Z);});}}