Publish and use ArcGIS Server services - Geoprocessing service (Geoprocessing service)

Geoprocessing services are a way of exposing the powerful analytical capabilities of ArcGIS to the World Wide Web. Essentially your way of exposing the powerful analytical capabilities of ArcGIS to the World Wide Web.

The common ones are:
map service: publish and use ArcGIS Server service - map service (Mapserver)
feature service: publish and use ArcGIS Server service - feature server (feature server)
image service: publish and use ArcGIS Server service - image Service (image server)
OGC service: publish and use ArcGIS Server service – OGC service (WMS/WMTS/WFS/WCS/WPS)
cache service: publish and use ArcGIS Server service – cache service (TileServer) (1)
cache service : Manage and migrate ArcGIS Server services and cache services (TileServer) (2)
Publish and use ArcGIS Server services - Geoprocessing service , vector tile service, scene service
, geographic data service, and geometric service, KML service, Geocoding Service, Locator Maritime Server, Routing Service, Schematics Service, Flow Service, Utility Network Service, Workflow Manager Service, etc.;

In this article, we mainly talk about what is a geoprocessing service:

1. What is geoprocessing service (GP service)

Geoprocessing services contain geoprocessing tasks that take simple data captured in a web application, process it, and return meaningful and useful output in the form of features, maps, reports, and files. One task can calculate the likely evacuated area for a hazardous chemical spill, the projected track and intensity of a hurricane, reports of land cover and soils within user-defined watersheds, parcel maps with historical details of ownership or licensed septic tanks System application. The possibilities with these services are endless.

A geoprocessing service consists of one or more geoprocessing tasks. A geoprocessing task is a geoprocessing tool that runs on a server, and its execution and output are managed through the server. When a geoprocessing result is shared as a geoprocessing service, a corresponding geoprocessing task is created by the tool that created the result.

A useful way of explaining services is to think of services as four separate activities, namely: designing, making, publishing (or sharing), and using (or consuming).

1.1 What is the difference between a geoprocessing service and a geoprocessing tool?

Services and tasks, toolboxes, and tools
If you've worked with geoprocessing services in ArcGIS Desktop, you can think of a geoprocessing service as a toolbox and tasks as the tools in the toolbox. The main difference is that when you execute a task in a geoprocessing service, the task executes on the server computer using the server computer's resources.

A geoprocessing service is like a toolbox, a container that does not perform any processing. However, services have properties that are inherited by all tasks in the service (for example, whether the results are drawn through a corresponding map service, execution mode, number of processes, where to write data, etc.).

When discussing geoprocessing services and tasks, it's easy to confuse a service and its tasks, especially if the service contains only one task. In small talk, it's common to equate services and tasks without (usually) causing confusion.

The implication is that a single tool can complete a single task, multiple tools can handle multiple workflow tasks, a geoprocessing service: can be composed of multiple tools and tasks;

1.2 How to author a geoprocessing task

Authoring a geoprocessing service requires authoring tasks in the service.
To create a task is to select or create a tool, define the input and output parameters of the task, and the location of all the data used by the task. To put it simply, I use the GP tool to create an operation tool that I need to process. Select one or more geoprocessing tools to be a task in the service, the following details several ways to create a geoprocessing service:

Any geoprocessing tool

  • You can use one of several system tools provided by ArcGIS, that is, we can publish any geoprocessing tool;
    insert image description here
    arcmap and arcgis Pro provide thousands of tools for us to use;

When we need to use a certain tool, we can directly run it successfully, and then share it as a GP service, and then use JS to call it at the front end;

or use ModelBuilder

ModelBuilder is an application for creating, editing, and managing models.

A model is a workflow that strings together a series of geoprocessing tools, using the output of one tool as input to another. You can also think of ModelBuilder as a visual programming language for building workflows.

The figure below shows an example of a tool created using ModelBuilder that will be included in a task. The model (and the published task) is a very simple supply and demand allocation model; given a set of point locations representing service provided (such as emergency response or retail facilities), and another set of point locations representing demand (such as homes and stores requiring service offerings), the purpose is to assign demand points to the closest facilities, create trade areas for each facility, and aggregate all demand in the facility trade area. The output is a set of polygons, one polygon for each input facility, each polygon having attributes containing the overall demand within the polygon.
insert image description here
In arcmap, according to our own project requirements, we can complete any complete process project processing requirements we need;

You can author geoprocessing tasks using models and ModelBuilder.
insert image description here
Enter the introduction to the above modelBulider, refer to the official website: Create geoprocessing tasks with ModelBuilder

or Python scripts to create your own tools

insert image description here

Refer to the official website link below:
How ArcGIS Python makes py scripts into python tools (custom geoprocessing tools)

The following link is a short-answer example operation I sorted out:

Author geoprocessing tasks using Python scripts

1.3 How to publish a geoprocessing service

  • To create your own geoprocessing tasks, see 1.2 Introduction.

  • Gather the input data needed to execute the tool. Typically, these datasets are layers in the ArcMap table of contents.

  • Execution tools create results in the Results window.

  • If necessary, define the symbology for the input and output datasets.

  • Share the results as a geoprocessing service. When sharing results, use the service editor to define the input schema for the dataset (described below) and other properties for the service and its tasks.

2. GP service parameter setting

2.1 Introduction to Service Editor

After defining the service to create or overwrite, the Geoprocessing Service Editor opens, as shown in the image below. On the left is a categorized list of modifiable settings. Some of these settings apply to the service, while others apply to tasks within the service. At the top right are buttons for performing actions.
insert image description here
Service settings
Service settings define how clients access services and tasks. These settings will apply to all tasks in the service. For example, one of these parameter settings will determine whether the task's output will be returned to the client as a map image.

Task Settings
Clicking a parameter in the left panel will display its settings in the right panel of the Service Editor. These settings are based on parameter types such as Feature, Table, Raster, String, File, Boolean, and so on.

Import Settings
You can import an existing service definition file or the properties of a published service. Using this method, you avoid using the service editor to configure service properties. Instead, you can import a similar service definition file or properties of a published service.

Adding tasks
A geoprocessing service can contain multiple geoprocessing tasks. Click the Add Result button to add a new task.

Removing a task
To remove a geoprocessing task, right-click the task and select Remove. When you remove a job, the job is removed from the service - the corresponding geoprocessing results and their tools are not deleted.

Preview Tasks
Click the Preview button to show how the task dialog box will appear when used in ArcGIS Desktop. Previewing a task helps to verify modifications made to task parameters. If there are multiple tasks, select the task (or one of its parameters) before clicking the preview button. When publishing, tasks can be previewed any number of times.

Publish Service
Click the Publish button to publish the service. The service will be analyzed and if any errors occur, the preparation window will open and the service will not be published. If there are no errors, a progress dialog opens and you will be prompted when the service publishing is complete.

2.2 Task Settings – Input Mode

When publishing results in the service editor, you need to specify an input mode for each task parameter. The selected mode determines how the client provides values ​​to task parameters. This topic is intended to help you understand why some input mode options are not available for a parameter, and recommends some methods for creating tasks that use the available input mode options.
insert image description here

The input mode is set in the service editor, since this only concerns geoprocessing tasks, not the underlying tool. There are three input modes for input features:

User Defined Value : The client will create a feature set that will be transmitted over the Internet for the task to read. When User Defined Values ​​is specified as the input mode, the feature type, attributes, spatial reference, and symbology of the input layer are stored in the feature set. Clients can retrieve this schema and use it to digitize features into a feature set or load features into a feature set from a file on disk. For input tables, a corresponding recordset is included to store the table's attribute schema.
Pick List : The client can enter the names of one or more layers that you have selected in the layer list. Whether a client can input multiple layers will depend on the tool itself. The Generate Neighbor Table tool shown above allows multiple layers as input. Other tools, such as Buffer, allow only one layer in the input selection list.
Constant value : The task will use the value you specify when you run the tool. The constant value is the same as for the remove parameter - the layer (dataset) is used internally by the task, not provided to the client.

Input mode and parameter data type:
https://desktop.arcgis.com/zh-cn/arcmap/10.7/analyze/sharing-workflows/parameter-data-type-transformations.htm

2.1.1 Non-transferable data

GIS services must use the simplest client of all: a web browser running on a computer without any GIS capabilities. This simple client only knows how to transmit (send and receive) simple data packets to the server, such as text, numbers, files, geographic features and their attributes (fields). In the context of geoprocessing tasks, GIS datasets can be divided into two distinct categories: transportable and non-transportable.

Transferable datasets include features, rasters, tables, and files. Parameters containing transferable data sets support a user-defined value input mode.
Non-transferable datasets include all datasets except features, rasters, tables, and files. Non-transferable data sets fall into two categories.
Complex datasets include geometric networks, network datasets, topologies, TINs, and more. These data types are called complex datasets because they are used to model complex relationships between simple features.
Container datasets include folders, files, and items such as personal geodatabases and map documents (.mxd). These data types are mixed with other data sets - hence, they are called "containers".
Complex datasets and container datasets are not transportable and do not support user-defined value input mode.

2.1.2 Datasets

GIS services must use the simplest client of all: a web browser running on a computer without any GIS capabilities. This simple client only knows how to transmit (send and receive) simple data packets to the server, such as text, numbers, files, geographic features and their attributes (fields). In the context of geoprocessing tasks, GIS datasets can be divided into two distinct categories: transportable and non-transportable.

Transferable datasets include features, rasters, tables, and files. Parameters containing transferable data sets support a user-defined value input mode.
Non-transferable datasets include all datasets except features, rasters, tables, and files. Non-transferable data sets fall into two categories.
Complex datasets include geometric networks, network datasets, topologies, TINs, and more. These data types are called complex datasets because they are used to model complex relationships between simple features.
Container datasets include folders, files, and items such as personal geodatabases and map documents (.mxd). These data types are mixed with other data sets - hence, they are called "containers".
Complex datasets and container datasets are not transportable and do not support user-defined value input mode.

2.1.3 Pick Lists and Non-Transferable Data Sets

If the Input Parameter value is a layer that references a non-transferable dataset, a Selection List can be selected as the Input Mode option. For example, the transportation mode network parameter can be used in the task of finding the best route based on the user's transportation mode (car, bicycle, or walking).

The data type of this parameter is Network Dataset Layer. Web datasets are complex datasets that cannot be transmitted over the web, so user-defined values ​​do not apply to this parameter. However, a selection list can be used to specify a selection list of layer names to use. The client will choose a layer name from the selection list, and the task will use the client-selected layer and access the network dataset referenced by the layer, stored on the server.

Most complex datasets have corresponding layer representations. The example above shows a network dataset layer. Other complex datasets include TIN layers, geostatistical layers, parcel fabric layers, and LAS dataset layers. When you have a non-transportable dataset, you can use its layer representation as an input value. The example task above was created by executing the model and providing the street network layer as input. If the model is executed by providing a path to a network dataset on disk instead of a layer name, the input mode will be set to a constant value. The tool must be executed with a layer as input for the picklist options to appear.

2.3 What is the difference between synchronous and asynchronous

The gp service is divided into asynchronous execution mode and synchronous execution mode. The difference between the two is:

Asynchronous and synchronous define how clients submit execution parameters and get results from tasks. When the service is set to synchronous, the client will wait for the task to complete. Typically, sync tasks execute quickly, taking about 5 seconds or less.
Synchronization: suitable for fast processing, the amount of data is small, the essential difference lies in the synchronous mode, after the server processes, the processing results are not saved on the server, but are sent to the client for display. If the client does not save the result either, then the processing result is lost.

The execution of asynchronous tasks usually takes a long time, and the client must periodically ask the server whether the task is complete, and if so, get the result. Web applications that use asynchronous tasks must add functional logic to check the status of the task and process the results when execution is complete. Asynchronous: It is suitable for long-term processing, and the amount of data is large. The essential difference is the asynchronous mode. After the server processes, the processing results are saved on the server side, which can be found in the arcgisjobs file.

So why does the GP service set these two different execution types?

Geoprocessing tasks can range from simple geoprocessing functions, which may take seconds to execute on the server, to advanced functions (processing large datasets), which may take longer to process. Therefore, the REST API provides two options for running geoprocessing tasks on the server.

Synchronous : Synchronous tasks are good for running tasks quickly. In a synchronous task, the client sends a request to run the task, and the result of the task is sent to the client as a response.

Asynchronous : Asynchronous tasks are suitable for long-running jobs. In an asynchronous task, the server returns a job ID, which the client uses to poll for the status of the task. When the status is complete, the result is created as a subresource of the job, and clients can access the job using its job ID.

3. Geoprocessing service production and release

3.1 Production

To author a geoprocessing task, you typically create a geoprocessing tool using ModelBuilder or Python. You don't have to create your own tools, you can use any of several system tools that come with your ArcGIS installation.

What we use the most is a single tool, or modelbuilder to build our own task flow;

3.2 Release

To publish a tool you've made, you can execute the tool in an ArcGIS Desktop application such as ArcMap or ArcGlobe.

Executing the tool creates results in the Results window. To publish a service, you must have administrator privileges on the ArcGIS Server installation.

To publish the service, right-click the result and click Share As > Geoprocessing Service , as shown in the image below.
insert image description here

This action opens a series of dialogs (shared as Service Step-by-Step Wizard and Service Editor dialog) to create the service definition and the initial tasks to include in the service. The initial task is exactly the same as the tool used to create that result. Results can be added to the service, and all results will become tasks in the service.

After clicking Share As > Geoprocessing Service, the Share As Service wizard opens, as shown in the image below

insert image description here
In the first panel, the options available are as follows:

  • Publish Service - Connect to a server and publish or save as a service definition file to publish later.
  • Save as a service definition file - no need to connect to the server. You'll create a service definition file that you can then publish.
  • Overwrite Existing Service - This is exactly the same as stopping and deleting the existing service before publishing.

If you choose to publish the service, the next dialog provides the service connection and service name. After clicking Next, a folder can be created to store the service.

By default, services are published to the root folder (root) of ArcGIS Server.
Services can also be organized into subfolders under the root folder. Select a folder to publish the service to, or create a new folder containing the service.

If you choose to save as a service definition file, on the next panel you will be given two options: create a service definition for a specific server or create a generic server definition file.

The last panel specifies where to save the completed service definition.

Note:
Beginning with version 10.4, only administrators can publish geoprocessing services. To allow publishers to publish geoprocessing services, add the allowGPAndExtensionPublishingToPublishers property to true in the ArcGIS Server Administrator Directory site properties.

4. use

Every ArcGIS Server has a service directory, accessible by URL; each service on the server has its own service page, also accessible by URL. The above geoprocessing REST service properties can be inspected on the service page within a web browser. This service page is primarily used by web developers to understand the functionality of the service. Even if you're not a web developer, you'll find that the services page helps you understand that decisions you make when publishing your service can affect how developers use your service and tasks internally.
After you have successfully published a geoprocessing service within ArcGIS Desktop, a new geoprocessing service is added to the ArcGIS Server connection in the Catalog window. To view the Services page for your service, right-click the service and select Service Properties. This will open the service editor. In the Service Editor, click the Geoprocessing tab under Capabilities. The REST URL value shown in the following figure is the URL of the service page.
insert image description here

ArcGIS REST web services are based on two clear principles:

  • 1. Each GIS service published on ArcGIS Server is regarded as a resource that can be accessed through a URL, such as http://<host name>/arcgis/rest/<service name>. This URL is also known as the REST endpoint.
  • 2. Each resource includes: attributes describing the resource, operations that can be performed on the resource (optional), sub-resources (optional)

An action is a behavior performed on a resource that triggers a state transition of the resource and/or creates a new resource. A child resource is a resource that exists within the context of its parent resource and inherits the properties of its parent resource. Subresources can also have their own properties and support actions that can be performed on them. An operation for a resource to create endpoint classes and access via URLs for its subresources.

Geoprocessing services and the tasks they contain are available through web clients. Examples of clients that can access GIS services include web browsers, mobile applications, and ArcGIS Engine applications.

Most importantly, GIS services are searchable by users just like any other web resource. You can find GIS resources and use them immediately through the clients or search engines listed above.

4.1 Using geoprocessing services in ArcGIS Desktop

ArcGIS Desktop is one such web client. ArcGIS Desktop allows you to access and use any geoprocessing service without programming.

In ArcGIS Desktop, you can add geoprocessing services and perform various tasks by connecting to an ArcGIS GIS Server site. Also, you must specify a SOAP endpoint (URL) to create an ArcGIS Server connection in ArcGIS Desktop. The SOAP URL can be derived from the REST URL provided by the service description in ArcGIS Online. For example, if the REST URL is:
http://sampleserver.esri.com/arcgis/rest/services//gpserver
then the corresponding SOAP URL to create a server connection is as follows:
http://sampleserver.esri.com/arcgis/services
Create a user connection to the server using this SOAP URL. After creating the connection, search the server directory thoroughly for geoprocessing services and tasks.

https://enterprise.arcgis.com/zh-cn/server/latest/publish-services/windows/a-quick-tour-of-using-a-service-in-desktop.htm

4.2 Using geoprocessing services with ArcGIS Online

ArcGIS Online is a website where maps and other types of geographic information can be used. ArcGIS Online includes maps, data, applications, and tools (including geoprocessing services) from Esri, its partners, and the entire GIS community. With ArcGIS Online, everyone can access, contribute, and share maps, tools, tasks, and applications.

Geoprocessing services in ArcGIS Online Geoprocessing
tasks can be shared when published, or the service and its tasks can be added to ArcGIS Online content through a REST endpoint that provides the service. Likewise, you can search ArcGIS Online to find geoprocessing services shared by the community. In ArcGIS Online, all content is called an item, and all items have a type (such as a web map or feature) and detailed information about the item. The Geoprocessing Service item in ArcGIS Online provides a brief description and REST URL for the service.

4.3 Overview of Geoprocessing REST Services

A geoprocessing service is a resource that is accessed via a URL. The URL format for a geoprocessing service is http://<servername>/<instancename>/rest/services/<servicename>/GPServer, for example http://myServer/ArcGIS/rest/services/BufferPoints/GPServer.

A geoprocessing service has attributes such as service description, task, execution type, and result map server. Geoprocessing tasks published within a geoprocessing service are its subresources.

Geoprocessing services themselves have no operations, but tasks can support submitJob or execute operations. Tasks within a geoprocessing service inherit the Execution Type and Result Map Server properties, and have other properties such as a task description, task parameters, and so on. The properties of services and tasks are determined by the publisher of the service and cannot be modified by the client.

The image below shows the hierarchy of geoprocessing REST resources. Note that the geoprocessing service properties shown in orange, such as execution type, maximum records (which is the maximum number of records in the graph), and result map server, are inherited by each geoprocessing task.

insert image description here

4.4 Using geoprocessing tasks in web applications

The ArcGIS API for JavaScript enables web browsers to communicate with ArcGIS Server services, draw geographic data, and perform analysis. There is no need to download this library as it is accessible through a web URL.

4.4.1 Geoprocessing tasks in web applications

Using geoprocessing services, you can add geoprocessing capabilities and data analysis to your web applications. Each geoprocessing service consists of one or more geoprocessing tasks.
If you browse the ArcGIS Server's Services Directory, you can find geoprocessing services, the tasks within that service, and the parameters and properties for each task. The Geoprocessing REST Services topic provides information on the REST resource class, while the Introduction to Geoprocessing Tasks topic provides details on geoprocessing tasks, parameters, and access methods.

ArcGIS API for JavaScript provides suitable objects and methods for accessing geoprocessing tasks and performing functions.
To add the geoprocessing functionality provided by a task to your web application, follow these four steps:

  • Initializes a geoprocessing task.
  • Set task parameters.
  • Run the task.
  • Render the result.

Through these four steps, the application can communicate with the server, perform tasks successfully, and display the desired results in the application.

4.4.2 Using geoprocessing tasks in the ArcGIS API for JavaScript

With these four steps, you can successfully add geoprocessing functionality using ArcGIS API for JavaScript.

Step 1: Initialize the Geoprocessing Task

To initialize a geoprocessing task, knowledge of the task URL is required. The template for geoprocessing task URLs is https:GPServer/. Add the following code to your JavaScript application to initialize a geoprocessing task.

When performing initialization, ensure that the Geoprocessing task instance's OutSpatialReference property is set to the web map spatial reference. Geoprocessing task datasets may be in different spatial references, and therefore their output will also be in different spatial references.

However, the web application assumes that the task output is the same spatial reference as the map. This can cause unexpected behavior when drawing output. Therefore, the output spatial reference property of the geoprocessing task must be set. The server will return output in the spatial reference specified by the OutSpatialReference property.

Initialize a geoprocessing task

// esri.tasks.gp is required for using Geoprocessor.
//  Add it along with other dojo.require statements.
dojo.require(esri.tasks.gp); 
/* Step 1: Initialize Geoprocessing Task as a global variable. 
    That is, declare the variable outside a function definition 
    since we will be using gpTask variable in other methods */
var gpTaskUrl="https://myserver/ArcGIS/rest/services/" +
                   "BufferPoints/GPServer/BufferPoints";
var gpTask = new esri.tasks.Geoprocessor(gpTaskUrl);	
// Set output spatial reference property to map's spatial reference.
//   myMap is assumed to be an instance of map container esri.map.
gpTask.outSpatialReference=myMap.spatialReference;

Step 2: Set task parameters

When executing a geoprocessing task, the web application must provide parameter values ​​for the geoprocessing task. To learn about the parameter requirements for a task, copy the task URL and paste it into the address bar of your web browser to open the Tasks page of the service catalog. The Tasks page lists all task parameters and their data types. In addition, the task page contains a Help URL where you can find detailed information on geoprocessing functionality, access, and usage.

In order for a task to execute successfully, you must specify values ​​for all input parameters (EsriGPParameterTypeRequired) required by the task, as shown on the Tasks page. Typically, task values ​​come from one or more of the following sources:

  • Values ​​entered by the user using the web application
  • The current value of one of the web map feature layers or graphics layers
  • Results of other tasks, such as queries, routing tasks, etc.
  • Results of other geoprocessing tasks

The following JavaScript code shows an example of creating an input feature GPFeatureRecordsetLayer parameter from a FeatureLayer added to a web map, and using the id="distance" derived GPLinearUnit parameter BuffDistance of a Dojo text input. This example assumes that the user will enter a distance value interactively. After the task parameters are created, a JSON structure with parameter name-value pairs is built and sent to the server.

Setting parameters

//Step 2: Setup Parameters of the task
function setupParameters(){
    
    
   /* The code below assumes that the web map 
     has a featurelayer with id fLayer. */
   // Get Input Parameter 1 : GPFeatureRecordSetLayer from fLayer.
   var inputFeatures = new esri.tasks.FeatureSet();			    
   inputFeatures.features = map.getLayer("fLayer").graphics;
   inputFeatures.fields=map.getLayer("fLayer").fields;
   // Get Input Parameter 2 : GPLinearunit from a dojo UI element
   var buffDistance = new esri.tasks.LinearUnit();
   buffDistance.distance=dojo.byId(“distance”).value;
   buffDistance.units=”esriMiles”;
   // Create Parameter list with name-value pairs.
   // Names must match the parameter name in Task page.
   // Parameters must be in the same-order as in Task page.
   var params= {
    
    "Input_Features":inputFeatures, 
              "Distance":buffDistance};
   // Return name-value pairs of parameters
   return params;
}

Note:
The GPFeatureRecordSetLayer and GPRecordSetLayer parameters have a default scheme defined by the task. You can find parameter schemes on the Tasks page. The GPFeatureRecordSetLayer schema contains geometry, spatial reference, fields, and features. It's best to make sure that the GPFeatureRecordSetLayer parameter has all the properties defined in the schema for successful results.

Step 3: Run the task

To run a job, use the execute or submitJob method of a geoprocessor instance (gpTask) based on the operations supported by the geoprocessing task. You can find out what actions a task supports on the Tasks page. The Task Operations: execute and Task Operations: submitJob topics describe the differences between the various operations and the communication between the server and the client during the operations.

Task operation: execute
If the supported operation of the task is to execute the task, you must use the execute method of the geoprocessor instance and pass the parameters. Event handlers must be defined to manipulate the application based on successful and failed requests. When the task executes successfully, the onExecuteComplete event fires and returns the result and a geoprocessing message. When the task execution fails, the onError event is triggered. When a task fails, the server will return an Error instance containing an HTML error code and a geoprocessing message, if any.

Task operation: execute

function myGPExecuteTask(){
    
    
 // Get params from setupParameters method described above. var params=setupParameters();
 // Setup onTaskSuccess and onTaskFailure event handlers. dojo.connect(gpTask, "onExecuteComplete",onTaskSuccess);
 dojo.connect(gpTask, "onError",onTaskFailure);
 // Execute gpTask with params gpTask.execute(params);
}
// Callback when the Task operation succeeded function onTaskSuccess(results, messages) {
    
    
  // Do something with the results...  // More info on rendering the results in section below    
}
// Handler that is invoked when the Task operation has failed function onTaskFailure(error) {
    
    
  // Report error   alert("Error:"+ error); 
}

Task operation: submitJob

If the operation supported by the job is the submitJob operation, the Geoprocessor.submitJob method must be used and parameters passed. In the case of submitJob, three events are fired which must be handled accordingly in the web application.
insert image description here

  • onStatusUpdate: Different from execute, if it is submitJob, the server will create the job and assign the job Id. The submitJob operation does not notify the client when the job is complete, so the client will check the service itself to determine the job status. By default, the web application sends a status request to the server every second to determine the status of the task. The onStatusUpdate event is fired every time a status response is received. If desired, the status check interval can be increased or decreased by the Geoprocessor.setUpdateDelay method. Every time the job status is checked, the onStatusUpdate event is fired. The event handler receives the JobInfo instance returned by the server, which contains the job ID, job status, and any GPMessages. You can use this information to keep track of task progress.
  • onJobComplete: When JobInfo.jobStatus = STATUS_SUCCEEDED, the onJobComplete event will be triggered. When the operation is complete, the results are not automatically returned to the client, but are stored on the server, and the client must send a request to retrieve the results. In the onJobComplete event handler, the Geoprocessor.getResultData method can be called to get the result. Each output parameter is a separate resource, so the Geoprocessor instance's GetResultData method must be called for each output parameter of the task. The job Id returned by the event handler and the output parameter name in the GetResultData method must be provided. Also, an event handler must be created for the onGetResultDataComplete event. The onGetResultDataComplete event is fired when the web application receives the result value of the output parameter.
  • onError: The onError event is fired if the submitJob request or status request times out or if the geoprocessing job fails. The event will return an error instance containing the HTML error code.

You can learn more about the job, job ID, jobstatus, and server-client communication in the submitJob action in Task Actions: submitJob. The following code shows how to submit a job to the server and how to handle events.

Task operation: submitJob

function myGPSubmitJob(){
    
    
 // Get params from setupParameters method described above.
 var params=setupParameters();
 // Setup event handlers.
 dojo.connect(gpTask, "onJobComplete",onTaskComplete);
 dojo.connect(gpTask, "onError",onTaskFailure);
 dojo.connect(gpTask, "onStatusUpdate",onTaskStatus);
 gpTask.submitJob(params);
}
// Event handler for onJobComplete event
function onTaskComplete(jobInfo) {
    
    
    /* Get the value of an output parameter Buffer_polygons
      using getResultData. The name of the output
      may vary in your gpTask*/      
    dojo.connect(gpTask, "onGetResultDataComplete",
                      onTaskResultComplete);
    gpTask.getResultData(jobInfo.jobId, 
                          "Buffer_polygons");
}
// Event handler for onStatusUpdate event
function onTaskStatus(jobInfo) {
    
    
     //write status to console to help debugging
    console.log(jobInfo.jobStatus);
}
// Event handler for onError event
function onTaskFailure(error) {
    
    
  // Report error 
  alert("Error:"+ error); 
}

Step 4: Render the result

Renders the results of a geoprocessing task according to the data type of the output parameter.
insert image description here

The result obtained from the onExecuteComplete event handler

In the case of an execute operation, the onExecuteComplete event will return the result and message of the geoprocessing task. The resulting instance is an array of all output parameters for the task, with entries in the array always in the order they are listed on the Task page. Therefore, individual parameter values ​​can be identified by their position in the array. Each output parameter in the array has a parameter name, data type, and value. The following code shows how to access the first output parameter in the result. In the code below, the output parameter is called the GPFeatureRecordSetLayer output, so the code shows how to render the parameter as a graphics layer and add it to the web application.

Render the result in the onExecuteComplete event handler

function onTaskSuccess(results, messages) {
    
    
    /* Retrieve the output parameter value based 
      on its position from the result instance.
      In the case shown below, the output is the first output 
      parameter of the task and it
      is a GPFeatureRecordSetLayer.*/
    var featureset = results[0].value;
   
    // Create a graphics layer with features
    var taskResultLayer= new esri.layers.GraphicsLayer
              ({
    
    id:"MyGPExecuteResultLayer"});
    
    // Create a symbol based on the geometry. 
    // The geometry is assumed to be polygons in the code below
    var simplePolySymbol = new esri.symbol.SimpleFillSymbol();
    simplePolySymbol.setOutline(new esri.symbol.SimpleLineSymbol(
                  esri.symbol.SimpleLineSymbol.STYLE_SOLID,
                  new dojo.Color([0,0,0,0.5]), 1));
    simplePolySymbol.setColor(new dojo.Color([255,0,0,0.7]));
    
    // Create graphics from features and add it graphicslayer 
    dojo.forEach(featureset.features,function(feature){
    
    
             feature.setSymbol(simplePolySymbol);
             //Add feature to the graphics layer
             taskResultLayer.add(feature);});
    }
    // Add graphicslayer to webmap 
    //  myMap is assumed to be an instance of map container esri.map
    myMap.addLayer(taskResultLayer)
}

The result obtained from the onGetResultDataComplete event handler

The onGetResultDataComplete event provides the result instance. Unlike results in the onExecuteComplete event, this result instance only has request parameter values. The parameter result will contain the name, data type and value of the request parameter. The parameter value is retrieved from the result and used as needed. The following code shows how to render the result of the GPFeatureRecordSetLayer parameter in the parameter result instance.

The result obtained from the OnGetResultDataComplete event handler

function onTaskResultComplete(paramResult) {
    
    
   // Retrieve the value of the parameter from the paramresult   var featureSet = paramResult.value;
   // Create a graphics layer with features   var taskResultLayer= new esri.layers.GraphicsLayer              ({id:"MyGPSubmitJobResultLayer"});
       // Create a symbol based on the geometry. 
   // The geometry is assumed to be polygons in the code below   var simplePolySymbol = new esri.symbol.SimpleFillSymbol();
   simplePolySymbol.setOutline(new esri.symbol.SimpleLineSymbol(                  esri.symbol.SimpleLineSymbol.STYLE_SOLID,                  new dojo.Color([0,0,0,0.5]), 1));
   simplePolySymbol.setColor(new dojo.Color([255,0,0,0.7]));
       // Create graphics from features and add it graphicslayer 
   dojo.forEach(featureset.features,function(feature){
    
    
             feature.setSymbol(simplePolySymbol);
             //Add feature to the graphics layer             taskResultLayer.add(feature);});
   }
   // Add graphicslayer to webmap    //   myMap is assumed to be an instance of map container esri.map.
   myMap.addLayer(taskResultLayer) }

Guess you like

Origin blog.csdn.net/weixin_40625478/article/details/111186845
Recommended