publicboolIsView3D(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Return whether the viewing mode is SceneLocal or SceneGlobalreturn mapView.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)return Task.FromResult(false);//Zoom to the selected layers in the TOCif(mapView.HasPreviousCamera())return mapView.PreviousCameraAsync();return Task.FromResult(false);}
Go To Next Camera
publicTask<bool>ZoomToNextCameraAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom to the selected layers in the TOCif(mapView.HasNextCamera())return mapView.NextCameraAsync();return Task.FromResult(false);}
Zoom To Full Extent
publicTask<bool>ZoomToFullExtent(){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Zoom to the map's full extentreturn mapView.ZoomToFullExtent();});}publicTask<bool>ZoomToFullExtentAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom to the map's full extentreturn mapView.ZoomToFullExtentAsync(TimeSpan.FromSeconds(2));}
Fixed Zoom In
publicTask<bool>ZoomInFixed(){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Zoom in the map view by a fixed amount.return mapView.ZoomInFixed();});}publicTask<bool>ZoomInFixedAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom in the map view by a fixed amount.return mapView.ZoomInFixedAsync();}
Fixed Zoom Out
publicTask<bool>ZoomOutFixed(){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Zoom out in the map view by a fixed amount.return mapView.ZoomOutFixed();});}publicTask<bool>ZoomOutFixedAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom in the map view by a fixed amount.return mapView.ZoomOutFixedAsync();}
Zoom To an Extent
publicTask<bool>ZoomToExtent(doublexMin,doubleyMin,doublexMax,doubleyMax, ArcGIS.Core.Geometry.SpatialReference spatialReference){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Create the envelopevarenvelope= ArcGIS.Core.Geometry.EnvelopeBuilderEx.CreateEnvelope(xMin, yMin, xMax, yMax, spatialReference);//Zoom the view to a given extent.return mapView.ZoomToAsync(envelope, TimeSpan.FromSeconds(2));}
Zoom To a Point
publicTask<bool>ZoomToPoint(doublex,doubley, ArcGIS.Core.Geometry.SpatialReference spatialReference){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);return QueuedTask.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 effectreturn mapView.ZoomTo(poly,new TimeSpan(0,0,0,3));});}
Zoom To Selected Features
publicTask<bool>ZoomToSelected(){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Zoom to the map's selected features.return mapView.ZoomToSelected();});}publicTask<bool>ZoomToSelectedAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom to the map's selected features.return mapView.ZoomToSelectedAsync(TimeSpan.FromSeconds(2));}
Zoom To Bookmark by name
publicTask<bool>ZoomToBookmark(stringbookmarkName){return QueuedTask.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.return mapView.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=await QueuedTask.Run(()=> mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name ==bookmarkName));if(bookmark==null)returnfalse;//Zoom the view to the bookmark.returnawait mapView.ZoomToAsync(bookmark, TimeSpan.FromSeconds(2));}
Zoom To Visible Layers
publicTask<bool>ZoomToAllVisibleLayersAsync(){return QueuedTask.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);return mapView.ZoomTo(visibleLayers);});}
Zoom To Selected Layers
publicTask<bool>ZoomToTOCSelectedLayersAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom to the selected layers in the TOCvarselectedLayers= mapView.GetSelectedLayers();return mapView.ZoomToAsync(selectedLayers);}
Pan To an Extent
publicTask<bool>PanToExtent(doublexMin,doubleyMin,doublexMax,doubleyMax, ArcGIS.Core.Geometry.SpatialReference spatialReference){return QueuedTask.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);return mapView.PanTo(envelope);});}publicTask<bool>PanToExtentAsync(doublexMin,doubleyMin,doublexMax,doubleyMax, ArcGIS.Core.Geometry.SpatialReference spatialReference){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Create the envelopevarenvelope= ArcGIS.Core.Geometry.EnvelopeBuilderEx.CreateEnvelope(xMin, yMin, xMax, yMax, spatialReference);//Pan the view to a given extent.return mapView.PanToAsync(envelope, TimeSpan.FromSeconds(2));}
Pan To Selected Features
publicTask<bool>PanToSelected(){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Pan to the map's selected features.return mapView.PanToSelected();});}publicTask<bool>PanToSelectedAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Pan to the map's selected features.return mapView.PanToSelectedAsync(TimeSpan.FromSeconds(2));}
Pan To Bookmark
publicTask<bool>PanToBookmark(stringbookmarkName){return QueuedTask.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.return mapView.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=await QueuedTask.Run(()=> mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name ==bookmarkName));if(bookmark==null)returnfalse;//Pan the view to the bookmark.returnawait mapView.PanToAsync(bookmark, TimeSpan.FromSeconds(2));}
Pan To Visible Layers
publicTask<bool>PanToAllVisibleLayersAsync(){return QueuedTask.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);return mapView.PanTo(visibleLayers);});}
Pan To Selected Layers Asynchronous
publicTask<bool>PanToTOCSelectedLayersAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Pan to the selected layers in the TOCvarselectedLayers= mapView.GetSelectedLayers();return mapView.PanToAsync(selectedLayers);}
Rotate the map view
publicTask<bool>RotateView(doubleheading){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Get the camera for the view, adjust the heading and zoom to the new camera position.varcamera= mapView.Camera;
camera.Heading =heading;return mapView.ZoomToAsync(camera, TimeSpan.Zero);}// or use the synchronous methodpublicTask<bool>RotateViewAsync(doubleheading){return QueuedTask.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;return mapView.ZoomTo(camera, TimeSpan.Zero);});}
Expand Extent
publicTask<bool>ExpandExtentAsync(doubledx,doubledy){return QueuedTask.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);return mapView.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.return mapView.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=new System.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=new System.Windows.Controls.ProgressBar();//Configure the progress bar
progressBarControl.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=new MapViewOverlayControl(progressBarControl,true,true,true, OverlayControlRelativePosition.BottomCenter,.5,.8);//Add to the active map
MapView.Active.AddOverlayControl(mapViewOverlayControl);await QueuedTask.Run(()=>{//Wait 3 seconds to remove the progress bar from the map. Thread.Sleep(3000);});//Remove from active map
MapView.Active.RemoveOverlayControl(mapViewOverlayControl);
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
public Task FlashSelectedFeaturesAsync(){return QueuedTask.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= wrapper as ICommand;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 view
tableView.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" mode
tableView.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);else
tableView.SetZoomLevel(200);
Toggle Field Alias
//Get the active table view.vartableView= TableView.Active;if(tableView==null)return;// set the value
tableView.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 value
tableView.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;await tableView.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=await tableView.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=await tableView.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 name
tv.SetActiveField("STATE_NAME");// or set active field by index
tv.SetActiveField(3);
Select Fields
vartv= TableView.Active;if(tv==null)return;// get selected fieldsvarselectedfields= tv.GetSelectedFields();// set selected fields
tv.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 fields
tv.ShowAllFields();
tv.SetHiddenFields(newList<string>{"CITY_FIPS","STATE_FIPS"});}// add "STATE_NAME to set of hidden fields
tv.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 fieldsawait tv.ClearAllFrozenFieldsAsync();// freeze a set of fieldsawait tv.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);await tv.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 =>(p as ITablePaneEx)?.Caption =="oldcCaption");vartablePaneEx= tablePane as ITablePaneEx;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 =>(p as ITablePaneEx)?.Caption =="caption");vartablePaneEx= tablePane as ITablePaneEx;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")as FeatureLayer;//Get the layer's definitionvarlyrDefn= lineLyrToBeMasked.GetDefinition();//Create an array of Masking layers (polygon only)//Set the LayerMasks property of the Masked layer
lyrDefn.LayerMasks =newstring[]{"CIMPATH=map3/testpoly.xml"};//Re-set the Masked layer's defintion
lineLyrToBeMasked.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>{new PopupContent("<b>This text is bold.</b>","Custom tooltip from HTML string"),new PopupContent(new Uri("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=new System.Windows.Point(200,200);varpopupDef=new PopupDefinition(){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=new System.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>{new PopupContent("<b>This text is bold.</b>","Custom tooltip from HTML string"),new PopupContent(new Uri("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=new System.Windows.Point(200,200);varpopupDef=new PopupDefinition(){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=new System.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(new PopupContent(mapMember, objectID));//Create a new custom command to add to the popup windowvarcommands=newList<PopupCommand>();
commands.Add(new PopupCommand(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"]as ImageSource));
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(var id in objectIDs){
popups.Add(new DynamicPopupContent(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(){return QueuedTask.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){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnnull;//Adding a new bookmark using the active view.return mapView.Map.AddBookmark(mapView, name);});}
Add New Bookmark from CIMBookmark
publicTask<Bookmark>AddBookmarkFromCameraAsync(Cameracamera,stringname){return QueuedTask.Run(()=>{//Set properties for CameraCIMViewCameracimCamera=new CIMViewCamera(){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=new CIMBookmark(){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.return mapView.Map.AddBookmark(cimBookmark);});}
Get the collection of bookmarks for the project
publicTask<ReadOnlyObservableCollection<Bookmark>>GetProjectBookmarksAsync(){//Get the collection of bookmarks for the project.return QueuedTask.Run(()=> Project.Current.GetBookmarks());}
Get Map Bookmarks
publicTask<ReadOnlyObservableCollection<Bookmark>>GetActiveMapBookmarksAsync(){return QueuedTask.Run(()=>{//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnnull;//Return the collection of bookmarks for the map.return mapView.Map.GetBookmarks();});}
Move Bookmark to the Top
public Task MoveBookmarkToTopAsync(Mapmap,stringname){return QueuedTask.Run(()=>{//Find the first bookmark with the namevarbookmark= map.GetBookmarks().FirstOrDefault(b => b.Name ==name);if(bookmark==null)return;//Remove the bookmark map.MoveBookmark(bookmark,0);});}
Rename Bookmark
public Task RenameBookmarkAsync(Bookmarkbookmark,stringnewName){return QueuedTask.Run(()=> bookmark.Rename(newName));}
Remove bookmark with a given name
public Task RemoveBookmarkAsync(Mapmap,stringname){return QueuedTask.Run(()=>{//Find the first bookmark with the namevarbookmark= map.GetBookmarks().FirstOrDefault(b => b.Name ==name);if(bookmark==null)return;//Remove the bookmark map.RemoveBookmark(bookmark);});}
Change the thumbnail for a bookmark
public Task SetThumbnailAsync(Bookmarkbookmark,stringimagePath){//Set the thumbnail to an image on disk, ie. C:\Pictures\MyPicture.png.BitmapImageimage=new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));return QueuedTask.Run(()=> bookmark.SetThumbnail(image));}
Update Bookmark
public Task UpdateBookmarkAsync(Bookmarkbookmark){return QueuedTask.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
public Task UpdateBookmarkExtentAsync(Bookmarkbookmark, ArcGIS.Core.Geometry.Envelope envelope){return QueuedTask.Run(()=>{//Get the bookmark's definitionvarbookmarkDef= bookmark.GetDefinition();//Modify the bookmark's location bookmarkDef.Location =envelope;//Clear the camera as it is no longer valid. bookmarkDef.Camera =null;//Set the bookmark definition bookmark.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=new TimeDelta(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.return cameraTrack.Keyframes.OfType<CameraKeyframe>().ToList();}
Interpolate Camera
publicTask<List<Camera>>GetInterpolatedCameras(){//Return the collection representing the camera for each frame in animation.return QueuedTask.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.return QueuedTask.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.return QueuedTask.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.Range range,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=await QueuedTask.Run(()=>{//add these to the overlayreturn mapView.AddOverlay(point, SymbolFactory.Instance.ConstructPointSymbol( ColorFactory.Instance.RedRGB,30.0, SimpleMarkerStyle.Star).MakeSymbolReference());});// update the overlay with new point graphic symbol
MessageBox.Show("Now to update the overlay...");await QueuedTask.Run(()=>{ mapView.UpdateOverlay(_graphic, point, SymbolFactory.Instance.ConstructPointSymbol( ColorFactory.Instance.BlueRGB,20.0, SimpleMarkerStyle.Circle).MakeSymbolReference());});// clear the overlay display by disposing of the graphic
MessageBox.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=new CIMPictureGraphic
{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=new CIMTextSymbol();//define the text graphicvartextGraphic=new CIMTextGraphic();await QueuedTask.Run(()=>{//Create a simple text symboltextSymbol= SymbolFactory.Instance.ConstructTextSymbol(ColorFactory.Instance.BlackRGB,8.5,"Corbel","Regular");//Sets the geometry of the text graphic textGraphic.Shape =geometry;//Sets the text string to use in the text graphic textGraphic.Text ="This is my line";//Sets symbol to use to draw the text graphic textGraphic.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;}protectedoverride Task OnToolActivateAsync(boolhasMapViewChanged){return QueuedTask.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}protectedoverride Task HandleMouseDownAsync(MapViewMouseButtonEventArgse){return QueuedTask.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){return QueuedTask.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=new Cursor(new MemoryStream(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;}protectedoverride Task HandleMouseDownAsync(MapViewMouseButtonEventArgse){//Get the instance of the ViewModelvarvm= EmbeddableControl;if(vm==null)return Task.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.return QueuedTask.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;}protectedoverride Task HandleMouseDownAsync(MapViewMouseButtonEventArgse){//Get the instance of the ViewModelvarvm= OverlayEmbeddableControl;if(vm==null)return Task.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.return QueuedTask.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.SelectionColor as CIMRGBColor; 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);});