Available with Network Analyst license.
Item | Description |
---|---|
Purpose | Generates travel directions between input points for the given travel mode. This example describes how to author, publish, and use a geoprocessing service that can perform network analysis. |
Service | TravelDirections (geoprocessing service) |
Web tool | GetTravelDirections |
Inputs |
|
Outputs | A feature class with the travel directions and the shape of the route |
Data | A street network dataset for the San Diego, California, area provided in the ToolData folder |
Minimum ArcGIS software requirements |
|
Of note | Demonstrates the basic steps required to author, publish, and use a web tool for generating travel directions based on a travel mode. You can follow similar steps to create a web tool for other types of analysis on transportation networks, such as generating drive-time areas around a set of facilities. |
GetTravelDirections tool
The primary purpose of the GetTravelDirections tool is to generate travel directions around user-specified points based on a given travel mode. The tool creates an output line feature class that shows the best route between the input points and text containing the travel directions to navigate the route.
The table below shows some of the columns from the output feature class created by the GetTravelDirections tool. The values in the ElapsedTime column are in the units of the time impedance attribute defined in the travel mode used for the analysis (minutes, in this example), and the values in the DriveDistance column are in the units of the distance impedance attribute defined in the travel mode (miles, in this example).
Selected columns from the GetTravelDirections tool output
Text | ElapsedTime | DriveDistance |
---|---|---|
Start at Stop A | 0 | 0 |
Go north on BRITANNIA BLVD toward OTAY MESA RD | 1.04 | 0.64 |
Turn right on OTAY MESA RD | 1.83 | 2.44 |
Continue forward on CA-905 | 0.29 | 0.39 |
Continue forward on OTAY MESA RD | 0.04 | 0.06 |
Keep left at the fork onto OTAY MESA RD | 0.16 | 0.1 |
Turn left | 0.04 | 0.02 |
Continue forward on CA-125 | 7.17 | 10.41 |
Finish at Stop B, on the right | 0 | 0 |
Data folder
The data for this tutorial can be downloaded from ArcGIS Online. Extract the data to C:\Routing\TravelDirections. The folder contains an ArcGIS AllSource project called TravelDirections.aprx. In this project, the TravelDirections.tbx toolbox contains a tool called GetTravelDirections that generates the travel directions. A transportation network, called Streets_ND, used by the GetTravelDirections tool is stored in a file geodatabase called SanDiego.gdb in the ToolData folder. The network dataset is added to the default map in the project as a layer called Street Network. The schema.gdb geodatabase contains the Stops feature class that is referenced by the Stops.lyrx layer file. This layer file is used to define the schema and the symbology for the input stops used by the GetTravelDirections tool.
Authoring geoprocessing tool
The GetTravelDirections geoprocessing tool is an example of a script tool that is used to provide a specific functionality (in this example, to generate travel directions). Running the tool executes the Python code that you write in a file and associate with the script tool. For this example, the Python code for the GetTravelDirections tool is written in the get_directions.py file. The inputs and outputs for the script tool, known as tool parameters, are defined using the New Script dialog box in ArcGIS AllSource.
Defining tool parameters
The image below shows the various parameters defined for the GetTravelDirections tool:
The tool uses the Feature Set data type for the stops parameter. This adds the ability to specify the input stops interactively. The schema and the symbology for the feature set are defined from the Stops.lyrx file in the ToolData folder. This allows you to enforce the constraint that the input stops can only be specified using a point geometry and also allows you to predefine the set of attribute fields supported by the input. If you do not define the schema, the users of your service can specify any geometry type for the feature set.
Note:
Specifying the schema for a feature set does not prevent users of your service to pass unsupported fields. In your tool's implementation, you can list all the input fields provided to the service and decide how the tool should behave if it gets fields that are not defined in the schema. In most cases, you can ignore the fields that are not defined in the schema.
The tool uses the Network Dataset Layer data type for the network_dataset parameter. This allows you to specify a network dataset using a network dataset layer from the map. The other valid data types for specifying a network dataset are Network Dataset and Network Data Source. The Network Data Source data type allows you to specify a network dataset on disk, a network dataset layer from a map, or a URL to an ArcGIS Online or ArcGIS Enterprise portal configured with routing services. In this example, you do not want to use routing services from a portal to run your analysis so you should not select the Network Data Source data type. The Network Dataset data type allows you to specify a network dataset only using the path to its disk location. While the GetTravelDirections tool can work with a network dataset specified using its path, this is not recommended, as the tool connects to the network dataset for every request, which is slow and increases the response time of the request.
Tip:
Using a network dataset layer improves the overall tool execution time since the network dataset layer keeps a connection to the network dataset open. Otherwise, if the network dataset is referenced by the path to its disk location, a connection to the network dataset is made each time the tool executes, which reduces the performance of the geoprocessing service created from the tool.
The tool uses the Network Travel Mode data type for the travel_mode parameter. The network_dataset parameter is set as a dependency for the network_travel_mode parameter. This causes the tool to read the travel modes defined on the network dataset and populate their names as the list of possible values supported by the travel_mode parameter.
The tool uses the Date data type for the start_time parameter. This parameter is optional and does not define a default value. In the tool's implementation, if a value is passed for the start_time parameter, it is used to calculate the travel time that uses travel speeds based on historical traffic patterns observed for that date-time value. If no value is passed for the start_time parameter, the tool calculates travel time based on a fixed travel speed.
The tool uses the Feature Class data type for the output_directions parameter. The parameter is marked as an output parameter by setting its Direction property. The default value for this parameter specifies that the output is written to a feature class in a memory-based workspace .
Tip:
Writing outputs to a memory-based workspace compared to a file geodatabase improves the performance of the geoprocessing service created from the script tool. In most cases, you should write outputs from your geoprocessing tools that perform network analysis to a memory-based workspace. The output should be written to a file geodatabase if you know your tool will produce large outputs that cannot be stored in the memory of the server machine running the geoprocessing service.
Documenting the tool
By documenting the geoprocessing tool, you are also documenting the resultant service and its parameters because the service publishing process copies the text to the item description of the service. Describing, or documenting, the service is required and helps users understand how to successfully interact with the service and generate travel directions. The GetTravelDirections tool used in this example is documented; you can inspect it by right-clicking the geoprocessing tool in the Catalog pane and choosing View Metadata.
Defining tool execution
When a request is sent to a geoprocessing service, the tool behind the service executes a Python script file associated with the tool. You define the implementation of your tool in this script file. The code snippet below lists the Python code that defines the implementation of the GetTravelDirections tool. The script uses the Route class in the arcpy.nax module to perform the point-to-point routing and generate travel directions.
The code snippet below includes the content of the get_directions.py file included in the tool folder. It shows how to perform point-to-point routing and export travel directions to a feature class. The general pattern for performing any type of network analysis (including point-to-point routing demonstrated here) is to initialize the solver class specific to the analysis, set the analysis settings, load the inputs, solve the analysis, and export the results. The comments in the source code (lines beginning with #) provide further information on the implementation details including some tips to optimize the performance of the tool.
"""Generate travel directions based on a travel mode."""
import arcpy
def get_directions():
"""Generate travel directions based on a travel mode."""
# Read inputs
stops = arcpy.GetParameter(0)
# Performance tip: The network data source should be read using the arcpy.GetParameterAsText()
# method instead of the arcpy.GetParameter() method since GetParameterAsText provides
# access to the network data source much faster
network_data_source = arcpy.GetParameterAsText(1)
travel_mode = arcpy.GetParameter(2)
start_time = arcpy.GetParameter(3)
output_directions = arcpy.GetParameterAsText(4)
# Initialize Route solver and set analysis settings
route_solver = arcpy.nax.Route(network_data_source)
route_solver.travelMode = travel_mode
route_solver.timeOfDay = start_time
route_solver.returnDirections = True
# Load inputs
route_solver.load(arcpy.nax.RouteInputDataType.Stops, stops)
# Solve. A network analyst license is required when solving
arcpy.CheckOutExtension("network")
result = route_solver.solve()
# Print all the warning and error messages in case the solve is not successful
if not result.solveSucceeded:
arcpy.AddMessage("Solve failed")
warning_msgs = result.solverMessages(arcpy.nax.MessageSeverity.Warning)
error_msgs = result.solverMessages(arcpy.nax.MessageSeverity.Error)
for msg in warning_msgs:
arcpy.AddWarning(msg[-1])
for msg in error_msgs:
arcpy.AddError(msg[-1])
raise SystemExit(1)
# Export the directions
result.export(arcpy.nax.RouteOutputDataType.Directions, output_directions)
if __name__ == "__main__":
get_directions()
Note:
The code snippet above shows how to implement point-to-point routing using the arcpy.nax module. However, the pattern shown in the code snippet above can be applied to any other analysis using the arcpy.nax module.
Publishing the tool as a web tool
To create a service from the GetTravelDirections tool, you must publish the tool as a web tool. To accomplish this, you must first successfully run the tool and share the tool result as a web tool using the Share As Web Tool pane in ArcGIS AllSource.
Running the tool
To run the GetTravelDirections tool, complete the following steps:
- Open the TravelDirections project in ArcGIS AllSource.
- In the TravelDirections toolbox, open the GetTravelDirections geoprocessing tool.
- Run the GetTravelDirections tool.
- For the Stops parameter, create at least two stops in the San Diego area of the map.
- For the Network Dataset parameter, select the Street Network layer added to the map.
Specifying the Street Network layer, and not specifying the network dataset using its disk location, provides the best performance for the geoprocessing service created from the tool.
- For the Travel Mode parameter, select a travel mode from the choice list such as Driving Time.
The choice list for the Travel Mode parameter lists the travel mode names from the network dataset because the Network Dataset parameter was set as a dependency when defining the Travel Mode parameter.
- Do not specify a value for the Start Time parameter.
Specifying a value for the Start Time parameter causes the service created from the tool to use this date-time value as the default start time when generating travel directions, which may not be desirable for the users of the service as they likely want to pass a date-time.
- Leave the default value for the Output Directions parameter.
The default value for the Output Directions parameter is to write the output from the tool to a memory-based workspace, which improves the performance of the service created from the tool.
- Click the Run button to run the tool.
Registering the folder containing the network dataset as a data store
The network dataset used by the GetTravelDirections tool must be accessible to all the machines that are participating in your ArcGIS Server site. You can achieve this in one of the following ways:
- Allow the publishing process to copy the network dataset to a location in your ArcGIS Server site that is accessible to all the participating machines.
- Copy the network dataset to all the participating machines at a location you predefine and allow the service to reference the data from this location.
The recommended option is to manually copy the network dataset on all the participating machines at a predefined location (for example, D:\RoutingData). While this may seem to be the more laborious of the two available options, it is more effective and provides better performance for the service.
Select a location for the data that is local to each participating machine instead of a file share common to all the machines. Storing the network dataset in a local folder as opposed to a file share improves the performance of the routing service. To update the network dataset—for example, if you receive a newer version of the data—you can stop the routing service, replace the file geodatabase containing the network dataset on all the participating machines, and restart the service.
When you select the option to copy the data , the publishing process copies the data to a shared location that is common to all the machines (when you have multiple machines in your ArcGIS Server site). The routing service reads the network dataset from a shared location, which degrades service performance. The location used by ArcGIS Server to store this data is considered internal to the ArcGIS Server site and is managed by ArcGIS Server. To perform data updates, you must delete and re-create the routing service, which may cause errors because you must republish the routing service using the same settings you previously used. Instead, if the data is referenced by the routing service, stop and start the routing service rather than re-creating the service.
To register the folder containing the network dataset as a data store in your server that is federated with your portal, complete the following steps:
- On the ribbon, click the Share tab. In the Manage group, click Data Stores .
The Manage Registered Data Stores pane appears.
- At the top of the pane, confirm that the drop-down list is set to Portal Items. Click the Add button and click Folder .
- On the Add data store dialog box, provide a title such as RoutingData and tags.
This is required metadata for the data store portal item.
- Optionally specify a folder to contain the data store item in your portal.
By default, the item is stored at the root level of your content. You can choose an existing folder or create a folder using the drop-down menu. You can also browse to a folder.
- To specify the publisher folder, click the Browse button , browse to the folder containing the network dataset C:\Routing\TravelDirections\ToolData, and click OK.
The publisher folder is the folder that contains the data you want to register with the server.
- If the publisher and server have the data in different folders, uncheck the Same as publisher folder path check box and type a path or browse to a folder the server can access.
- Click the check box for the server to which you want to add the data store. You can select more than one server.
- Optionally click Validate to confirm that the server can access the server folder.
If the folder is accessible, a confirmation appears in the Status column next to the server name. If not, an error appears. The connection is also validated automatically when you create the data store.
- Under Sharing Level, specify how the data store will be shared.
- Everyone (public)—This option makes your data store public. Anyone can access and see it.
- My Organization—This option allows your data store to be shared with all authenticated users in the organization.
- Groups—You can share your data store with groups to which you belong and their members.
Leave all options unchecked to set the sharing level to the owner of the item. Organization members with privileges to view content owned by other members can also access the item.
- Click Create.
The data store is created and appears in the Manage Registered Data Stores pane.
Sharing the tool as a web tool
To create a geoprocessing service from the GetTravelDirections tool, complete the following steps:
- Sign in to your ArcGIS Enterprise portal as a user who has permissions to publish web tools.
Sharing web tools requires administrative or web tool publisher permissions.
- Click the History button in the Geoprocessing group on the Analysis ribbon tab to open the History pane.
- Right-click GetTravelDirections and select Share As > Web Tool.
- Configure the service settings, such as the service name and the execution mode, in the Share As Web Tool pane.
- Under Item Details, type TravelDirections for Name.
- Under Data, select Reference registered data.
- Under Location, optionally specify or create a portal folder to store the web tool item in your ArcGIS Enterprise portal.
If you do not specify a Portal Folder value, the web tool item is stored at the root level of your content.
- Under Location, select the federated server to which you want to publish the web tool and the folder on the federated server that will contain the routing service.
If you are using a base deployment of ArcGIS Enterprise, there is only one server (the hosting server) in the Server and Folder list. If you do not specify the folder name under Server and Folder, the routing service is created in the root folder of your federated server.
- Under Sharing Level, specify how the web tool will be shared.
By default, a web tool is only accessible to the user who published it. The web tool can be shared publicly so that anyone can execute the web tool, with all the authenticated users in the organization, or with specific groups to which you belong and their members.
- Click the Configuration tab in the Share As Web Tool pane.
- Under Capabilities, uncheck the Uploads check box.
The uploads capability controls whether a client can upload a file to your server for the web tool to use as input. The routing service in this example does not need to support file uploads.
- Under Execution Mode, select Synchronous.
The TravelDirections routing service executes quickly (usually in less than a second). Select the Synchronous execution mode for best performance. However, if you have a routing service that took a long time to execute (for example, calculating multiple long-distance two-point routes), set the execution mode to Asynchronous since the asynchronous execution mode is better suited for long-running requests. Using asynchronous execution mode for services that execute quickly is not recommended since it adds a fixed overhead to every execution of the service. For long-running requests, the fixed overhead incurred is an insignificant contributor to the overall execution time of the service.
- Under Properties, select Warning for Message Level
Setting the message level of the service to Warning ensures that all error and warning messages produced by the service are returned to the client. This can be helpful for clients when diagnosing service issues, such as why the service cannot generate travel directions.
- Under Properties, use the default value for Maximum number of records returned by server.
The service in this example should not produce more than 1,000 output directions features for most cases. If the service produces more than 1,000 features, the server only returns the first 1,000 features to the clients, and a subset of features may not be useful to clients. To avoid this, set a higher value for the Maximum number of records returned by server option. For other routing services, you can set this option to a higher number. For example, if you have a service that frequently computes an origin-destination cost matrix between 500 origins and 500 destinations, your service can produce 250,000 features. Set this option value to at least 250,000 or more in these cases.
- Click the Content tab in the Share As Web Tool pane.
- Click the Configure Tool Properties button to the right of the GetTravelDirections tool under My Content > TravelDirections to configure the properties of the GetTravelDirections web tool.
- Expand the Network Dataset parameter category and select Constant value for the Input Mode option.
The clients using the TravelDirections service do not need to specify the network dataset used to generate the travel directions since the service always uses the same network dataset. Setting the parameter's input mode as constant ensures that the parameter is not available on the resulting service created by the tool.
- Click the back button in the upper left corner of the GetTravelDirections page to go back to the Share As Web Tool pane.
- Click the Analyze button in the Share As Web Tool pane and ensure that there are no errors or warnings reported.
The analyzer checks for issues that will prevent successful execution of the tool as a service. If errors are reported, you must correct them before publishing the tool. If only warnings are reported, you can proceed to publish if the warnings are expected for your scenario. For example, if you are copying data instead of referencing registered data, a warning message appears indicating that the data will be copied to the server. This is an expected warning for this scenario, and this message can be ignored. You can right-click an error or warning message to access the help topic that describes how to fix an issue.
- Click the Publish button in the Share As Web Tool pane to publish the tool as a service.
Using the web tool
You can open web tools in the Portal section of the Catalog pane in ArcGIS AllSource. In addition to running the tool in ArcGIS AllSource, the geoprocessing service can be used in a Python script or web app.
The steps below describe how to run the GetTravelDirections tool using ArcGIS AllSource as a client application:
- In the Catalog pane, click Portal > All Portal.
- Type TravelDirections in the Search bar.
- Double-click the TravelDirections toolbox and open the GetTravelDirections tool.
- Run the GetTravelDirections web tool.
The Output Feature Class Name parameter on the web tool is automatically added by the geoprocessing framework since the GetTravelDirections tool outputs a feature class. This parameter allows you to write the results as a feature service stored in your enterprise portal. However, using this parameter has certain limitations.
Caution:
If you specify an Output Feature Service Name value, the GetTravelDirections web tool returns an error since creating results as a feature service is not supported by a service published using the synchronous execution mode such as the TravelDirections service in this example.