Skip to content

ProSnippets MapExploration

ArcGIS Pro SDK edited this page Jul 21, 2015 · 31 revisions
Language:      C#
Subject:       MapExploration
Contributor:   ArcGIS Pro SDK Team <arcgisprosdk@esri.com>
Organization:  Esri, http://www.esri.com
Date:          7/13/2015
ArcGIS Pro:    ArcGIS Pro 1.1
Visual Studio: Visual Studio 2013

##Get the active map's name

public string GetActiveMapName()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return null;

  //Return the name of the map currently displayed in the active map view.
  return mapView.Map.Name;
}

##Select all feature layers in TOC

public void SelectAllFeatureLayersInTOC()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return;

  //Zoom to the selected layers in the TOC
  var featureLayers = mapView.Map.Layers.OfType<FeatureLayer>();
  mapView.SelectLayers(featureLayers.ToList());
}

##Flash selected features

public Task FlashSelectedFeaturesAsync()
{
  return QueuedTask.Run(() =>
  {
    //Get the active map view.
    var mapView = MapView.Active;
    if (mapView == null)
      return;

    //Get the selected features from the map and filter out the standalone table selection.
    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);
  });
}

##Test if the view is 3D

public bool IsView3D()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return false;

  //Return whether the viewing mode is SceneLocal or SceneGlobal
  return mapView.ViewingMode == ArcGIS.Core.CIM.MapViewingMode.SceneLocal || mapView.ViewingMode == ArcGIS.Core.CIM.MapViewingMode.SceneGlobal;
}

##Rotate the map view

public void RotateView(double heading)
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return;

  //Get the camera for the view, adjust the heading and zoom to the new camera position.
  var camera = mapView.Camera;
  camera.Heading = heading;
  mapView.ZoomToAsync(camera, TimeSpan.Zero);
}

##Zoom to an extent

public async Task<bool> ZoomToExtentAsync(double xMin, double yMin, double xMax, double yMax, ArcGIS.Core.Geometry.SpatialReference spatialReference)
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return false;

  //Create the envelope
  var envelope = await QueuedTask.Run(() => ArcGIS.Core.Geometry.EnvelopeBuilder.CreateEnvelope(xMin, yMin, xMax, yMax, spatialReference));

  //Zoom the view to a given extent.
  return await mapView.ZoomToAsync(envelope, TimeSpan.FromSeconds(2));
}

##Zoom to visible layers

public Task<bool> ZoomToVisibleLayersAsync()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return Task.FromResult(false);

  //Zoom to all visible layers in the map.
  var visibleLayers = mapView.Map.Layers.Where(l => l.IsVisible);
  return mapView.ZoomToAsync(visibleLayers);
}

##Zoom to selected layers in TOC

public Task<bool> ZoomToTOCSelectedLayersAsync()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return Task.FromResult(false);

  //Zoom to the selected layers in the TOC
  var selectedLayers = mapView.GetSelectedLayers();
  return mapView.ZoomToAsync(selectedLayers);
}

##Zoom to previous camera

public Task<bool> ZoomToPreviousCameraAsync()
{
  //Get the active map view.
  var mapView = MapView.Active;
  if (mapView == null)
    return Task.FromResult(false);

  //Zoom to the selected layers in the TOC
  if (mapView.HasPreviousCamera())
    return mapView.PreviousCameraAsync();

  return Task.FromResult(false);
}

##Zoom to a bookmark with a given name

public Task<bool> ZoomToBookmarkAsync(string bookmarkName)
{
  return QueuedTask.Run(() =>
  {
    //Get the active map view.
    var mapView = MapView.Active;
    if (mapView == null)
      return false;

    //Get the first bookmark with the given name.
    var bookmark = mapView.Map.GetBookmarks().FirstOrDefault(b => b.Name == bookmarkName);
    if (bookmark == null)
      return false;

    //Zoom the view to the bookmark.
    return mapView.ZoomTo(bookmark);
  });
}

##Create a new bookmark using the active map view

public Task<Bookmark> AddBookmarkAsync(string name)
{
  return QueuedTask.Run(() =>
  {
    //Get the active map view.
    var mapView = MapView.Active;
    if (mapView == null)
      return null;

    //Adding a new bookmark using the active view.
    return mapView.Map.AddBookmark(mapView, name);
  });
}

##Remove bookmark with a given name

public Task RemoveBookmarkAsync(Map map, string name)
{
  return QueuedTask.Run(() =>
  {
    //Find the first bookmark with the name
    var bookmark = 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

public Task<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(Bookmark bookmark, string imagePath)
{
  //Set the thumbnail to an image on disk, ie. C:\Pictures\MyPicture.png.
  BitmapImage image = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));
  return QueuedTask.Run(() => bookmark.SetThumbnail(image));
}

##Project camera into a new spatial reference

public Task<Camera> ProjectCamera(Camera camera, ArcGIS.Core.Geometry.SpatialReference spatialReference)
{
  return QueuedTask.Run(() =>
  {
    var mapPoint = MapPointBuilder.CreateMapPoint(camera.X, camera.Y, camera.Z, camera.SpatialReference);
    var newPoint = GeometryEngine.Project(mapPoint, spatialReference) as MapPoint;
    var newCamera = new Camera()
    {
      X = newPoint.X,
      Y = newPoint.Y,
      Z = newPoint.Z,
      Scale = camera.Scale,
      Pitch = camera.Pitch,
      Heading = camera.Heading,
      Roll = camera.Roll,
      Viewpoint = camera.Viewpoint,
      SpatialReference = spatialReference
    };
    return newCamera;
  });
}

##Step forward in time by 1 month

public void StepMapTime()
{
  //Get the active view
  MapView mapView = MapView.Active;
  if (mapView == null)
    return;

  //Step current map time forward by 1 month
  TimeDelta timeDelta = new TimeDelta(1, TimeUnit.Months);
  mapView.Time = mapView.Time.Offset(timeDelta);
}

##Change symbol for a sketch tool

internal class SketchTool_WithSymbol : MapTool
{
  public SketchTool_WithSymbol()
  {
    IsSketchTool = true;
    SketchOutputMode = SketchOutputMode.Map; //Changing the Sketch Symbol is only supported with map sketches.
    SketchType = SketchGeometryType.Rectangle;
  }

  protected override Task OnToolActivateAsync(bool hasMapViewChanged)
  {
    return QueuedTask.Run(() =>
    {
      //Set the Sketch Symbol if it hasn't already been set.
      if (SketchSymbol != null)
        return;
      var polygonSymbol = SymbolFactory.ConstructPolygonSymbol(ColorFactory.CreateRGBColor(24, 69, 59), SimpleFillStyle.Solid, SymbolFactory.ConstructStroke(ColorFactory.Black, 1.0, SimpleLineStyle.Dash));
      SketchSymbol = SymbolFactory.MakeSymbolReference(polygonSymbol);
    });
  }
}

##Create a tool to the return coordinates of the point clicked in the map

internal class GetMapCoordinates : MapTool
{
  protected override void OnToolMouseDown(MapViewMouseButtonEventArgs e)
  {
    if (e.ChangedButton == System.Windows.Input.MouseButton.Left)
      e.Handled = true; //Handle the event args to get the call to the corresponding async method
  }

  protected override Task HandleMouseDownAsync(MapViewMouseButtonEventArgs e)
  {
    return QueuedTask.Run(() =>
    {
      //Convert the clicked point in client coordinates to the corresponding map coordinates.
      var mapPoint = 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

internal class CustomIdentify : MapTool
{
  public CustomIdentify()
  {
    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;
  }

  protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
  {
    return QueuedTask.Run(() =>
    {
      var mapView = MapView.Active;
      if (mapView == null)
        return true;

      //Get all the features that intersect the sketch geometry and flash them in the view. 
      var results = 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");
      return true;
    });
  }
}

##Flash a single Feature on the active map pane

// Flash the Feature
var SelectedFeatureLayer = ... // the BasicFeatureLayer for which to flash the feature
var Oid = ... // object id
IReadOnlyDictionary<BasicFeatureLayer, List<long>> flashFeature = 
    new Dictionary<BasicFeatureLayer, List<long>>()
       {{SelectedFeatureLayer, new List<long>(){Oid}}};
FlashFeaturesAsync(flashFeature);

##Zoom to the extent of all selected features regardless of Feature Layer

/// <summary>
/// Zoom to selection
/// </summary>
private async void Zoom2Select()
{
    var mapView = MapView.Active;
    if (mapView == null) return;
    await QueuedTask.Run(() =>
    {
        //select features that intersect the sketch geometry
        var selection =  mapView.Map.GetSelection()
                .Where(kvp => kvp.Key is BasicFeatureLayer)
                .ToDictionary(kvp => (BasicFeatureLayer)kvp.Key, kvp => kvp.Value);

        //zoom to selection
        MapView.Active.ZoomToAsync(selection.Select(kvp => kvp.Key), true);
    });
}

##Convert selected features for a FeatureLayer into DataTable

private async void GetSelectedFeatures(FeatureLayer selectedFeatureLayer)
{
    //Get the active map view.
    var mapView = MapView.Active;
    if (mapView == null || selectedFeatureLayer == null) return;
    await QueuedTask.Run(() =>
    {
        // Get all selected features for selectedFeatureLayer
        // and populate a datatable with data and column headers
        var resultTable = new DataTable();
        using (var rowCursor = selectedFeatureLayer.GetSelection().Search(null))
        {
            bool bDefineColumns = true;
            while (rowCursor.MoveNext())
            {
                var anyRow = rowCursor.Current;
                if (bDefineColumns)
                {
                    foreach (var fld in anyRow.GetFields().Where(fld => fld.FieldType != FieldType.Geometry))
                    {
                        resultTable.Columns.Add(new DataColumn(fld.Name, typeof(string)) { 
                                                Caption = fld.AliasName });
                    }
                }
                var addRow = resultTable.NewRow();
                foreach (var fld in anyRow.GetFields().Where(fld => fld.FieldType != FieldType.Geometry))
                {
                    addRow[fld.Name] = (anyRow[fld.Name] == null) ? string.Empty : anyRow[fld.Name].ToString();
                }
                resultTable.Rows.Add(addRow);
                bDefineColumns = false;
            }
        }
        lock (_lockSelectedFeaturesDataTable) _selectedFeaturesDataTable = resultTable;
    }).ContinueWith(t =>
    {
        if (t.Exception != null)
        {
            var aggException = t.Exception.Flatten();
            foreach (var exception in aggException.InnerExceptions)
                System.Diagnostics.Debug.WriteLine(exception.Message);
        }
    });
    NotifyPropertyChanged(() => SelectedFeatureDataTable);
}

Home

ProSnippets: MapExploration

Clone this wiki locally