Creating Geoprocessing Services Tutorial
Creating Geoprocessing Services Tutorial
Creating Geoprocessing Services Tutorial
Table of Contents
Guide to the geoprocessing service examples GP service step by step: Buffer points . . . . . . . . . . . . . . . . . . . . . . . 3 . . . . . . . . . . . . . . . . . . . . . . . . . . 5
GP service example: Buffer features . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 GP service step by step: Watershed . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 GP service example: Stream network . . . . . . . . . . . . . . . . . . . . . . . . . . 30
GP Service example: More Stream network . . . . . . . . . . . . . . . . . . . . . . . . 40 GP Service example: Clip and ship . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
GP service example: Drive-time polygons . . . . . . . . . . . . . . . . . . . . . . . . . 73 GP service example: Shortest route on a street network . . . . . . . . . . . . . . . . . . . 85 . . . . . . . . . . . . . . 99
Common geoprocessing service design patterns, such as the use of feature and record sets and tool layers, using layers from a source map document, and drawing results with a result map service Preprocessing data to make fast and efficient services Useful tips and tricks
Types of examples
There are two types of example topics in this book, distinguished by their titles: GP service step by step: These topics are step-by-step guides to creating a service. They assume you have cursory knowledge of geoprocessing. The idea behind these step-by-step examples is to show you how everything in the corresponding folder was created. When you complete the steps, you will have created a duplicate of the corresponding folder in the tutorial directory. You can use the corresponding folder to check your work. GP service example: These topics assume you are familiar with geoprocessing and ArcGIS Server and you do not need step-by-step instructions on how to create models and tool layers or publish services. Rather, they focus on particular aspects of the service, providing step-by-step instructions only when more advanced concepts are introduced. Note: While authoring Geoprocessing Services in ArcMap it is advised to disable background processing. Learn more about background processing
Example Buffer points (step by step) Buffer features Description A simple model to buffer point features Expands the above service to buffer line and polygon features
Watershed (step by step) Stream network More stream network Clip and ship
Creates a watershed polygon from input points Produces a stream network for cartographic display Expands the above service by allowing the user to download existing stream networks Extracts data based on area of interest polygons, creates a file geodatabase of the extracted features, compresses the geodatabase into a .zip file, and optionally e-mails the .zip file to the user Much like the above example, but makes extensive use of scripting Shows a variety of ways to select data by attribute and location Creates polygons based on drive time around points Finds the shortest route on a street network Finds features closest to a given location based on shortest route on a street network
Data on demand Selecting data Drivetime polygons Shortest route on a street network Finding nearby features over a street network
Folder Purpose Services Geoprocessing tasks Inputs Outputs Data Extensions Of note
BufferPoints
Creates polygons around points.
Corresponding folder
Data can be found at C:\arcgis\ArcTutor\GP Service Examples\BufferPoints. After completing all the steps described below, you will have duplicated the contents of this folder.
In the Catalog tree, right-click BufferPts and click New > Folder. Name the folder ToolData. In the Catalog tree, right-click ToolData and click New > File Geodatabase. Name the file geodatabase Schema. Using the same steps, create a folder within BufferPts named Scratch. Within the Scratch folder, create a new file geodatabase named Scratch.
b. c.
On the Add Data or Tool dialog box, navigate to Toolboxes > System Toolboxes > Analysis Tools > Proximity. Click Buffer and click Add. (An alternative to this method is to drag the Buffer tool from the ArcToolbox, Search, or Catalog window onto the ModelBuilder canvas.) The ModelBuilder canvas now appears as follows:
3.
When using ModelBuilder, you often need to move and resize elements (tools and variables). In the illustration above, the output variable is actually named Output Feature Class but is truncated because of the size of the variable. To resize, click the output variable and click and drag one of the small blue selection squares. Now your model looks as follows:
4.
Right-click Buffer, point to Make Variable > From Parameter, then click Input Features.
illustrated below:
5.
Right-click Input Features and click Properties. On the Input Features Properties dialog box, click the Data Type tab.
6.
In the Select data type drop-down list, choose Feature Set. On the Import schema and symbology from box, enter the path or browse to the point feature class Points you created
7. 8. 9.
Click OK. The Input Features variable is now a blue color. Right-click Buffer, point to Make Variable > From Parameter, then click Distance [value or field]. A new model variable is created. You may need to click and drag the variable so that it is not on top of the Input Features variable and resize it to show the complete variable name.
Right-click the Distance [value or field] variable and click Rename. Rename the variable to Distance. Right-click Distance and click Properties. On the Distance Properties dialog box, click the Data Type tab. In the Select data type drop-down list, choose Linear Unit. Click OK. Double-click Distance (or right-click and click Open). Set the distance to 1000 meters. The Distance variable is now a blue color, and the Output Feature Class variable is a green color. This signifies that all required inputs to Buffer have been provided. Right-click the Output Feature Class variable (the output of Buffer) and click Rename. Rename the variable to Output Polygons. Double-click Output Polygons and enter %scratchworkspace%\BufferedPoints.shp
15. 16.
Click OK Right-click Input Features and click Model Parameter. P (for parameter) appears next to the variable. Right-click Distance and click Model Parameter. P appears next to the variable. Right-click Output Polygons and click Model Parameter. P appears next to the variable. The model should now appear similar to the illustration below:
21.
In the main ModelBuilder menu, click Model and click Model Properties a. Set Name to BufferPoints b. c. Set Label to Buffer Points Check the Store Relative pathnames option.
22. 23.
Click OK. In the main ModelBuilder menu, click Model and click Save. Then click Model again and click Close
3.
Configure the following: Geoprocessing Options: Check the Overwrite the outputs of geoprocessing operations check box. Geoprocessing Options: Check the Add results of geoprocessing operations to the display check box. Environments Settings: Expand the Workspace category and set the scratch workspace to BufferPoints\Scratch, the folder you created above.
4.
In the Catalog window of ArcMap, navigate to your toolshare folder and choose the BufferService toolbox you created above.
10
5.
Double-click Buffer Points. (Optionally, you can right-click Buffer Points and click Open). This opens the Buffer Points tool dialog box, as illustrated below.
6. 7. 8.
Click Add Feature to add a point feature to buffer. You can add more than one feature. Learn more about using the feature set control to add features Optionally, change the Distance parameter. Click OK. The tool begins to execute. When the tool finishes execution, a new layer named BufferedPoints is added to the ArcMap table of contents. Exit ArcMap. You do not need to save your changes.
9.
11
Once you have established an administrator connection to ArcGIS Server, you are ready to publish your toolbox. Steps: 1. 2. 3. 4. In ArcCatalog , right-click the BufferService toolbox and click Publish to ArcGIS Server. On the Publish to ArcGIS Server dialog box, choose the server you want to publish to. Name the service BufferService (this is the default namethe same as the name of the toolbox). Click Next. Click Finish.
12
on the server (defined by %scratchworkspace%), and there is no need for you to specify an
output location.
5. 6. 7.
Click Add Feature ( ) to add a point feature to buffer. You can add more than one feature. Learn more about using the feature set control to add features Optionally, change the Distance parameter. Be sure to turn backgroud process off to allow process dialog box appears by running following steps: a. Click Geoprocessing from ArcMap. b. c. SelectGeoprocessing Options If the Enable check box of Background Processing is checked, uncheck it. Otherwise leave the way it is.
Learn more about foreground and background processing 8. 9. Click OK. Click Geoprocessing menu > Results, expand Current Session, then expand the BufferPoints entry. Note how you can view outputs, inputs, environments, and messages for the execution of the task. Anytime you execute a geoprocessing tool, a result is written to the Results window. Learn more about using results It should only take a few moments for the task to complete. A new layer is added to the ArcMap table of contents. This layer is named Output Polygons [<time>_<date>], as illustrated
below.
13
In the next series of steps, you will be modifying the BufferService properties and running the Buffer Points task again to see the effect of changing these properties. Therefore, you do not want to exit ArcMap.
There are three basic parameters that you can modify that affect how the task executes. Change these parameters as discussed below, click OK, then start the service (right-click BufferService and click Start). Then run the task again in ArcMap to see the effect.
Execution type
Synchronous means that the client waits until the server has finished executing the task. Asynchronous means that the client is free to do other work while the server executes the task. You should choose synchronous only for tasks that execute quickly. BufferService has one task, Buffer Points, and this task executes quickly. Change the execution type to synchronous, restart the service, then execute Buffer Points again. With synchronous execution, the progress dialog box remains open until the task is finished executing.
14
Show Messages
Geoprocessing models write messages during the execution of model processes. These messages include warnings, errors, and other information. The messages can contain paths to data residing on your server or local area network, and you may not want the paths to this data to be viewed by users. By default, messages are not shown. Check the checkbox next to Show Messages, restart the service, then execute Buffer Points again. You should see more messages in both the progress dialog box (if the service is running synchronously) and in the result. When you are developing and testing services, you almost always want to show messages.
15
Folder Purpose Services Geoprocessing tasks Inputs Outputs Data Extensions Of note
BufferFeatures
Create polygons around point, line, or polygon features.
Corresponding folder
C:\arcgis\ArcTutor\GP Service Examples\BufferFeatures contains the completed models and data.
Data
Similar to the BufferPoints service, you need to create schema feature classes for use in the three models. For this service, you need three schema feature classes: one containing point features, one containing line features, and another containing polygon features. Create these feature classes in the Schema geodatabase inside the ToolData folder.
Models
There is one model for each of the feature types. These models are constructed using the same basic steps as described in GP service step by step: Buffer points. The main difference between the models is that they use different schemas for the input variable to Buffer. Buffer Lines modelThe Input Lines variable uses line schema. Buffer Points modelThe Input Points variable uses point schema. Buffer Polygons modelThe Input Polygons variable uses polygon schema.
The Buffer Lines model has one additional parameter, the end type of the line, which is either ROUND or FLAT, as described in the Buffer tool reference. This variable was created as follows: In the Buffer Lines model, right-click Buffer and click Make Variable > From Parameter > End Type.
16
It is not required that you make a variable for the End Type parameter. End Type will default to ROUND if you do not create a variable.
Publishing
The BufferFeatures toolbox is published using similar steps as described in GP service step by step: Buffer points.
17
Watershed
Using the Spatial Analyst extension, this basic service computes a watershed polygon.
Corresponding folder
C:\arcgis\ArcTutor\GP Service Examples\Watershed contains the completed model and data. After completing all the steps described below, you will have duplicated the contents of this folder.
3.
18
Data processing
For this service, you'll need to create four new raster datasets, as shown below.
Dem_fill is the result of executing the Fill tool using elevation as input. Hillshade is the result of executing the Hillshade tool using dem_fill as input. Flowdir is the result of executing the Flow Direction tool using dem_fill as input. Accumulation is the result of executing the Flow Accumulation tool using flowdir as input.
The model in this example uses a feature set, and you will need a point feature class to use as the feature set schema. In Stowe.gdb, create a new point feature class named PourPoint. For a coordinate system, import any of the existing datasets within the ToolData folder. Use the default values for xy tolerance and configuration keyword.
19
Basemap
The basemap contains three layers: Landuse (landuse raster), Hillshade (hillshade raster), and Roads (Stowe.gdb/roads feature class). You will need to create a map document containing these layers. Name the ArcMap document StoweBasemap.mxd.
The Hillshade layer is drawn with a transparency of 55 percent. To change transparency, right-click the Hillshade layer, choose Properties, click the Display tab, then change the transparency. After creating and saving StoweBasemap.mxd, publish it as a map service to your server. Steps: 1. 2. 3. 4. 5. 6. In the Catalog window, right-click StoweBasemap.mxd and click Publish to ArcGIS Server. In the first panel, name the service StoweBasemap (the default). Click Next. The only capability that you need is mappingall other capabilities are optional for this service. Click Next. Click Finish.
You can test the StoweBasemap service by starting ArcMap with a blank document, then add the service by clicking Add Data , navigating to the server, and choosing StoweBasemap.
20
3.
The Flow Direction and Flow Accumulation layers will be used in the published task but never displayed to the user. Therefore, the symbology of these layers does not matter.
Set the geoprocessing scratch workspace environment to the Scratch folder, as follows: Steps: 1. 2. 3. 4. 5. In ArcMap, click Geoprocessing > Environments. Expand the Workspace Settings category. Enter the path to the scratch workspace you created above (for example, E:\Watershed\Scratch) Accept the change by clicking OK. Save the map as StoweHydro,mxd.
21
Steps to building the model Steps: 1. 2. In the Catalog window, right-click the StoweHydro toolbox and choose New > Model. This opens ModelBuilder with a new empty model. Create a variable with the Feature Set data type, as follows: a. Right-click in the ModelBuilder canvas and click Create Variable. b. 3. 4. 5. 6. 7. 8. 9. Choose Feature Set as the data type.
Click OK. Rename the variable as Pour Point. Right-click Pour Point and click Properties. Click the Data Type tab. Set the schema to the Pour Point layer by choosing it in the drop-down list. Right-click Pour Point and click Model Parameter. A check mark appears next to Model Parameter, and a P appears next to the Pour Point variable. Add the Snap Pour Point tool to the model by dragging the tool from the ArcToolbox, Catalog, or Search window. Right-click Snap Pour Point and make a variable from the Snap Distance parameter. Double-click Snap Distance and set the snap distance to 250 meters. It is not a requirement that you make Snap Distance a model variable, but doing so gives anyone that views the model a visual clue that snap distance is an important variable. Double-click Snap Pour Point and set the input raster parameter to Pour Point. Set the Pour point field parameter to ObjectID if not already set. Set the Input accumulation raster parameter to the Flow Accumulation layer.
10.
22
11.
Right-click Snap Pour Point and click Make Variable > From Environment > Processing Extent > Extent, as illustrated below.
12. 13.
Double-click the Extent variable and set it to Union of Inputs. Rename the output of Snap Pour Point as Pour Point Raster. This is intermediate output and should be deleted after the model executes. Right-click Pour Point Raster and check Managed. Add the Raster To Point tool to the model. Double-click Raster To Point and set the Input raster parameter to Pour Point Raster. Set the Output point features parameter to %scratchworkspace%\snapped_pour.shp.
14.
23
Rename the Raster To Point output variable atos Output snapped pour point. Right-click Output snapped pour point and make it a Model Parameter. Add the Watershed tool to the model and use the Flow Direction layer for the Input flow direction raster parameter. Rename the output of the Watershed tool as Watershed raster. Watershed raster is intermediate output. Right-click Watershed raster and click Managed. Add the Raster To Polygon tool to the model. Set the Input raster parameter to Watershed raster. Set the Output Polygon features parameter to %scratchworkspace%\Watershed.shp. Rename the output variable of the Raster To Polygon tool as Output Watershed. Right-click Output Watershed and make it a Model Parameter. In the main ModelBuilder menu, click Model > Model Properties. a. Set Name to CreateWatershedPolygon. b. c. Set Label to Create Watershed Polygon. Check Store Relative pathnames.
18. 19.
23.
24
(The order of the parameters in your tool dialog box may be different, depending on the order in which you made variables model parameters. You can change the order of parameters in the model tool's properties.). 2. Click Add Feature ( ) to add a pour point. The location you use for the pour point should be in a valley, not on a mountaintop where there is no watershed. The following illustration shows a result of executing Create Watershed Polygon:
In the above illustration, note that the output watershed polygon is blue and the snapped pour point is a small dot. (Your symbology may be different.) In the following steps, you will create better symbology,
25
save this symbology as a layer file (.lyr), then use these layer files to define the symbology of your output variables. Steps: 1. 2. 3. 4. 5. 6. Open the properties for the snapped_pour layer and set the symbol to a red cross. Open the properties for the Watershed layer and set the fill symbol to a light blue. Right-click snapped_pour, click Save As Layer File, then save as Stowe\ToolData\snapped_pour.lyr. Right-click Watershed, click Save As Layer File, then save as Stowe\Tooldata\Watershed.lyr. Edit the Create Watershed Polygon model. Right-click the Output snapped pour point variable and click Properties. On the Properties dialog box, click the Layer Symbology tab and set the symbology layer to snapped_pour.lyr.
7. 8. 9.
Do the same for the Output Watershed variable, setting the symbology layer to watershed.lyr. Save and close the model. Remove the existing snapped_pour and Watershed layers from the table of contents.
26
3.
Right-click the tool layer and click Open. The tool dialog box opens. Add a pour point using the feature set control and run the tool. After the tool runs, the two sublayers in the ArcMap table of contents are refreshed and have the symbology as defined in the symbology layers you created above. Finally, remove the PourPoint layer since it is no longer needed. You should first save the layer to a layer file for subsequent reuse. Save the map as StoweHydro.mxd and exit ArcMap.
4. 5.
27
4.
Click Next. From this point on, you can accept the default values provided by the wizard.
below:
28
5.
Examine the results of the task in the Results window, as illustrated below:
29
StreamNet
Creates a stream network from flow and accumulation data.
StoweHillshade (map service) StoweStreamNet (geoprocessing service and result map service)
Corresponding folder
C:\arcgis\ArcTutor\GP Service Examples\StreamNet contains the completed model and data.
30
The task creates a stream network defined by a minimum areathe smaller the area, the more stream segments are produced. Each stream segment is assigned a stream order value based on the number of upstream stream segments, and this value is used to determine the line thickness to display each stream segment. The number of stream segments produced depends on the minimum area used. Using an input of 1 hectare, approximately 32,000 stream segments are produced. For 45 hectares, approximately 600 stream segments are produced. One of the decisions that you make when creating a geoprocessing service is determining the maximum number of records and features that can be returned from the server to the client. The default is 1,000, and you can increase this to billions. However, transporting large numbers of features across the Web is expensive and slow. Whenever you have a service that may output a large number of features, you should consider using a result map service to create a map of the result and let ArcGIS Server transport the map across the Web instead of the features. Because the number of stream segments produced by the Create Stream Network task is dependent on the minimum drainage area and, if you substitute your own data, the size and topography of the study area, this example uses a result map service to draw the results instead of transporting the features across the Web to the client.
31
Data Data
The data for this example comes from C:\arcgis\ArcTutor\GP Service Examples\Watershed. This data, in turn, was derived from C:\arcgis\ArcTutor\Spatial Analyst. To learn how the data in the Watershed folder was created, see the Watershed example.
Basemap
The basemap for this example, StoweHillshade.mxd, has only one layer, Hillshade, as illustrated below. The Hillshade layer is drawn with a transparency of 55 percent.
32
Project data
The Flow Accumulation and Flow Direction variables are layers from the source map document, StoweStreamNet.mxd. These variables are termed project data because they are nonparameter input data.
33
The Calculate Value tool divides the input hectares by the size of a cell in hectares (30 x 30 meters = 900 square meters = 0.09 hectares) to yield the number of cells for the minimum upstream area. The parameters for the Calculate Value tool, illustrated below, make use of variable substitution. By placing percent signs (%) around a variable name, the contents of the variable are substituted for the value.
The Minimum upstream area in hectares variable is a double data type, created as follows: 1. 2. 3. 4. 5. Right-click on the ModelBuilder canvas and click Create Variable. On the Create Variable dialog box, choose Double as the data type. Click OK. Rename the newly created variable to Minimum upstream area in hectares. Double-click the variable and enter a default value. For the Stowe area, 45 is a reasonable default.
The Minimum upstream area in hectares variable is a precondition to the execution of Calculate Value. A precondition means that a variable must contain a value before Calculate Value executes. You can set preconditions as follows: 1. 2. Right-click Calculate Value. Click Properties.
34
3. 4.
Con process
The Con tool performs a conditional if-else evaluation on each of the input cells in the Flow Accumulation raster.
Note that the expression makes use of variable substitution. In the expression, all cells with a value greater than the minimum number of cells are selected. (The value of a cell in the Flow Accumulation raster is the number of cells flowing into an individual cell.) The Input true raster or constant value parameter is the value to assign each selected cell and is set to 1. If you are creating this model from scratch, do the following: 1. 2. 3. Double-click the Con tool. For the Input true raster or constant value parameter, enter 1. Click OK.
The Input true raster or constant value model variable is automatically created and connected to the Con tool.
35
The output raster contains the Shreve stream order value for every cell that represents a stream.
Note that the output is written to %scratchworkspace%. This location is the scratch workspace environment that is set and used by ArcGIS Server.
Tool layer
The tool layer in StoweStreamNet.mxd defines the result map symbology. The steps below show how to create the tool layer and appropriate symbology: 1. 2. 3. 4. In ArcMap, drag the Create Stream Network tool from the StoweStreamNet toolbox into the ArcMap table of contents to create the Create Stream Network tool layer. Right-click the Create Stream Network tool layer and click Open to open the tool dialog box. Use 45 (the default) as the minimum area. Click OK to run the tool. Note that the default symbology for the stream network is a single line.
In the steps below, you will change the symbology to graduated line symbols. Right-click the Stream Network sublayer and click Properties, then click the Symbology tab. 1. Click Graduated symbols found beneath the Quantities category.
36
2. 3.
1. 2.
On the Classification dialog box, choose Manual as the classification method. You will set up a manual classification with breaks of 100, 250, 500, 750, and 10000. In the Break Values panel, click the last value in the list. This allows you to edit the value. Enter one of the break values, such as 10000. The list refreshes so that the values are sorted.
setting the break values until the list appears as illustrated below.
3.
Click OK.
37
The Symbology tab now looks as illustrated below. You may need to reset the color to blue by clicking Template and choosing a suitable blue color.
4.
Click OK.
The legend for the Stream Network sublayer displays GRID_CODE as the classification field, which will not make much sense to the user of your service. To change it, click GRID_CODE in the legend, press the F2 key, and change the text to something more descriptive, such as Shreve Order or Stream Order.
Publishing
StoweHillshade.mxd is published as a map service. To publish StoweStreamNet.mxd as a geoprocessing service with a result map service, do the following: 1. 2. In the Catalog window, right-click StoweStreamNet.mxd and click Publish to ArcGIS Server. Accept all defaults.
38
Using
To use the services, start ArcMap and add the StoweHillshade map service and the StoweStreamNet geoprocessing service. Do not add the StoweStreamNet map service since this is a result map service and contains the Flow Accumulation and Flow Direction layers, which have nothing to do with results.
39
Folder Purpose Services Geoprocessing tasks Inputs Outputs Data Extensions Of note
StreamNet2
User can download a precomputed network or create their own.
Precomputed Stream Network task, the user inputs a layer name. For Create Stream Network, the user enters the minimum upstream area in hectares.
Stream network This example uses digital elevation data (raster) and other data found in the Spatial Analyst tutorial. Spatial Analyst. Uses layer symbology files (.lyr) to instruct the client application on how to draw the output stream networks, as described in the GP Watershed service example.
Corresponding Folder
C:\arcgis\ArcTutor\GP Service Examples\StreamNet2 contains the completed model and data.
40
The basemap service allows you to view five precomputed networks, ranging from 10 to 50 hectares. There are two geoprocessing services: Get Precomputed Stream NetworkThe user chooses a precomputed stream network, and the features are transported back. Create Stream NetworkThe user creates a new network by entering an upstream drainage area. This is a slightly modified version of the Create Stream Network task discussed in the GP Service example: Stream network.
Basemap
The table of contents of StoweStreamNetworksBasemap.mxd is shown below, along with the StoweStreamNetworkTasks toolbox as shown in the Catalog view.
41
The five stream network layers were created using the Precompute a Stream Network model. This is a utility tool and is not part of the geoprocessing service. Precompute a Stream Network is similar to the Create Stream Network with the following differences: The input variable is named Area. The accumulation and flowdir raster dataset variables refer to raster datasets in the ToolData folder rather than layers in the ArcMap table of contents. This allows you to execute the model without having the raster layers in the ArcMap table of contents. The Stream Network variable has a Layer Symbology file. The basic steps for creating and using a layer symbology file are Run the Precompute a Stream Network model from the Catalog window. A new layer is added to ArcMap. Right-click the new layer, choose Properties, then click the Symbology tab. Change the symbology to Graduated Symbols using GRID_CODE as the value. Use a Natural Breaks (Jenks) classification. Right-click the layer in the table of contents and click Save As Layer File. Save to ToolData/Stream Network.lyr Edit the Precompute a Stream Network model. Right-click the Stream Network output variable and click Properties. In the Properties dialog box, click the Layer Symbology tab and enter the layer file created above.
42
Models
The contents of StoweStreamNetworkTasks.mxd are illustrated below.
The table of contents has the same precomputed stream network layers as found in StoweStreamNetworksBasemap.mxd. These layers were created as follows: 1. 2. Each stream network layer in StoweStreamNetworksBasemap.mxd was saved as a layer file to the ToolData directory. Using Add Data in StoweStreamNetworkTasks.mxd, each layer file created above was added to the table of contents.
The Get Precomputed Stream Network model is a simple model that copies the contents of a feature layer to the scratch workspace.
43
The input variable, Network to download, is a Feature Layer data type. When the task executes, all featurebased layers are listed, and the user picks one. (Note that the raster layers are not listed since they are not features. Nor are any of the sublayers in the tool layers listed, because ArcGIS Server automatically filters out any tool layers and their sublayers from the list of feature layers.) The underlying features are then copied to the scratch workspace and, when transported back to the client, drawn using the symbology defined in ToolData/Stream Network.lyr. The Create Stream Network task is the same as found in GP Service example: Stream network with one notable exception: the output variable, Stream Network, has its Layer Symbology property set to Stream Network.lyr, as shown below.
Publishing
StoweStreamNetworksBasemap.mxd is published as a map service. StoweStreamNetworkTasks.mxd is published as a geoprocessing service: 1. 2. 3. In the Catalog window, navigate to your GIS Server, right-click, then choose Add New Service. Name the service StoweStreamNetworkTasks and choose Geoprocessing Service as the type. Click Next. Choose StoweStreamNetworkTasks.mxd as the source for your service. Change the Maximum Number of Record Returned by Server to 10000. You need to change this because there is no result map service to draw the results, and the features are transported back to the client. If you leave the number of records to the default 1000, none of the tasks return the full dataset, since they all generate more than 1,000 records. 4. For testing purposes, check Show Messages.
Click Next. From this point on, you can accept the default values provided by the wizard.
44
Using
To use the service, start ArcMap with a blank document and add the StoweStreamNetworksBasemap map service and the StoweStreamNetworkTasks geoprocessing service. Open and execute both tasks. If you do not get results from either of the tasks, it is probably because the Maximum Number of Record Returned by Server parameter was not set to a large number as described above.
2. 3. 4.
After making this change to the Create Stream Network model, the service must be restarted for the change to take effect. With these changes, anytime a value less than 5 is entered, the task will display an error in its messages. The service must have Show Messages checked for the user to see the message.
45
Folder Purpose Services Geoprocessing tasks Inputs Outputs Data Extensions Of note
ClipAndShip
Using a polygon digitized by the user, this service clips layers from the study area into a file geodatabase, then creates a .zip file that can be downloaded by the user.
Corresponding Folder
C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip contains the completed models and data.
Data
The study area for this example is a small area in the city of Portland, Oregon. Data includes places, transportation networks, hydrologic features, land records, and a hillshade raster of the study area. The data can be found in C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip\ToolData\Portland.gdb.
Publishing
Steps: You need to have an administrative connection to an ArcGIS server to publish services. To create an administrative connection, in the Catalog window, go to GIS Servers > Add ArcGIS Server and check Manage GIS Services. On the General panel, enter the Server URL and
46
Host Name, then click Finish. A server administrative connection with the host name will appear under GIS Servers. 1. 2. 3. 4. 5. 6. 7. From the Catalog window, navigate to C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip. Right-click Portland.mxd and select Publish to ArcGIS Server. In the first window, keep all defaults and click Next. in the next panel, deselect all check boxes except Mapping (always enabled). Click Next. Click Finish. The map service Portland will be published to the ArcGIS Server. You will use it as a basemap later. Open C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip\Portland.mxd in ArcMap. In the Catalog window, a. Expand Toolboxes > System Toolboxes > Server Tools.tbx > Data Extraction > Extract Data Task. b. Drag the Extract Data Task tool to the ArcMap table of contents.
The tool layer Extract Data Task appears in the table of contents. 8. 9. 10. 11. Save the map document containing the tool layer as ClipAndShip.mxd. In the Catalog window, right-click the connection to your ArcGIS Server and select Add New Service. In the Add GIS Service panel, type ClipAndShip as the service name and select Geoprocessing Service as the Type. Click Next. In the next panel, check A Map as your source file. Enter the path to the ClipAndShip.mxd map document that you created above and click Next.
47
12.
For any remaining panels, leave the default value and click Next until the last panel, where you click Finish. You should see the service ClipAndShip under your ArcGIS Server connection.
Using
The following steps show how to use the map and geoprocessing services that you previously published. Steps: 1. 2. Open a new ArcMap document. In the Catalog window, a. Navigate to your server connection under GIS Servers, select the map service Portland, and drag it into the ArcMap table of contents. b. 3. 4. 5. Expand the Portland map service in the table of contents, and you will see all the layers belonging to the Portland map service.
In the Catalog window, navigate to your server connection under GIS Servers, find the geoprocessing service ClipAndShip, and expand it. The task Extract Data Task appears. Double-click the task Extract Data Task to open the task dialog box. At the top of the task panel is a list of Layers to Clip. Note that the layer names in the check box are the same as the layers of the Portland map service in the table of contents. Check the box next to each layer that you want to be included in your download.
48
6.
The next parameter of the Extract Data Task is the Area of Interest. This parameter is used to digitize an area of interest that will be used to clip each of the Layers to Clip. Click Add Feature, then digitize a polygon as an area of interest. Other input parameters, Feature Format and Raster Format, can be modified or left as default. Click OK to run the geoprocessing task. The output is returned from the server and written to the location set in your geoprocessing scratch workspace environment.
7. 8.
When the task completes, open the Results window to view the results of the task. Double-click output.zip to open the compressed file, then extract the data to a location of your choice.
49
In the Catalog window, a. Expand Toolboxes > System Toolboxes > Server Tools.tbx > Data Extraction > Extract Data Task.
50
b. c. d. 3.
Select the Extract Data Task, right-click the model, then select Copy. Go to ExtractPortland.tbx that is created in step 1b, right-click and select Paste. The model Extract Data Task is copied to the toolbox. Right-click the model, select Rename, then rename the model ExtractPortlandData.
Right-click the model ExtractPortlandData and select Edit to open the model in ModelBuilder. In the model, right-click the variable Spatial Reference and select Model Parameter. The letter P appears on the upper right-hand corner of the variable so it is now a model parameter.
4.
Create a new folder where all the standard and custom coordinate system projection files will be saved. a. In Windows Explorer, go to C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip. Right-click the folder and select New > Folder. b. c. d. Rename the new folder SpatialReference. Go to <ArcGISInstallDirectory>\Desktop10.0\Coordinate Systems\Projected Coordinate Systems, copy the State Plane folder. Paste it into the new SpatialReference folder.
5.
Right-click the model ExtractPortlandData and select Edit. Double-click the variable Custom Spatial Reference Folder and enter the path to the new SpatialReference folder (C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip\SpatialReference), then click OK. With the ExtractPortlandData model still open in ModelBuilder, a. Go to the Model menu > Properties > Parameters tab. The parameter Spatial Reference appears at the bottom of the parameter list. b. Reorder the parameters so the output parameter is the last parameter. Highlight the parameter Output Zip Fileand click the button to move it to the bottom of the list.
6.
51
7.
Still in the Parameters tab, a. Highlight the variable Spatial Reference, then change the Filter value to Value List. b. c. d. e. Enter the values Same As Input, NAD 1983 StatePlane Oregon South FIPS 3602 (US Feet), and WGS1984 to the value list. Click OK to close the Value List dialog box. Click OK to close the model Properties dialog box. Save the model and exit ModelBuilder.
The Feature Format parameter can also be customized by adding more data types to the list of formats. Learn more about the different data formats supported by the Data Interoperability extension. 8. 9. Save the customized model and add it as a tool layer in a new ArcMap document that contains all the layers from Portland.mxd. Refer to the instruction in the Publishing and Using sections above to publish and use the customized model as a geoprocessing service.
52
Folder Purpose Services Geoprocessing tasks Inputs Outputs Data Extensions Of note
DataOnDemand
Using a polygon digitized by the user, clips datasets in a file geodatabase, outputting shapefiles, then creates a .zip file that is e-mailed to the user.
Corresponding Folder
C:\arcgis\ArcTutor\GP Service Examples\DataOnDemand contains the tools and data.
Comparison between the Clip and Ship example and this DataOnDemand example
53
Other features of this service include An ArcMap document that views the downloaded data is included in the .zip file. The Python scripts demonstrate many useful techniques such as the following: Finding data relative to the script location Adding a toolbox and using its tools Importing a script and calling routines in the imported script Using system functions to copy the map document
The scripts and tools in the DataOnDemand folder are the same as those used by the ClipAndShip task in the ESRI_CadastralData_Portland geoprocessing service. The data used for this example, found in DataOnDemand/ToolData/Portland.gdb, is a small subset of the data used in the Portland_Portland_ESRI_LandBase_AGO map service. Note: The map and geoprocessing services found in sampleserver1 and sampleserver2 may change in the future. There is no guarantee that the services described above are always available.
Data
The data is of a small area in the city of Portland, Oregon, and is found in C:\arcgis\ArcTutor\GP Service Examples\DataOnDemand\ToolData\Portland.gdb. The ClipZipAndEmail tool uses a Feature Set variable, which in turn needs a schema to define the feature types and fields. The schema can be found in C:\arcgis\ArcTutor\GP Service Examples\DataOnDemand\ToolData\Templates.gdb. The ToolData folder also contains Mapofzip.mxd, which is included in the ZIP file and displays the clipped and shipped data.
Scripts
The DataOnDemandTools toolbox contains one script tool, ClipZipAndEmail. The source for this script tool is DataOnDemand/Scripts/zipandemail.py.
54
Before using the ClipZipAndEmail tool, you must edit the code and provide the name of your e-mail server. (You can either edit the Python source directly in an application like PythonWin or right-click the script tool and click Edit.) Your system administrator should be able to supply you with the name of your e-mail server. Some important properties and features of this script are described below: The Area to Zip parameter is a feature set and, therefore, needs to have a schema. The schema is set in the Parameters tab of the tool's properties.
In the ClipZipAndEmail script, the UtilityTools toolbox is added, and the Zip script tool from that toolbox is used. See the zipData() routine in the script. In the ClipZipAndEmail script, the emailZip() routine imports the send_mail() routine found in the sendemail.py script (found in DataOnDemand/Scripts), as follows:
from sendemail import send_mail
Publishing
PortlandDataMapService is published as a map service. The DataOnDemandTools toolbox is published as a geoprocessing service.
55
The location of the data is relative to the location of the script. Learn more about using the script location to build paths Next, change the list of datasets to clip, found in this code snippet:
ds = ["Streets" + g + "streets", \ "Water" + g + "StreamRoute", "Water" + g + "floodplain", "Water" + g + "riv_fill", \ "Transit" + g + "railroad", \ "Census" + g + "blockgrp", \ "Develop" + g + "Buildings", \ "Land" + g + "zoning", "Land" + g + "Parks", \ "Places" + g + "schools", "Places" + g + "hospital"]
Finally, you will need to provide the name of your e-mail server in the sendemail.py script. The code you need to modify is near the top of the script:
def send_mail(send_from, send_to, subject, text, f=""): assert type(send_to)==list # Provide the name of your email server below # server = "ouremailserver.somewhere.com"
56
SelectingData
Demonstrates various ways to select data by attribute query or location query.
SelectingData (geoprocessing service with a source map document) SelectingDataRMS (geoprocessing service with result map service)
Several (See the models below.) Varies by model; usually a query string or a feature set. Selected data Uses a dataset of a small area in the city of Portland, Oregon. None
57
In the first two configurations, when ArcGIS Server executes a task that outputs a layer, it reads the selected features from the layer and transports the selected features back to the client. In the third configuration, there are two servicesthe geoprocessing service and the result map service. The two services execute independently of each other. When the task executes, ArcGIS Server executes the geoprocessing task first, then executes the result map service, which draws the output of the geoprocessing service, sending the map image of the output data back to the client. Because of this execution order, the result map service needs datasets on disk produced by the geoprocessing service. This means that the output of the tasks in the geoprocessing service must be datasets, not layers. Layers, allowed in the first two configurations, do not work with the result map service configuration. In this example, you will find two toolbox/map document pairs; SelectingData (for publishing as a geoprocessing service with a source map document) and SelectingDataRMS (for publishing as a geoprocessing with a result map service). The tools in the SelectingDataRMS toolbox result in datasets on disk, while the tools in the SelectingData toolbox result in layers. In general, the tools in the SelectingDataRMS toolbox take a bit longer to execute since they must copy their data to disk. Which service you choose to publishSelectingData or SelectingDataRMSis up to you. Typically, you publish a result map service when any of the following are true: The selected set of features can be large and you do not want to transport a large number of features back to the client. You want to protect your data and only let the client see a map image of the data. You have advanced cartography that can only be drawn by ArcMap, not other client applications.
Data
The data is of a small area in the city of Portland, Oregon, and is found in C:\arcgis\ArcTutor\GP Service Examples\SelectingData\ToolData\Portland.gdb. This file geodatabase has been
58
compressed to save space using the Compress File Geodatabase Data tool. You cannot make edits to a compressed file geodatabase. If you need to make edits, use the Uncompress File Geodatabase tool. Several of the models use feature set and record set variables, which need schemas to define their feature types and fields. These schemas can be found in C:\arcgis\ArcTutor\GP Service Examples\SelectingData\ToolData\Templates.gdb.
SelectingData toolbox
59
Select Tax Lots With Value Greater Than (for result map service)
60
When you work with layer selections (as these tools do), there are a few guidelines to remember: When you create the tool layer in ArcMap (before publishing), the sublayer (the output of the model) will always be a layer named the same as the input layer, regardless of the output variable name in the model. The symbology will be the same as the input layer. When you execute the server task (after publishing), the output layer will be the name of the model variable.
61
When creating the expression on the Select Layer By Attribute tool dialog box, you use percent signs (%) around the variable name. Although it is not required, it is good practice to make the variable a precondition to the process that substitutes the variable. To make a precondition, follow these steps: Steps: 1. 2. 3. In ModelBuilder, right-click a tool and click Properties. Click the Preconditions tab. Choose the variable or variables that are a precondition to tool execution.
62
Selection method
Both the Select Layer By Attribute tool and the Select Layer By Location tool have several options for selection. For example, instead of creating a new selection, you can add or remove features from the current selection. The Select Layer By Location tool lets you establish a spatial relationship, such as CONTAINS, WITHIN, and INTERSECT. The example models make use of just a few of the options. Consult the Select Layer By Location tool documentation for more information.
You can also use the Select tool to create a dataset of selected features from a datasetno layer is required.
The Select Tool performs attribute selection. If you need to perform spatial selection, consider using one or more of the following tools: The Make Feature Layer tool Tools from the Analysis toolbox, such as Clip or Spatial Join
63
SelectionUtilities
This toolbox contains several utility tools to support the tasks.
Tool Check Match Results Get 1 Field Value Get 2 Field Values Get 3 Field Values Overlay Tax Lots And Neighborhoods Print Tax Lot Mailing Labels Description Checks the output of the Geocode Addresses tool and outputs an error if addresses do not match. Reads a field value from the first record of a table and outputs it to a geoprocessing model variable. Same as above, but reads two fields and outputs two variables. Same as above, but reads three fields and outputs three variables. Creates the dataset used by the Select Tax Lots By Neighborhood (optimized) model above. Given a selected set of tax lots, prints a file of mailing labels.
Utility tools
Notes on the models Select Tax Lots With Value Greater Than
This is the simplest of the models. It selects all tax lots whose total value is greater than the input value. As noted above, it uses variable substitution to build the select expression.
64
The output of Summary Statistics is written to an in-memory table rather than a table on disk. Writing tables and feature classes to memory is fast compared to writing to disk.
65
Description An address locator for the TaxLots feature class. This locator uses the U.S. Single Address style. Learn more about address locators This is a record set variable. The template is ToolData/templates.gdb/Address. For some sample addresses in the study area, see ToolData/sample addresses.txt. Takes a table containing addresses and outputs a point feature class of the address location. A status field is also output. This field will contain an M if the address was found. A custom script tool found in the SelectionUtilities toolbox included with this example. It checks that the address was successfully match. Output of Check Match Results. True if there was one address input and the address matched. A custom script tool found in the SelectionUtilities toolbox included with this example. It retrieves the unique object ID of the tax lot matching the address. Selects the tax lot with the object ID output by Get 1 Field Value.
Geocode Addresses Check Match Results Success Get 1 Field Value Select Layer By Attribute
Model elements
66
Select Neighborhood
This model selects a polygon from the Neighborhood layer.
Select Neighborhood
This model lets you pick a neighborhood from a list of neighborhoods. The Neighborhood Name variable is a string variable that has a Value List filter containing all neighborhood names. To create or change a filter, open the model properties dialog box and click the Parameters tab, shown below.
67
The main feature of this model is how it allows you to first choose a layer. The Layer to Select variable is a string variable that has a Value List filter containing Tax Lots and Neighborhoods. To view the filter, open the Model Properties dialog box and click the Parameters tab, as illustrated below.
The Calculate Value tool takes the string and turns it into a feature layer variable, as illustrated below. This technique of turning a string into another data type is discussed in Input and output data types. The output of Calculate Value is input to Select Layer By Attribute.
Finally, the selected features are copied to a feature class using the Copy Features tool. This final step is not required. (Copying the features helps to avoid confusion when creating and testing the tool layer.) The features are written to memory rather than to disk (writing features to memory is faster than writing to disk). In the SelectingDataRMS toolbox, the selected features have to be written to disk for the result map service to draw them.
68
Mailing List
This model shows how to select nearby features based on a selected feature, as well as generating a simple text containing the addresses of the nearby features.
Mailing List
Description This is a record set variable. The template is ToolData/templates.gdb/ Address. For some sample addresses in the study area, see ToolData/sample addresses.txt. This is the model described above.
Select Tax Lot By Address (attribute method) Selected Lot Search Distance Input Layer Select Layer By Location Tax Lots Print Tax Lot Mailing Labels MailingList.txt Success
The selected tax lot. This is the Tax Lot layer. Search distance to use. The Tax Lot layer. Selects all tax lots within the distance specified, using Selected Lot as the center of the search. Tax lots within the search distance. A custom script tool found in the SelectionUtilities toolbox. A text file containing mailing addresses. True if every record has a mailing address. False if one or more of the records has an empty or corrupted mailing address.
Model elements
69
70
Once TaxLotsOverNeighborhoods is created, all that is necessary is a simple attribute query to select all tax lots within a neighborhood.
Publishing
Publish Portland.mxd found in the publishing section of GP service example: Clip and ship as a map service. You will use this map service as a basemap for the services in this example. (The corresponding folder for this service is C:\arcgis\ArcTutor\GP Service Examples\ClipAndShip.) Publish SelectingData.mxd as a geoprocessing service based on a source map document. Because features are sent back to the client, be sure to increase the maximum number of records that can be returned by the service to 11,000 (slightly more than the number of features in the Tax Lot layer). Learn more about publishing geoprocessing services with a source map document Publish SelectingDataRMS as a geoprocessing service with a result map service. Learn more about publishing geoprocessing services with result map services
Using
To use the services, open a new ArcMap session and add the Portland map service as a basemap. Open the Catalog window and go to the ArcGIS Server user connection where you can see and execute all the tasks you published. Expand SelectingDataRMS service and execute the Mailing List task.
71
Open the Results window and perform the following steps: Steps: 1. 2. 3. 4. 5. Expand the MailingList result. Right-click the Mailing List task result and choose Get Data. The task result changes from <Data on Server> to MailingList.txt. Right-click MailingList.txt and click Copy Location. (Since the result is a text file, Add to Display has no effect.) Open your Internet browser and paste the location into the address bar. The contents of MailingList.txt appear. Optionally, you can click the Copy tool and drag MailingList.txt from the Results window onto the input parameter of the Copy tool dialog box. The file is copied to a location of your choice.
72
DriveTimePolygons
Creates drive-time polygons around input points for the given drive-time values
Corresponding folder
C:\arcgis\ArcTutor\GP Service Examples\DriveTimePolygons contains the completed model and data.
73
Data
The data for this example comes from C:\arcgis\ArcTutor\GP Service Examples\DriveTimePolygons.
74
Network dataset
The ToolData folder contains a file geodatabase, SanFrancisco.gdb. This geodatabase contains a network dataset, Streets_ND, within the Transportation feature dataset. This network dataset models the street network for the San Francisco area. It provides a network attribute, TravelTime (among others), which indicates the time taken to travel each street segment in minutes.
Basemap
The basemap layer within SanFranciscoBasemap.mxd has a layer, Streets, as illustrated below. This layer shows the extent of the network dataset. This means that this task can be used to determine drivetime polygons only in this extent.
75
Model
76
Model overview
The Calculate Drive Time Polygons model is illustrated below. There are two input variables: Input Facilities are the centers of the drive-time polygons to be generated. (In network analysis, a facility is any fixed location on the network, such as a building or your current location.) Drive Time Values is a space-separated list of drive-time values in minutes.
The model creates a service area network analysis layer, adds the user-digitized points as facilities, and performs a solve to determine the drive-time polygons.
Element Streets_ND Drive Time Values Make Service Area Layer Service Area Type Network dataset layer String, input parameter Tool Description The network dataset layer. Space-separated list of drive-time values in minutes. Creates a service area network analysis layer. This layer contains both data and properties that determine how service areas will be calculated, along with the results of the calculation. Service area layer.
Network analysis layer Feature set (points), input parameter Tool Network analysis layer Tool Network analysis layer Boolean Tool Feature layer, output parameter
Input Facilities
Adds the input points as facilities to the service area layer. Service area layer with facilities.
Calculates the drive-time polygons. Service area layer containing the calculated drive-time polygons.
The derived output from the Solve tool that indicates if the solve was successful. Selects the polygons sublayer from the service area layer. The polygons layer from the Service Area (3) network analysis layer.
Model elements
77
78
79
Model processes
The Make Service Area Layer tool creates a new Network Analyst (NA) layer, ServiceArea, that stores the analysis properties, references the Streets_ND network dataset layer used for the analysis, and stores the input facilities and the output polygons. The network dataset has a network cost attribute called TravelTime that specifies the travel time required to traverse each street segment. This attribute is used as an impedance attribute. The default break values are read from the Drive Time Values variable as a space-separated list of values.
For this service, the NO_MERGE option was used to create overlapping polygons that do not merge for each facility. The RINGS option is used so that for each drive-time value, the polygons are drawn as rings. This results in polygons that encompass the area from the previous break up to the cutoff value for the break and do not include the area of the smaller breaks. The Add Locations tool adds the user-digitized points as facilities to the service area layer. The Input Facilities parameter is a feature set data type so that the model can interactively accept the user-digitized points as facilities. The schema and symbology for the feature set are derived from the InputFacilities.lyr file found within the ToolData folder.
80
The Solve tool calculates the service area based on the options specified in the input service area layer and generates the drive-time polygons. The calculated polygons are written to the Polygons sublayer in the output service area layer. Network Analyst layers are not supported output parameter data types for ArcGIS Server clients. So the Select Data tool is used to retrieve the Polygons sublayer from the service area layer. The Polygons sublayer is a feature layer data type.
Tool layer
The Calculate Drive Time Polygons tool layer is created by dragging the model into the ArcMap table of contents. You should test the model before publishing as follows: 1. 2. 3. Create the tool layer. Right-click the tool layer and click Open. The tool dialog box opens. Enter a point and drive-time distances, such as 1 2 3, and click OK. The drive-time polygons are added as a sublayer to the tool layer.
The output of the Calculate Drive Time Polygons model is a feature layer. When a feature or raster layer is output by a model, the output layer is added to the tool layer as is, meaning symbology you define in the tool sublayer is ignored. You can try the following experiment to confirm this: 1. 2. 3. 4. After opening and executing the tool layer, right-click the Polygons sublayer and click Properties. Click the Symbology tab. Change the symbology to a single symbol (a blue polygon fill, for example). The Polygons sublayer is now drawn with a single color instead of graduated colors. Open the tool layer and execute. The Polygons sublayer is again drawn with graduated colors.
81
As explained in the topic Defining output symbology for geoprocessing tasks, when a model outputs a layer, the symbology found in the layer takes precedence over tool layer symbology. The reason for this rule is that some tools, like Make Service Area Layer, output layers containing custom symbology. To preserve this custom symbology, the symbology in the tool sublayer is ignored. If you want to change symbology of the drive-time polygons, the Calculate Drive Time Polygons model will need to output a feature class instead of a feature layer. This is easily accomplished by adding the Copy Features tool to the model, using the Polygons variable as input to Copy Features.
Publishing
SanFranciscoBaseMap.mxd is published as a map service. DriveTimePolygonsService.mxd is published as a geoprocessing service with no result map service, as follows: 1. 2. 3. In the Catalog window, right-click SanFranciscoBaseMap.mxd and click Publish to ArcGIS Server. Accept all defaults. In the Catalog window, navigate to your server administrative connection under the GIS Servers node, right-click, then choose Add New Service. Name the service DriveTimePolygonsService and choose Geoprocessing Service as the type. Click Next. In the next panel, choose Asynchronous for Execution Type. For The tools exposed by the Geoprocessing Service are stored in option, choose A map and specify DriveTimePolygonsService.mxd for Map Document. Since you will test your service, check Show Messages.
4. 5.
Publishing DriveTimePolygonsService
6.
Click Next. From this point on, you can accept the default values provided by the wizard and create the service.
82
Using
1. 2. 3. 4. Start ArcMap with a blank document. Create a user connection to ArcGIS Server from the Catalog window if one does not exist. Add the SanFranciscoBaseMap map service to the ArcMap table of contents. In the Catalog window, under your GIS Servers user connection node, expand the DriveTimePolygonsService toolbox and open the Calculate Drive Time Polygons tool by double-clicking it. The illustration below shows the result of these steps:
5.
Add a point to create a facility location. Specify 2 3 4 for drive-time values and click OK to run the task. After the task completes, the table of contents contains the Polygons output layer, as illustrated below.
83
Completed task
6.
Take the opportunity to examine the result of the task in the Results window as illustrated below.
Task results
84
Folder Purpose
ShortestRoute
Creates a shortest route between given points on a street network and generates driving directions in a text or HTML file.
Services
SanFranciscoBaseMap (map service) ShortestRouteService (geoprocessing service) Calculate Shortest Route and Text Directions Calculate Shortest Route and HTML Directions
Geoprocessing tasks
Inputs Outputs
Two or more user-digitized points. A shortest route between the user-specified points based on the travel time. An HTML or text file (depending on the task used) containing driving directions.
Uses a street network dataset for the San Francisco area provided in the ToolData folder. Network Analyst Demonstrates how to reuse an existing Route network analysis layer each time the task is executed. Calculate Shortest Route and HTML Directions taskHow an external Python library can be used from a script tool to convert driving directions from XML to HTML format.
Corresponding folder
C:\arcgis\ArcTutor\GP Service Examples\ShortestRoute contains the completed models, script tool, and data.
85
Example output from Calculate Shortest Route and Text Directions task
Data
The data for this example comes from C:\arcgis\ArcTutor\GP Service Examples\ShortestRoute.
Network dataset
The ToolData folder contains a file geodatabase, SanFrancisco.gdb. This geodatabase contains a network dataset, Streets_ND, within the Transportation feature dataset. This network dataset models the street network for the San Francisco area. It provides a network attribute, TravelTime, which indicates the time taken to travel each street segment in minutes.
86
Basemap
The basemap layer within SanFranciscoBaseMap.mxd has a layer, Streets, as illustrated below. This layer shows the extent of the network dataset. This means that this task can be used to determine the shortest route only in this extent.
87
88
89
90
Model processes
The Add Locations tool adds user-digitized points as stops to the route layer. The Input Locations parameter for the tool is specified through a model parameter, Input Stops. This parameter is a feature set data type. The schema and symbology for the feature set are derived from the InputStops.lyr file found within the ToolData folder. The schema for the Input Stops feature set contains a text field, Name. This field can be used to provide stop names while generating driving directions by mapping the Name property to the name field in Field mappings, as illustrated below. If the value for the name field is not specified by the user, default values of Location 1, Location 2, and so on, are used for stop names. Since the same route layer is used for each model run, any existing stops need to be removed before adding the new stops. To delete existing stops, the Append to existing locations option, illustrated below, is unchecked.
Adding stops
The Solve tool calculates the shortest route based on the TravelTime network attribute and other options as specified in the Route layer. The calculated route is written to the Routes sublayer in the output route layer. Network analysis layers (such as Route) are not supported output parameter data types for ArcGIS Server clients. So the Select Data tool is used to get the Routes sublayer from the Route layer. The Directions tool is used to generate the driving directions and output them to a text file. The output text file containing driving directions is created in the jobs directory on the server using the %scratchworkspace% inline variable. The SolveSucceeded variable derived from the Solve tool is used
91
as a precondition for the Directions tool. This means that the directions file is generated only if the Solve tool can find a route between input points.
Tool layer
The Calculate Shortest Route and Text Directions tool layer is created by dragging the Calculate Shortest Route and Text Directions model into the ArcMap table of contents. Since the model updates the existing Route layer, the tool layer output derives its symbology from the Routes sublayer within the Route layer in the table of contents.
Publishing
SanFranciscoBaseMap.mxd is published as a map service. ShortestRouteService.mxd is published as a geoprocessing service with no result map service, as follows: 1. 2. In the Catalog window, right-click SanFranciscoBaseMap.mxd and click Publish to ArcGIS Server. Accept all defaults.
92
3.
In the Catalog window, navigate to your server administrative connection under the GIS Servers node, right-click, then choose Add New Service. Name the service ShortestRouteService and choose Geoprocessing Service as the type. Click Next. In the next panel, choose Synchronous for Execution Type. For The tools exposed by the Geoprocessing Service are stored in option, choose A map and specify ShortestRouteService.mxd for Map Document. Since you will test your service, check Show Messages.
4. 5.
Publishing ShortestRouteService
6.
Click Next. From this point on, you can accept the default values provided by the wizard and create the service.
Using
1. 2. 3. 4. Start ArcMap with a blank document. Create a user connection to ArcGIS Server from the Catalog window if one does not exist. Add the SanFranciscoBaseMap map service to the ArcMap table of contents. In the Catalog window, under your GIS Servers user connection node, expand the ShortestRouteService toolbox and open the Calculate Shortest Route and Text Directions tool. The illustration below shows the result of these steps:
93
5.
Add two or more points to create stops. Optionally, specify names for each stop and click OK to run the task. After the task completes, the table of contents contains the Shortest Route output layer, as illustrated below. The input stops are not output from the task but are added to the table of contents from the Inputs node in the Results window.
Task result
6.
The text file containing the directions is copied from the jobs directory on the server to the scratch workspace for the current ArcMap session. The text file containing the directions can be viewed by double-clicking it in the Results window.
94
95
96
97
2. 3.
The ShortestRouteService service should now have a second task called Calculate Shortest Route and HTML Directions. This task is similar to the Calculate Shortest Route and Text Directions task except that it generates the directions in HTML format.
98
Folder Purpose
ClosestFacilities
Finds a given number of closest libraries from a starting location based on the travel time along a street network, calculates the shortest route to each of the closest library, and generates driving directions in a text file.
Services
Uses a street network dataset and a feature class containing all the library locations in the San Francisco area provided in the ToolData folder. Network Analyst Demonstrates how to use a solved network analysis layer for further analysis.
Corresponding folder
C:\arcgis\ArcTutor\GP Service Examples\ClosestFacilities contains the completed models and data.
99
Data
The data for this example comes from C:\arcgis\ArcTutor\GP Service Examples\ClosestFacilities.
Network dataset
The ToolData folder contains a file geodatabase, SanFrancisco.gdb. This geodatabase contains a network dataset, Streets_ND, within the Transportation feature dataset. This network dataset models the street network for the San Francisco area. It provides a network attribute, TravelTime, which indicates the time taken to travel each street segment.
100
Basemap
The basemap layer within SanFranciscoBaseMap.mxd has a layer, Streets, as illustrated below. This layer shows the extent of the network dataset. This means that this task can be used to determine the nearby libraries only in this extent.
101
Model
102
Model overview
The Find Nearby Libraries model is illustrated below. There are two input variables: Input Locations, which are the user-specified points from which the closest libraries are found Number of libraries to find
The model creates a closest facility network analysis layer; adds the library locations from the library feature layer as facilities; adds the user-specified locations as incidents; and performs a solve to determine the routes to the closest libraries, generate driving directions, and find only those libraries that are included in the routes from all the libraries that are loaded as facilities.
Element Street Network Type Network dataset layer Long, input parameter Tool Description The network dataset layer.
Creates a closest facility network analysis layer. This layer contains both data and properties that determine how the closest facilities will be calculated, along with the results of the calculation. Closest facility layer.
Library
The point feature class containing all the library locations. The positions of these points on the street network are already calculated as described in the section Precalculating network locations for libraries. Adds the library locations as facilities to the closest facility layer. Closest facility layer with facilities.
Tool Network Analyst layer Feature set (points), input parameter Tool Network Analyst layer Tool Network Analyst layer Boolean Tool File, output parameter Network Analyst layer
Input Locations
Adds the input locations as incidents to the closest facility layer. Closest facility layer with facilities and incidents.
Calculates the closest facilities and determines the shortest route to each facility. Closest facility layer containing all the facilities and the shortest route to the closest facilities. The derived output from the Solve tool that indicates if the solve was successful. Generates the driving directions for the routes to the closest facilities. The text file containing driving directions.
Closest facility layer containing all the facilities and the shortest route to the closest facilities.
103
Select Data Routes OutputRoutesSymbology Apply Symbology From Layer Closest Routes
Tool Feature layer Layer Tool Feature layer, output parameter Tool Feature layer Tool Table view Tool Feature layer Layer Tool Feature layer, output parameter
Selects the Routes sublayer from the closest facility layer. The routes layer from Closest Facility (3) Network Analyst layer. The symbology layer used to apply symbology to the Routes feature layer. Applies symbology to the Routes layer from the OutputRoutesSymbology layer. The Routes layer with appropriate symbology.
Select Data (Facilities) Facilities Join Field Facilities (3) Make Feature Layer Facilities_Layer ClosestLibrariesSymbology Apply Symbology From Layer (1) Closest Libraries
Selects the facilities sublayer from the closest facility layer. The facilities layer from the Closest Facility (3) Network Analyst layer. Joins the FacilityID, FacilityRank, Total_TravelTime, and Total_Meters fields from the Routes layer to the Facilities layer. The derived facilities layer containing the joined fields. Selects only the facilities for which the FacilityID value is not null. Only the fields required in the output facilities are set to be visible. The facilities feature layer containing only the facilities that are included in the routes. The symbology layer used to apply symbology to Facilities_Layer. Applies symbology to Facilities_layer from the ClosestLibrariesSymbology layer. The Facilities_Layer with appropriate symbology.
Model elements
104
105
Note that if in another scenario the facilities are transient, their network locations will have to be determined every time they are added as facilities. So precalculating their network locations using the Calculate Locations tool will not provide any performance benefit.
106
Model processes
The Make Closest Facility Layer tool creates a new Network Analyst layer, Closest Facility, that stores the analysis properties, references the Streets_ND network dataset layer used for the analysis, and stores the input facilities and incidents and the output routes. The network dataset has a network cost attribute called TravelTime, which specifies the travel time required to traverse each street segment in minutes. This attribute is used as an impedance attribute. The Number of libraries to find variable specifies the number of facilities to find.
The Add Locations (Libraries) tool adds the library locations as facilities to the closest facility layer. Since the network locations for the libraries were already calculated using the Calculate Locations tool, the Use Network Location fields instead of geometry option was checked.
The Add Locations tool adds the user-digitized points as incidents to the closest facility layer. The Input Locations parameter is a feature set data type so that the model can interactively accept the user-digitized
107
points as incidents. The schema and symbology for the feature set are derived from the InputLocations.lyr file found within the ToolData folder. The Solve tool searches the given number of closest facilities from each incident and calculates a shortest route to each facility based on the TravelTime network attribute. The calculated routes are written to the Routes sublayer in the output closest facility layer. The Network Analyst layer is not a supported output parameter data type for ArcGIS Server clients. So the Select Data tool is used to get the Routes sublayer from the Closest Facility Network Analyst layer. The Routes sublayer uses the symbology of the Network Analyst layer. To apply a different symbology such that each route has a unique color, the Apply Symbology From Layer tool is used to apply symbology to the Routes sublayer from the OutputRoutesSymbology layer. The Directions tool is used to generate the driving directions and output them to a text file. The output text file containing driving directions is created in the jobs directory on the server using the%scratchworkspace% inline variable. The Routes sublayer in the Closest Facility layer contains a FacilityID field that indicates the object ID of the facility visited by the route. This information can be used to select only the facilities that are visited by routes from all the facilities. The Join Field tool joins the Routes sublayer to the facilities layer using the FacilityID field. The tool joins the FacilityID, FacilityRank, Total_TravelTime, and Total_Meters fields to the facilities sublayer based on FacilityID in routes and ObjectID in facilities.
The output of the Join Field tool contains the FacilityID field in the facilities sublayer. This field has a value of null for all the facilities that are not visited by the routes. Using the Make Feature Layer tool, only those facilities for which the value of the FacilityID field is not null are selected and output to a new layer.
108
The symbology for the facilities layer is set from the OutputLibrariesSymbology layer using the Apply Symbology From Layer tool.
Tool layer
The Find Nearby Libraries tool layer is created by dragging the Find Nearby Libraries model into the ArcMap table of contents. Since the model outputs are in-memory feature layers, the Closest Libraries and Routes sublayer within the tool layer will have a broken data source when you first open ClosestFacilitiesService.mxd. The map document will publish as is. However, you should rerun the tool layer and verify that the model works before publishing the service. Note that if you change the symbology for any of the output layers in the tool layer, the new symbology will not be used. This is because the outputs of this model are feature layers and their symbologies have already been defined using the Apply Symbology To Layer tool in the model.
Publishing
SanFranciscoBaseMap.mxd is published as a map service. ClosestFacilitiesService.mxd is published as a geoprocessing service with no result map service, as follows: 1. 2. 3. In the Catalog window, right-click SanFranciscoBaseMap.mxd and click Publish to ArcGIS Server. Accept all defaults. In the Catalog window, navigate to your server administrative connection under the GIS Servers node, right-click, then choose Add New Service. Name the service ClosestFacilitiesService and choose Geoprocessing Service as the type. Click Next.
4.
109
5.
In the next panel, choose Synchronous for Execution type. For The tools exposed by the Geoprocessing service are stored in option, choose A map and specify ClosestFacilitiesService.mxd for Map Document. Since you will test your service, check Show Messages.
6.
Click Next. From this point on, you can accept the default values provided by the wizard and create the service.
Using
1. 2. 3. 4. Start ArcMap with a blank document. Create a user connection to ArcGIS Server from the Catalog window if one does not exist. Add the SanFranciscoBaseMap map service to the ArcMap table of contents. In the Catalog window, under your GIS Servers user connection node, expand the ClosestFacilitiesService toolbox and open the Find Nearby Libraries tool. The illustration below shows the result of these steps:
110
5.
Add a point to create an input location. Specify 3 for number of libraries to find and click OK to run the task. After the task completes, the table of contents contains the Closest Libraries and Routes output layer, as illustrated below. The input locations are not output from the task but are added to the table of contents from the Inputs node in the Results window.
Completed task
6.
The text file containing the directions is copied from the jobs directory on the server to the scratch workspace for the current ArcMap session. This file can be viewed by double-clicking it in the Results window.
111
112