publicboolIsView3D(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Return whether the viewing mode is SceneLocal or SceneGlobalreturnmapView.ViewingMode==ArcGIS.Core.CIM.MapViewingMode.SceneLocal||mapView.ViewingMode==ArcGIS.Core.CIM.MapViewingMode.SceneGlobal;}
Set ViewingMode
publicvoidSetViewingModeToSceneLocal(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Check if the view can be set to SceneLocal and if it can set it.if(mapView.CanSetViewingMode(ArcGIS.Core.CIM.MapViewingMode.SceneLocal))mapView.SetViewingModeAsync(ArcGIS.Core.CIM.MapViewingMode.SceneLocal);}
Enable View Linking
publicvoidEnableViewLinking(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Set the view linking mode to Center and Scale.MapView.LinkMode=LinkMode.Center|LinkMode.Scale;}
Update MapView Extent (Zoom, Pan etc)
Go To Previous Camera
publicTask<bool>ZoomToPreviousCameraAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom to the selected layers in the TOCif(mapView.HasPreviousCamera())returnmapView.PreviousCameraAsync();returnTask.FromResult(false);}
Go To Next Camera
publicTask<bool>ZoomToNextCameraAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom to the selected layers in the TOCif(mapView.HasNextCamera())returnmapView.NextCameraAsync();returnTask.FromResult(false);}
Zoom To Full Extent
publicTask<bool>ZoomToFullExtent(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Zoom to the map's full extentreturnmapView.ZoomToFullExtent();});}publicTask<bool>ZoomToFullExtentAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom to the map's full extentreturnmapView.ZoomToFullExtentAsync(TimeSpan.FromSeconds(2));}
Fixed Zoom In
publicTask<bool>ZoomInFixed(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Zoom in the map view by a fixed amount.returnmapView.ZoomInFixed();});}publicTask<bool>ZoomInFixedAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom in the map view by a fixed amount.returnmapView.ZoomInFixedAsync();}
Fixed Zoom Out
publicTask<bool>ZoomOutFixed(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Zoom out in the map view by a fixed amount.returnmapView.ZoomOutFixed();});}publicTask<bool>ZoomOutFixedAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom in the map view by a fixed amount.returnmapView.ZoomOutFixedAsync();}
Zoom To an Extent
publicTask<bool>ZoomToExtent(doublexMin,doubleyMin,doublexMax,doubleyMax,ArcGIS.Core.Geometry.SpatialReferencespatialReference){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Create the envelopevarenvelope=ArcGIS.Core.Geometry.EnvelopeBuilderEx.CreateEnvelope(xMin,yMin,xMax,yMax,spatialReference);//Zoom the view to a given extent.returnmapView.ZoomToAsync(envelope,TimeSpan.FromSeconds(2));}
Zoom To a Point
publicTask<bool>ZoomToPoint(doublex,doubley,ArcGIS.Core.Geometry.SpatialReferencespatialReference){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);returnQueuedTask.Run(()=>{//Note: Run within QueuedTask//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 effectreturnmapView.ZoomTo(poly,newTimeSpan(0,0,0,3));});}
Zoom To Selected Features
publicTask<bool>ZoomToSelected(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Zoom to the map's selected features.returnmapView.ZoomToSelected();});}publicTask<bool>ZoomToSelectedAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom to the map's selected features.returnmapView.ZoomToSelectedAsync(TimeSpan.FromSeconds(2));}
Zoom To Bookmark by name
publicTask<bool>ZoomToBookmark(stringbookmarkName){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Get the first bookmark with the given name.varbookmark=mapView.Map.GetBookmarks().FirstOrDefault(b =>b.Name==bookmarkName);if(bookmark==null)returnfalse;//Zoom the view to the bookmark.returnmapView.ZoomTo(bookmark);});}publicasyncTask<bool>ZoomToBookmarkAsync(stringbookmarkName){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Get the first bookmark with the given name.varbookmark=awaitQueuedTask.Run(()=>mapView.Map.GetBookmarks().FirstOrDefault(b =>b.Name==bookmarkName));if(bookmark==null)returnfalse;//Zoom the view to the bookmark.returnawaitmapView.ZoomToAsync(bookmark,TimeSpan.FromSeconds(2));}
Zoom To Visible Layers
publicTask<bool>ZoomToAllVisibleLayersAsync(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Zoom to all visible layers in the map.varvisibleLayers=mapView.Map.Layers.Where(l =>l.IsVisible);returnmapView.ZoomTo(visibleLayers);});}
Zoom To Selected Layers
publicTask<bool>ZoomToTOCSelectedLayersAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Zoom to the selected layers in the TOCvarselectedLayers=mapView.GetSelectedLayers();returnmapView.ZoomToAsync(selectedLayers);}
Pan To an Extent
publicTask<bool>PanToExtent(doublexMin,doubleyMin,doublexMax,doubleyMax,ArcGIS.Core.Geometry.SpatialReferencespatialReference){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Pan the view to a given extent.varenvelope=ArcGIS.Core.Geometry.EnvelopeBuilderEx.CreateEnvelope(xMin,yMin,xMax,yMax,spatialReference);returnmapView.PanTo(envelope);});}publicTask<bool>PanToExtentAsync(doublexMin,doubleyMin,doublexMax,doubleyMax,ArcGIS.Core.Geometry.SpatialReferencespatialReference){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Create the envelopevarenvelope=ArcGIS.Core.Geometry.EnvelopeBuilderEx.CreateEnvelope(xMin,yMin,xMax,yMax,spatialReference);//Pan the view to a given extent.returnmapView.PanToAsync(envelope,TimeSpan.FromSeconds(2));}
Pan To Selected Features
publicTask<bool>PanToSelected(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Pan to the map's selected features.returnmapView.PanToSelected();});}publicTask<bool>PanToSelectedAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Pan to the map's selected features.returnmapView.PanToSelectedAsync(TimeSpan.FromSeconds(2));}
Pan To Bookmark
publicTask<bool>PanToBookmark(stringbookmarkName){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Get the first bookmark with the given name.varbookmark=mapView.Map.GetBookmarks().FirstOrDefault(b =>b.Name==bookmarkName);if(bookmark==null)returnfalse;//Pan the view to the bookmark.returnmapView.PanTo(bookmark);});}publicasyncTask<bool>PanToBookmarkAsync(stringbookmarkName){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Get the first bookmark with the given name.varbookmark=awaitQueuedTask.Run(()=>mapView.Map.GetBookmarks().FirstOrDefault(b =>b.Name==bookmarkName));if(bookmark==null)returnfalse;//Pan the view to the bookmark.returnawaitmapView.PanToAsync(bookmark,TimeSpan.FromSeconds(2));}
Pan To Visible Layers
publicTask<bool>PanToAllVisibleLayersAsync(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Pan to all visible layers in the map.varvisibleLayers=mapView.Map.Layers.Where(l =>l.IsVisible);returnmapView.PanTo(visibleLayers);});}
Pan To Selected Layers Asynchronous
publicTask<bool>PanToTOCSelectedLayersAsync(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Pan to the selected layers in the TOCvarselectedLayers=mapView.GetSelectedLayers();returnmapView.PanToAsync(selectedLayers);}
Rotate the map view
publicTask<bool>RotateView(doubleheading){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnTask.FromResult(false);//Get the camera for the view, adjust the heading and zoom to the new camera position.varcamera=mapView.Camera;camera.Heading=heading;returnmapView.ZoomToAsync(camera,TimeSpan.Zero);}// or use the synchronous methodpublicTask<bool>RotateViewAsync(doubleheading){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Get the camera for the view, adjust the heading and zoom to the new camera position.varcamera=mapView.Camera;camera.Heading=heading;returnmapView.ZoomTo(camera,TimeSpan.Zero);});}
Expand Extent
publicTask<bool>ExpandExtentAsync(doubledx,doubledy){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnfalse;//Expand the current extent by the given ratio.varextent=mapView.Extent;varnewExtent=ArcGIS.Core.Geometry.GeometryEngine.Instance.Expand(extent,dx,dy,true);returnmapView.ZoomTo(newExtent);});}
Maps
Get the active map's name
publicstringGetActiveMapName(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnnull;//Return the name of the map currently displayed in the active map view.returnmapView.Map.Name;}
//Selection tolerance for the map in pixelsvarselectionTolerance=SelectionEnvironment.SelectionTolerance;QueuedTask.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 uints.varsearchRadius=GeometryEngine.Instance.Distance(mapPoint,radiusMapPoint);});
MapView Overlay Control
//Creat a Progress Bar user controlvarprogressBarControl=newSystem.Windows.Controls.ProgressBar();//Configure the progress barprogressBarControl.Minimum=0;progressBarControl.Maximum=100;progressBarControl.IsIndeterminate=true;progressBarControl.Width=300;progressBarControl.Value=10;progressBarControl.Height=25;progressBarControl.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);awaitQueuedTask.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
publicvoidSelectAllFeatureLayersInTOC(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Zoom to the selected layers in the TOCvarfeatureLayers=mapView.Map.Layers.OfType<FeatureLayer>();mapView.SelectLayers(featureLayers.ToList());}
Flash selected features
publicTaskFlashSelectedFeaturesAsync(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Get the selected features from the map and filter out the standalone table selection.//At 2.x//var selectedFeatures = mapView.Map.GetSelection()// .Where(kvp => kvp.Key is BasicFeatureLayer)// .ToDictionary(kvp => (BasicFeatureLayer)kvp.Key, kvp => kvp.Value);////Flash the collection of features.//mapView.FlashFeature(selectedFeatures);varselectedFeatures=mapView.Map.GetSelection();//Flash the collection of features.mapView.FlashFeature(selectedFeatures);});}
// get the layer you wantvarlayer=MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().FirstOrDefault();// select it in the TOCList<Layer>layersToSelect=newList<Layer>();layersToSelect.Add(layer);MapView.Active.SelectLayers(layersToSelect);// now execute the layer properties commandvarwrapper=FrameworkApplication.GetPlugInWrapper("esri_mapping_selectedLayerPropertiesButton");varcommand=wrapperasICommand;if(command==null)return;// execute the commandif(command.CanExecute(null))command.Execute(null);
varmapMember=MapView.Active.Map.GetLayersAsFlattenedList().OfType<MapMember>().FirstOrDefault();//Gets or creates the CIMMapTableView for a MapMember.vartableView=FrameworkApplication.Panes.GetMapTableView(mapMember);//Configure the table viewtableView.DisplaySubtypeDomainDescriptions=false;tableView.SelectionMode=false;tableView.ShowOnlyContingentValueFields=true;tableView.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(tableView);
TableView
Set Table ViewingMode
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// change to "selected record" modetableView.SetViewMode(TableViewMode.eSelectedRecords);
Set ZoomLevel
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// change zoom levelif(tableView.ZoomLevel>100)tableView.SetZoomLevel(100);elsetableView.SetZoomLevel(200);
Toggle Field Alias
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// set the valuetableView.ShowFieldAlias=true;// OR toggle itif(tableView.CanToggleFieldAlias)tableView.ToggleFieldAlias();
Toggle Subtype Descriptions
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// set the valuetableView.ShowSubtypeDomainDescriptions=true;// OR toggle itif(tableView.CanToggleSubtypeDomainDescriptions)tableView.ToggleSubtypeDomainDescriptionsAsync();
Get the active row
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// get the active rowindexintrowIndex=tableView.ActiveRowIndex;
Change the active row
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// get the active rowindexintrowIndex=tableView.ActiveRowIndex;// move to a different rowvarnewIndex=10+rowIndex;awaittableView.BringIntoView(newIndex);
Get the active object ID
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// get the active objectIDlong?OID=tableView.ActiveObjectId;
Translate between rowIndex and objectID
//Get the active table view.vartableView=TableView.Active;if(tableView==null)return;// get the active rowindexintrowIndex=tableView.ActiveRowIndex;// increaseintnewIndex=rowIndex+10;// get the objectIDlongnewOID=awaittableView.GetObjectIdAsync(newIndex);// 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=awaittableView.GetRowIndexAsync(OID,true);
Get selected rows or row indexes
vartv=TableView.Active;if(tv==null)return;QueuedTask.Run(async()=>{// get the set of selected objectIDs varselOids=tv.GetSelectedObjectIds();// get the set of selected row indexesvarselRows=tv.GetSelectedRowIndexes();});
Change selected rows
vartv=TableView.Active;if(tv==null)return;QueuedTask.Run(async()=>{// set of selected OIDSvarnewoids=newList<long>();newoids.AddRange(newList<long>(){10,15,17});tv.Select(newoids,true);// add to set of selected row indexesvarselRows=tv.GetSelectedRowIndexes();varnewRows=newList<long>(selRows);newRows.AddRange(newList<long>(){21,35});tv.Select(newRows,false);});
vartv=TableView.Active;if(tv==null)return;// toggle the active rows selectionif(tv.CanToggleRowSelection)tv.ToggleRowSelection();// switch the selectionif(tv.CanSwitchSelection)tv.SwitchSelection();// clear the selectionif(tv.CanClearSelection)tv.ClearSelection();
vartv=TableView.Active;if(tv==null)return;QueuedTask.Run(async()=>{IReadOnlyList<long>highlightedOIDs=null;if(tv.CanGetHighlightedObjectIds)// get the set of selected objectIDs highlightedOIDs=tv.GetHighlightedObjectIds();});
Change highlighted rows
vartv=TableView.Active;if(tv==null)return;QueuedTask.Run(()=>{// get list of current selected objectIDsvarselectedObjectIds=tv.GetSelectedObjectIds();varidsToHighlight=newList<long>();// add the first two selected objectIds to highlightif(selectedObjectIds.Count>=2){idsToHighlight.Add(selectedObjectIds[0]);idsToHighlight.Add(selectedObjectIds[1]);}// highlightif(tv.CanHighlight)tv.Highlight(idsToHighlight,true);});
Toggle, Switch, Clear Highlights
vartv=TableView.Active;if(tv==null)return;// toggle the active rows selectionif(tv.CanToggleRowHighlight)tv.ToggleRowHighlight();// switch highlighted rowsif(tv.CanSwitchHighlight)tv.SwitchHighlight();// clear the highlightsif(tv.CanClearHighlighted)tv.ClearHighlighted();
vartv=TableView.Active;if(tv==null)return;// field accessvarflds=tv.GetFields();varfldIdx=tv.GetFieldIndex("STATE_NAME");varfldDesc=tv.GetField(fldIdx);
Get or set the Active Field
vartv=TableView.Active;if(tv==null)return;// get active field, active field namevaractiveFieldIdx=tv.ActiveFieldIndex;varfldDesc=tv.GetField(activeFieldIdx);varfldName=fldDesc.Name;// set active field by nametv.SetActiveField("STATE_NAME");// or set active field by indextv.SetActiveField(3);
Select Fields
vartv=TableView.Active;if(tv==null)return;// get selected fieldsvarselectedfields=tv.GetSelectedFields();// set selected fieldstv.SetSelectedFields(newList<string>{"CITY_FIPS","STATE_FIPS"});
vartv=TableView.Active;if(tv==null)return;// get list of hidden fieldsvarhiddenFields=tv.GetHiddenFields();// show all fieldsif(tv.CanShowAllFields)tv.ShowAllFields();// hide only "CITY_FIPS", "STATE_FIPS"if(tv.CanShowAllFields){// show all fieldstv.ShowAllFields();tv.SetHiddenFields(newList<string>{"CITY_FIPS","STATE_FIPS"});}// add "STATE_NAME to set of hidden fieldstv.SetHiddenFields(newList<string>{"STATE_NAME"});// hide selected fieldsif(tv.CanHideSelectedFields)tv.HideSelectedFields();
Freeze Fields
vartv=TableView.Active;if(tv==null)return;// get list of frozen fieldsvarfrozenfields=tv.GetFrozenFields();// un freeze all fieldsawaittv.ClearAllFrozenFieldsAsync();// freeze a set of fieldsawaittv.SetFrozenFieldsAsync(newList<string>{"CITY_FIPS","STATE_FIPS"});
Sort
vartv=TableView.Active;if(tv==null)return;// sort the active field descendingif(tv.CanSortDescending)tv.SortDescending();// sort the active field ascendingif(tv.CanSortAscending)tv.SortAscending();// peform a custom sort programmaticallyif(tv.CanCustomSort){// sort fieldsvardict=newDictionary<string,FieldSortInfo>();dict.Add("STATE_NAME",FieldSortInfo.Asc);dict.Add("CITY_NAME",FieldSortInfo.Desc);awaittv.SortAsync(dict);}// perform a custom sort via the UIif(tv.CanCustomSort)tv.CustomSort();
Find and Replace
vartv=TableView.Active;if(tv==null)return;// launch the find UIif(tv.CanFind)tv.Find();// or launch the find and replace UIif(tv.CanFindAndReplace)tv.FindAndReplace();
GoTo
vartv=TableView.Active;if(tv==null)return;// launch the GoTo UIif(tv.CanGoTo)tv.GoTo();
// find all the table panes (table panes hosting map data)vartablePanes=FrameworkApplication.Panes.OfType<ITablePane>();vartablePane=tablePanes.FirstOrDefault(p =>(pasITablePaneEx)?.Caption=="oldcCaption");vartablePaneEx=tablePaneasITablePaneEx;if(tablePaneEx!=null)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=="oldcCaption");if(externalTablePane!=null)externalTablePane.Caption="newCaption";
Get TableView from table pane
TableViewtv=null;// find all the table panes (table panes hosting map data)vartablePanes=FrameworkApplication.Panes.OfType<ITablePane>();vartablePane=tablePanes.FirstOrDefault(p =>(pasITablePaneEx)?.Caption=="caption");vartablePaneEx=tablePaneasITablePaneEx;if(tablePaneEx!=null)tv=tablePaneEx.TableView;// if it's not found, maybe it's an external table paneif(tv==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)tv=externalTablePane.TableView;}
Features
Mask feature
//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=newstring[]{"CIMPATH=map3/testpoly.xml"};//Re-set the Masked layer's defintionlineLyrToBeMasked.SetDefinition(lyrDefn);
Popups
Show a pop-up for a feature
publicvoidShowPopup(MapMembermapMember,longobjectID){//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;mapView.ShowPopup(mapMember,objectID);}
Show a custom pop-up
publicvoidShowCustomPopup(){//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Create custom popup contentvarpopups=newList<PopupContent>{newPopupContent("<b>This text is bold.</b>","Custom tooltip from HTML string"),newPopupContent(newUri("http://www.esri.com/"),"Custom tooltip from Uri")};mapView.ShowCustomPopup(popups);}
Show a pop-up for a feature using pop-up window properties
publicvoidShowPopupWithWindowDef(MapMembermapMember,longobjectID){if(MapView.Active==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.Active.ShowPopup(mapMember,objectID,popupDef);}
Show a custom pop-up using pop-up window properties
publicvoidShowCustomPopupWithWindowDef(){if(MapView.Active==null)return;//Create custom popup contentvarpopups=newList<PopupContent>{newPopupContent("<b>This text is bold.</b>","Custom tooltip from HTML string"),newPopupContent(newUri("http://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.Active.ShowCustomPopup(popups,null,true,popupDef);}
Show A pop-up With Custom Commands
publicvoidShowCustomPopup(MapMembermapMember,longobjectID){//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Create custom popup content from existing map member and object idvarpopups=newList<PopupContent>();popups.Add(newPopupContent(mapMember,objectID));//Create a new custom command to add to the popup windowvarcommands=newList<PopupCommand>();commands.Add(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
publicvoidShowDynamicPopup(MapMembermapMember,List<long>objectIDs){//Get the active map view.varmapView=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));}}
Bookmarks
Create a new bookmark using the active map view
publicTask<Bookmark>AddBookmarkAsync(stringname){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnnull;//Adding a new bookmark using the active view.returnmapView.Map.AddBookmark(mapView,name);});}
Add New Bookmark from CIMBookmark
publicTask<Bookmark>AddBookmarkFromCameraAsync(Cameracamera,stringname){returnQueuedTask.Run(()=>{//Set properties for CameraCIMViewCameracimCamera=newCIMViewCamera(){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=name,ThumbnailImagePath=""};//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnnull;//Add a new bookmark for the active map.returnmapView.Map.AddBookmark(cimBookmark);});}
Get the collection of bookmarks for the project
publicTask<ReadOnlyObservableCollection<Bookmark>>GetProjectBookmarksAsync(){//Get the collection of bookmarks for the project.returnQueuedTask.Run(()=>Project.Current.GetBookmarks());}
Get Map Bookmarks
publicTask<ReadOnlyObservableCollection<Bookmark>>GetActiveMapBookmarksAsync(){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)returnnull;//Return the collection of bookmarks for the map.returnmapView.Map.GetBookmarks();});}
Move Bookmark to the Top
publicTaskMoveBookmarkToTopAsync(Mapmap,stringname){returnQueuedTask.Run(()=>{//Find the first bookmark with the namevarbookmark=map.GetBookmarks().FirstOrDefault(b =>b.Name==name);if(bookmark==null)return;//Remove the bookmarkmap.MoveBookmark(bookmark,0);});}
publicTaskRemoveBookmarkAsync(Mapmap,stringname){returnQueuedTask.Run(()=>{//Find the first bookmark with the namevarbookmark=map.GetBookmarks().FirstOrDefault(b =>b.Name==name);if(bookmark==null)return;//Remove the bookmarkmap.RemoveBookmark(bookmark);});}
Change the thumbnail for a bookmark
publicTaskSetThumbnailAsync(Bookmarkbookmark,stringimagePath){//Set the thumbnail to an image on disk, ie. C:\Pictures\MyPicture.png.BitmapImageimage=newBitmapImage(newUri(imagePath,UriKind.RelativeOrAbsolute));returnQueuedTask.Run(()=>bookmark.SetThumbnail(image));}
Update Bookmark
publicTaskUpdateBookmarkAsync(Bookmarkbookmark){returnQueuedTask.Run(()=>{//Get the active map view.varmapView=MapView.Active;if(mapView==null)return;//Update the bookmark using the active map view.bookmark.Update(mapView);});}
Update Extent for a Bookmark
publicTaskUpdateBookmarkExtentAsync(Bookmarkbookmark,ArcGIS.Core.Geometry.Envelopeenvelope){returnQueuedTask.Run(()=>{//Get the bookmark's definitionvarbookmarkDef=bookmark.GetDefinition();//Modify the bookmark's locationbookmarkDef.Location=envelope;//Clear the camera as it is no longer valid.bookmarkDef.Camera=null;//Set the bookmark definitionbookmark.SetDefinition(bookmarkDef);});}
Time
Step forward in time by 1 month
publicvoidStepMapTime(){//Get the active viewMapViewmapView=MapView.Active;if(mapView==null)return;//Step current map time forward by 1 monthTimeDeltatimeDelta=newTimeDelta(1,TimeUnit.Months);mapView.Time=mapView.Time.Offset(timeDelta);}
publicList<CameraKeyframe>GetCameraKeyframes(){varmapView=MapView.Active;if(mapView!=null)returnnull;varanimation=mapView.Map.Animation;varcameraTrack=animation.Tracks.OfType<CameraTrack>().First();//There will always be only 1 CameraTrack in the animation.returncameraTrack.Keyframes.OfType<CameraKeyframe>().ToList();}
Interpolate Camera
publicTask<List<Camera>>GetInterpolatedCameras(){//Return the collection representing the camera for each frame in animation.returnQueuedTask.Run(()=>{varmapView=MapView.Active;if(mapView!=null||mapView.Animation==null)returnnull;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 greating than the duration.if(time>animation.Duration)time=animation.Duration;cameras.Add(mapView.Animation.GetCameraAtTime(time));}returncameras;});}
Interpolate Time
publicTask<List<TimeRange>>GetInterpolatedMapTimes(){//Return the collection representing the map time for each frame in animation.returnQueuedTask.Run(()=>{varmapView=MapView.Active;if(mapView!=null||mapView.Animation==null)returnnull;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 greating than the duration.if(time>animation.Duration)time=animation.Duration;timeRanges.Add(mapView.Animation.GetCurrentTimeAtTime(time));}returntimeRanges;});}
Interpolate Range
publicTask<List<ArcGIS.Desktop.Mapping.Range>>GetInterpolatedMapRanges(){//Return the collection representing the map time for each frame in animation.returnQueuedTask.Run(()=>{varmapView=MapView.Active;if(mapView!=null||mapView.Animation==null)returnnull;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));}returnranges;});}
Create Camera Keyframe
publicvoidCreateCameraKeyframe(TimeSpanatTime){varmapView=MapView.Active;if(mapView!=null)return;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,ArcGIS.Core.CIM.AnimationTransition.FixedArc);}
Create Time Keyframe
publicvoidCreateTimeKeyframe(TimeSpanatTime){varmapView=MapView.Active;if(mapView!=null)return;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,ArcGIS.Core.CIM.AnimationTransition.Linear);}
Create Range Keyframe
publicvoidCreateRangeKeyframe(ArcGIS.Desktop.Mapping.Rangerange,TimeSpanatTime){varmapView=MapView.Active;if(mapView!=null)return;varanimation=mapView.Map.Animation;varrangeTrack=animation.Tracks.OfType<RangeTrack>().First();//There will always be only 1 RangeTrack in the animation.rangeTrack.CreateKeyframe(range,atTime,ArcGIS.Core.CIM.AnimationTransition.Linear);}
Create Layer Keyframe
publicvoidCreateLayerKeyframe(Layerlayer,doubletransparency,TimeSpanatTime){varmapView=MapView.Active;if(mapView!=null)return;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,ArcGIS.Core.CIM.AnimationTransition.Linear);}
Graphic overlay
Graphic Overlay
//Defined elsewhereprivateIDisposable_graphic=null;publicasyncvoidGraphicOverlaySnippetTest(){// get the current mapview and pointvarmapView=MapView.Active;if(mapView==null)return;varmyextent=mapView.Extent;varpoint=myextent.Center;// add point graphic to the overlay at the center of the mapView_graphic=awaitQueuedTask.Run(()=>{//add these to the overlayreturnmapView.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...");awaitQueuedTask.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
// get the current mapviewvarmapView=MapView.Active;if(mapView==null)return;//Valid formats for PictureURL are:// e.g. local file URL:// file:///<path>// file:///c:/images/symbol.png//// e.g. network file URL:// file://<host>/<path>// file://server/share/symbol.png//// e.g. data URL:// data:<mediatype>;base64,<data>// data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD/2wBDAAU ...//// image/bmp// image/gif// image/jpeg// image/png// image/tiff// image/x-esri-bglfvarpictureGraphic=newCIMPictureGraphic{PictureURL=@"file:///C:/Images/MyImage.png",Shape=envelope};IDisposable_graphic=mapView.AddOverlay(pictureGraphic);
Add overlay graphic with text
internalclassAddOverlayWithText:MapTool{privateIDisposable_graphic=null;privateCIMLineSymbol_lineSymbol=null;publicAddOverlayWithText(){IsSketchTool=true;SketchType=SketchGeometryType.Line;SketchOutputMode=SketchOutputMode.Map;}protectedoverrideasyncTask<bool>OnSketchCompleteAsync(Geometrygeometry){//Add an overlay graphic to the map view_graphic=awaitthis.AddOverlayAsync(geometry,_lineSymbol.MakeSymbolReference());//define the text symbolvartextSymbol=newCIMTextSymbol();//define the text graphicvartextGraphic=newCIMTextGraphic();awaitQueuedTask.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=this.ActiveMapView.AddOverlay(textGraphic);});returntrue;}}
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(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=String.Join("\n",results.ToDictionary().Select(kvp =>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);});}}
Mapping Options
Get/Set Selection Options
varoptions=ApplicationOptions.SelectionOptions;QueuedTask.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);});