arcgis pro Geoprocessing

地理处理公共API通过ArcGIS Pro API参考指南中的“ArcGIS.Desktop.Core.geoprocessing”命名空间公开。地理处理任务的核心有用方法、枚举器和接口在此命名空间中可用。
ArcGIS.Desktop.Core.Geoprocessing.dll

Performing analysis and geoprocessing

“ArcGIS.Desktop.Core.Geoprocessing”命名空间中提供的Geoprocesssing API都是关于如何使用.NET在ArcGIS Pro中执行分析的。它公开了执行任何地理处理工具的方法。
要使用Geoprocessing API,首先需要创建一个外接程序,该外接程序执行涉及ExecuteToolAsync的代码,以响应与外接程序交互触发的事件(例如,Button Click)。
使用ExecuteToolAsync方法运行任何地理处理工具(包括Python脚本工具和模型)。插件的代码可以使用地图图层、动态创建的几何图形或存储在磁盘上的数据作为分析输入。您可以为地理处理工具提供数据路径,也可以在ArcGIS Pro的“地理处理”窗格中打开工具对话框,让用户提供参数值并执行该工具。
每个地理处理工具都采用一组不同类型的输入数据,如要素类、表格、几何图形、工作空间、空间参照等,在大多数情况下,都会创建新数据作为输出。请参阅该工具的帮助页面,了解该工具的行为,并获取适当的数据类型以及输入和输出参数的可接受值。
ExecuteToolAsync有一个重载;这两种方法都需要执行工具的路径,所有输入和输出都打包在一个数组中。输入-输出参数值是位置的;您必须保持工具帮助页上指定的相同位置和顺序。
在ArcGIS Pro中,您无法再在.NET中创建自己的自定义地理处理工具。但是,您可以使用Python脚本创建一个工具,并在.NET代码中调用它。
如果您需要在调用之间使用用户的输入来运行一系列工具,请使用设置了适当模型参数的序列创建一个模型,然后在代码中调用此模型工具。

Before calling the ExecuteToolAsync method

在调用ExecuteToolAsync之前,请遵循以下准备步骤,以避免陷阱和简单错误。

Refer to the tool documentation page

记下以下内容:

  • 工具名称和工具箱别名。两者都区分大小写。
  • 正确参数序列的语法。请注意哪些参数是必需的,哪些是可选的。
  • 为参数提供的数据类型和可接受值。在.Net中,您始终可以传递参数值的字符串。您还可以将一些受支持的本机对象的本机.Net对象作为参数值传递。
  • 该工具使用的环境名称。
  • 通过检查Python代码示例使用该工具的示例。
    因此,对于引用系统工具箱工具,指定工具箱的完整路径或使用约定“ToolboxName.ToolName”是等效的。例如,它们都是等价的:
var path = @"C:\<ArcGIS Pro Install Path>\Resources\ArcToolBox\Toolboxes\Analysis Tools.tbx";
var long_tool_name = System.IO.Path.Combine(path, "Buffer");

var short_tool_name = "analysis.Buffer";

对于自定义工具,因为它们不是系统工具箱工具,所以应始终提供工具箱的完全限定路径。因此,例如,给定一个名为“DeepThought.tbx”的自定义工具箱,其中包含一个名“Answer”的python脚本工具,该工具安装在特定计算机上的文件夹“C:\Data\DeepThroughtProAddin\Toolboxes\Toolboxes”中,工具名称将指定为:

var path = @"C:\Data\DeepThought-ProAddin\Toolboxes\toolboxes\DeepThought.tbx";
var long_tool_name = System.IO.Path.Combine(path, "Answer");

Create the array of parameter values

使用MakeValueArray方法创建要传递给ExecuteToolAsync方法的数组。使用MakeValueArray可确保ExecuteToolAsync正确处理参数值。以下是创建参数值数组的代码示例:

// the tool to be executed has workspace as first parameter
// feature class name as second and feature type as third parameter
string outpath = Project.Current.DefaultGeodatabasePath;
string fcname = "accident_sites";
var sr = await QueuedTask.Run(() => {
    return SpatialReferenceBuilder.CreateSpatialReference(3857);
});
// must maintain the sequence and position of each parameter value
var parameters = Geoprocessing.MakeValueArray(outpath, fcname, "POINT", "", "", "", sr);

Create the array of parameter values using Geometries

许多工具使用任意几何图形作为其输入参数列表的一部分(例如剪辑或缓冲区多边形)。所有几何图形和信封都可以传递给“Geoprocessing.MakeValueArray”,以创建与“Geoproessing.ExecuteToolAsync”和“Geoprossing.OpenToolDialog”兼容的参数值。
下面是创建包含任意几何图形的参数值数组的两个示例。请注意,在由Geoprocessing.MakeValueArray参数化之前,必须将要参数化的几何图形/几何图形添加到列表中:

 var mv = MapView.Active;
 var tool_name = "analysis.Buffer";

 var val_array = await QueuedTask.Run(() =>  {

    var center_pt = MapPointBuilderEx.CreateMapPoint(mv.Camera.X, mv.Camera.Y, mv.Camera.SpatialReference);
    var poly = GeometryEngine.Instance.Buffer(center_pt, 2000);
    //add the geometry to a list before parameterizing
    var geom_values = new List<object>() { poly };
     return Geoprocessing.MakeValueArray(new object[] { geom_values, null, @"1000 Meters" });

 });
 //execute the tool with ExecuteToolAsync
 //Geoprocessing.ExecuteToolAsync(tool_name, val_array,
 //                      null, null, null, GPExecuteToolFlags.InheritGPOptions);

 //Invoke on the UI - show the tool dialog pre-populated with the parameter values
 Geoprocessing.OpenToolDialog(tool_name, val_array, null, false);
var tool_name = "analysis.Clip";
 var extent = MapView.Active.Extent;
 var sel_layer = MapView.Active.Map.GetLayersAsFlattenedList()
                        .OfType<FeatureLayer>().FirstOrDefault(l => l.Name == "GreatLakes");
 if (sel_layer == null) return;

 var gdb = Project.Current.DefaultGeodatabasePath;
 var out_fc = System.IO.Path.Combine(gdb, "clipped_lakes_out");

 var val_array = await QueuedTask.Run(() => {
   var rect = GeometryEngine.Instance.Scale(extent, extent.Center, 0.5, 0.5) as Envelope;
   var clip_poly = PolygonBuilderEx.CreatePolygon(rect, rect.SpatialReference);

   //Add the geometry to a list before calling MakeValueArray
   //Envelope and Geometry types are supported
   var geom = new List<object>() { clip_poly };
   return Geoprocessing.MakeValueArray(new object[] { sel_layer, geom, out_fc });
 });
 Geoprocessing.ExecuteToolAsync(tool_name, val_array,
        null, null, null, GPExecuteToolFlags.InheritGPOptions);

Create an array of environment settings

要设置一个或多个环境以供工具执行时使用,请使用MakeEnvironmentArray,如以下代码段所示:

// create the spatial reference object
var sp_ref = await QueuedTask.Run(() => {
    return SpatialReferenceBuilder.CreateSpatialReference(26911);  // UTM 83 11N: 26911
});

// create an extent object
var ext = "460532 3773964 525111 3827494";
// follow syntax env_name: env_value
// environment names will be available in the intellisense          
var environments = Geoprocessing.MakeEnvironmentArray(outputCoordinateSystem: sp_ref, extent: ext);

注意:每个地理处理工具都支持特定的环境。请参阅工具帮助页,以了解该工具支持哪些环境。但是,ExecuteToolAsync方法将忽略设置工具不支持的环境。

Supported native objects as parameter values

在许多情况下,可能需要将图层、与地图交互时创建的几何图形、封套或范围、空间参考或表格作为参数传递给地理处理工具。支持以下.Net类型,可以作为参数值传递:

  • Scalars 长、短、浮点、双精度、日期、字符串
  • ArcGIS.Core.Geometry.SpatialReference
  • ArcGIS.Core.Geometry – 几何图形–点、线、多边形
  • ArcGIS.Core.Geometry.Envelope –支持GPExtentEnv、GPExtent、GPEneveope等GP类型
  • ArcGIS.Core.Data.Field – 支持GPField和GPFieldList的字段列表
  • ArcGIS.Desktop.Mapping –图层、标准表
  • ArcGIS.Core.Data.Dataset –表、特征类
// example of using ArcGIS.Core.Geometry.SpatialReference object
var spatial_ref = await QueuedTask.Run(() => {
    return SpatialReferenceBuilder.CreateSpatialReference(3857);
});
// call MakeValueArray on spatial_ref so that ExecuteToolAsync can internally use the object
var sr_param = Geoprocessing.MakeValueArray(spatial_ref);

Decide which ExecuteToolAsync to use

ExecuteToolAsync过载;有两种方法具有相同的名称和不同的参数签名。要处理地理处理事件,请将ExecuteToolAsync与GPToolExecuteEventHandler类型的参数一起使用。要显示progressor对话框,请使用参数类型为CancelableProgressor的对话框。

Executing geoprocessing tools

Executing a tool with event handling

重载的ExecuteToolAsync方法之一具有GPToolExecuteEventHandler类型的委托参数。要处理各种事件,如OnValidate、OnProgressMessage、OnBeginExecute、OnProgress Pos、OnbeginExecutive和OnEndExecutes,请传递回调(第五个参数),如以下代码示例所示:

// code in the implementing method that Button's OnClick can call
string ozone_points = @"C:\data\ca_ozone.gdb\MarchValues";

var args = Geoprocessing.MakeValueArray(ozone_points, "OZONE", "", "in_memory\\raster", "300", "EMPIRICAL", 
               "300", "5", "5000",
               "NBRTYPE=StandardCircular RADIUS=310833.272442914 ANGLE=0 NBR_MAX=10 SECTOR_TYPE=ONE_SECTOR",
               "PREDICTION", "0.5", "EXCEED", "", "K_BESSEL" );

string tool_path = "ga.EmpiricalBayesianKriging";

// cancellation token variable is declared as a class member
System.Threading.CancellationTokenSource _cts = new System.Threading.CancellationTokenSource();

var result = Geoprocessing.ExecuteToolAsync(tool_path, args, null, _cts.Token,
    (event_name, o) =>  // implement delegate and handle events, o is message object.
    {
        switch (event_name){     
            case "OnValidate": // stop execute if any warnings
                if ((o as IGPMessage[]).Any(it => it.Type == GPMessageType.Warning))
                    _cts.Cancel();
                break;
            case "OnProgressMessage":
                string msg = string.Format("{0}: {1}", new object[] { event_name, (string)o });
                System.Windows.MessageBox.Show(msg);
                _cts.Cancel();
                break;
            case "OnProgressPos":
                string msg2 = string.Format("{0}: {1} %", new object[] { event_name, (int)o });
                System.Windows.MessageBox.Show(msg2);
                _cts.Cancel();
                break;
        }
    });

Executing a tool with the progress dialog

此示例使用带有Cancel选项的CancelableProgressorSource,以便用户可以在执行完成之前终止执行。

protected override async void OnClick()
{
    var progDlg = new ProgressDialog("Running Geoprocessing Tool", "Cancel", 100, true);
    progDlg.Show();

    var progSrc = new CancelableProgressorSource(progDlg);
    string infc = @"D:\data\california\california.gdb\ca_highways";
    string outfc = System.IO.Path.Combine(ArcGIS.Desktop.Core.Project.Current.DefaultGeodatabasePath, 
                                                                        "Clipped_points");
    var parameters = Geoprocessing.MakeValueArray(infc, outfc);
    await Geoprocessing.ExecuteToolAsync("management.CopyFeatures", parameters,
        null, new CancelableProgressorSource(progDlg).Progressor, GPExecuteToolFlags.Default);

    progDlg.Hide();
}

Executing model and script tools

使用.NET创建自己的地理处理自定义工具不再可用。然而,您可以利用ArcPy包的强大功能在Python中创建自定义工具。您还可以通过编织一系列系统工具并在.NET中调用模型工具来创建模型。
传递脚本工具或模型的完整路径。遵循前面描述的准备步骤。请务必从其文档中获取该工具的语法。

// get the model tool's parameter syntax from the model's help 
string input_roads = @"C:\data\Input.gdb\PlanA_Roads";
string buff_dist_field = "Distance";   // use the distance values from a field named Distance
string input_vegetation = @"C:\data\Input.gdb\vegtype";
string output_data = @"C:\data\Output.gdb\ClippedFC2";

string tool_path = @"C:\data\CompletedModels.tbx\ExtractVegetationforProposedRoads";

var args = Geoprocessing.MakeValueArray(input_roads, buff_dist_field, input_vegetation, output_data);

return Geoprocessing.ExecuteToolAsync(tool_path, args);

Executing a geoprocessing service

首先创建一个*.ags文件,并传递服务的完整路径。

// pass the full path of the service
string tool_path = @"C:\data\agsonline.ags\Network/ESRI_DriveTime_US\CreateDriveTimePolygons";
string in_point = @"C:\MyProject\MyProject.gdb\apoint";

var result = await Geoprocessing.ExecuteToolAsync(tool_path, Geoprocessing.MakeValueArray(in_point, "3 9 12"));

Adding results to Map and Project history

ExecuteToolAsync方法的最后一个参数的类型是GPExecuteToolFlags。根据需要使用以下值之一。使用GPExecuteToolFlags。默认值将输出添加到映射并刷新项目项。

GPExecuteToolFlags.AddOutputsToMap
GPExecuteToolFlags.AddToHistory
GPExecuteToolFlags.RefreshProjectItems
GPExecuteToolFlags.Default

Open the tool dialog in the Geoprocessing pane

OpenToolDialog方法在“地质处理”窗格中打开工具对话框,允许用户输入输入值并手动运行工具。您可以在打开工具对话框之前填写外接程序代码中计算的参数值,打开对话框,并让用户填写其他值。应始终在UI线程上调用OpenToolDialog。以下是三个示例:
此代码打开“缓冲区”对话框,其中填写了所有三个必需值:


//On the UI thread
string input_points = @"C:\data\ca_ozone.gdb\ozone_points";
string output_polys = @"C:\data\ca_ozone.gdb\ozone_buff";
string buffer_dist = "2000 Meters";
var param_values = Geoprocessing.MakeValueArray(input_points, output_polys, buffer_dist);

Geoprocessing.OpenToolDialog("analysis.Buffer", param_values);

此代码将打开“缓冲区”对话框,其中填充了前两个参数值:

//On the UI thread
string input_points = @"C:\data\ca_ozone.gdb\ozone_points";
string output_polys = @"C:\data\ca_ozone.gdb\ozone_buff";
string buffer_dist = "";
var param_values = Geoprocessing.MakeValueArray(input_points, output_polys, buffer_dist);
 
Geoprocessing.OpenToolDialog("analysis.Buffer", param_values);

此代码打开“缓冲区”对话框,其中没有任何参数的值,用户可以完全控制要使用的值:

//On the UI
string input_points = "";
string output_polys = "";
string buffer_dist = "";
var param_values = Geoprocessing.MakeValueArray(input_points, output_polys, buffer_dist);

Geoprocessing.OpenToolDialog("analysis.Buffer", param_values);

在本例中,工具参数在QueuedTask上配置,并通过UI线程传递给OpenToolDialog:

 var mv = MapView.Active;

 //configure parameters on the QueuedTask
 var val_array = await QueuedTask.Run(() =>  {

    var center_pt = MapPointBuilderEx.CreateMapPoint(mv.Camera.X, mv.Camera.Y, mv.Camera.SpatialReference);
    var poly = GeometryEngine.Instance.Buffer(center_pt, 2000);
    //add the geometry to a list before parameterizing
    var geom_values = new List<object>() { poly };
     return Geoprocessing.MakeValueArray(new object[] { geom_values, null, @"1000 Meters" });

 });

 //show the tool dialog pre-populated with the parameter values on the UI thread
 Geoprocessing.OpenToolDialog("analysis.Buffer", val_array, null, false);

After execution of the geoprocessing tools is complete

您可以通过检查IGPResult对象来确定执行是否成功。下面的代码通过检查是否失败来检查执行是否失败gp_result.IsFailed是否为true。

Using result and message objects

您可以从结果对象获取地理处理消息,如下所示:

// gp_result is the returned result object from a call to ExecuteToolAsync
// displays error messages if the tool fails, otherwise shows the default messages
Geoprocessing.ShowMessageBox(gp_result.Messages, "GP Messages", 
                gp_result.IsFailed ? GPMessageBoxStyle.Error : GPMessageBoxStyle.Default);

Running ArcPy Python from Pro Addin

test1.py脚本(在“C:\scripts文件夹”中)运行一个地理处理工具,并以字符串形式返回消息。在.NET中,您可以截取该值并使用它。该机制提供了一种在更简单、但功能强大的ArcPy模块的方法和函数中实现工作流并在.NET中使用的方法。

object myCommand = "python " + @"C:\scripts\test1.py";
System.Diagnostics.ProcessStartInfo procStartInfo = 
               new System.Diagnostics.ProcessStartInfo("cmd", "/c" + myCommand );

procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();

string result = proc.StandardOutput.ReadToEnd();

System.Windows.MessageBox.Show(result);

Geoprocessing Options

与Pro选项UI上的选项子集相对应的地理处理选项可通过静态ApplicationOptions在api中获得。GeoprocessingOptions属性-有关详细信息,请参阅ProConcepts Content-ApplicationOptions。可用选项包括:

 //ArcGIS.Desktop.Core.GeoprocessingOptions 
 //Gets and sets the available application geoprocessing options
 public class GeoprocessingOptions {
   //Gets whether geoprocessing tools can overwrite existing data, layers, or files when run.
   public bool OverwriteExistingDatasets { get; }
   //Gets whether layers in a map are removed if their source datasets are deleted
   //by a geoprocessing tool that overwrites output.
   public bool RemoveOverwrittenLayers { get; }
   //Gets whether output datasets created by geoprocessing tools should be automatically
   //added to an open map.
   public bool AddOutputDatasetsToOpenMap { get; }
   //Gets whether the tools being run are added to the current project's geoprocessing history.
   public bool WriteGPOperationsToHistory { get; }

   //Sets whether geoprocessing tools can overwrite existing data, layers, or files
   //when run. This method must be called on the MCT. Use QueuedTask.Run.
   public void SetOverwriteExistingDatasets(bool overwriteExistingDatasets);

   //Sets whether layers in a map are removed if their source datasets are deleted by a geoprocessing 
   //tool that overwrites output. This method must be called on the MCT. Use QueuedTask.Run.
   public void SetRemoveOverwrittenLayers(bool removeOverwrittenLayers);

   //Sets whether output datasets created by geoprocessing tools should be automatically
   //added to an open map. This method must be called on the MCT. Use QueuedTask.Run.
   public void SetAddOutputDatasetsToOpenMap(bool addOutputDatasetsToOpenMap);

   //Sets whether the tools being run are added to the current project's geoprocessing
   //history. This method must be called on the MCT. Use QueuedTask.Run.
   public void SetWriteGPOperationsToHistory(bool writeGPOperationsToHistory);	
}

请注意使用显式的“Set”方法而不是“Setter”属性。这是因为设置GP选项值需要使用通过QueuedTask.Run(…)访问的Pro主CIM线程MCT。还应注意,更改这些选项值会修改交互式GP工具的行为,而不是Geoprocessing.ExecuteToolAsync(…)的行为。要修改ExecuteToolAsync的行为,外接程序开发人员应使用其ArcGIS.Desktop.Core.Geoprocessing。GPExecuteToolFlags参数。

 //Get the current option values
 var overwrite_gp = ApplicationOptions.GeoprocessingOptions.OverwriteExistingDatasets;
 var remove_gp = ApplicationOptions.GeoprocessingOptions.RemoveOverwrittenLayers;
 var addoutput_gp = ApplicationOptions.GeoprocessingOptions.AddOutputDatasetsToOpenMap;
 var history_gp = ApplicationOptions.GeoprocessingOptions.WriteGPOperationsToHistory;

 //Setting GeoprocessingOptions requires the QueuedTask. We are modifying the behavior
 //of interactive GP tools _only_.
 QueuedTask.Run(() => {
   ApplicationOptions.GeoprocessingOptions.SetOverwriteExistingDatasets(true);
   ApplicationOptions.GeoprocessingOptions.SetRemoveOverwrittenLayers(false);
   ApplicationOptions.GeoprocessingOptions.SetAddOutputDatasetsToOpenMap(true);
   ApplicationOptions.GeoprocessingOptions.SetWriteGPOperationsToHistory(false);
 });

参考
参考2
examples

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

假装我不帅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值