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;}
Test if the view is 3D
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;}
Rotate the map view
publicvoidRotateView(doubleheading){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return;//Get the camera for the view, adjust the heading and zoom to the new camera position.varcamera= mapView.Camera;
camera.Heading =heading;
mapView.ZoomToAsync(camera, TimeSpan.Zero);}
//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.varselectedFeatures= 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);});}
// 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);
//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);
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);}
Zoom
Zoom to an extent
publicasyncTask<bool>ZoomToExtentAsync(doublexMin,doubleyMin,doublexMax,doubleyMax,
ArcGIS.Core.Geometry.SpatialReference spatialReference){//Get the active map view.varmapView= MapView.Active;if(mapView==null)returnfalse;//Create the envelopevarenvelope=await
QueuedTask.Run(()=> ArcGIS.Core.Geometry.EnvelopeBuilder.CreateEnvelope(xMin, yMin, xMax, yMax, spatialReference));//Zoom the view to a given extent.returnawait mapView.ZoomToAsync(envelope, TimeSpan.FromSeconds(2));}
Zoom to a specified point
//Note: Run within QueuedTask//Create a pointvarpt= MapPointBuilder.CreateMapPoint(x, y, SpatialReferenceBuilder.CreateSpatialReference(4326));//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 effect
MapView.Active.ZoomTo(poly,new TimeSpan(0,0,0,3));
Zoom to visible layers
publicTask<bool>ZoomToVisibleLayersAsync(){//Get the active map view.varmapView= MapView.Active;if(mapView==null)return Task.FromResult(false);//Zoom to all visible layers in the map.varvisibleLayers= mapView.Map.Layers.Where(l => l.IsVisible);return mapView.ZoomToAsync(visibleLayers);}
Zoom to selected layers in TOC
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);}
Zoom 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);}
publicTask<bool>ZoomToBookmarkAsync(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);});}
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);});}
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);});}
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());}
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));}
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);}
//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",Box=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);//Show a message box reporting each layer the number of the features. MessageBox.Show( String.Join("\n", results.Select(kvp => String.Format("{0}: {1}", kvp.Key.Name, kvp.Value.Count()))),"Identify Result");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(MapExploration.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;}