Make Route Analysis Layer (Network Analyst)

Summary

Makes a route network analysis layer and sets its analysis properties. A route analysis layer is useful for determining the best route between a set of network locations based on a specified network cost. The layer can be created using a local network dataset or a routing service hosted online or in a portal.

Usage

  • After creating the analysis layer with this tool, you can add network analysis objects to it using the Add Locations tool, solve the analysis using the Solve tool, and save the results on disk using the Save To Layer File tool.

  • When using this tool in geoprocessing models, if the model is run as a tool, the output network analysis layer must be made a model parameter; otherwise, the output layer is not added to the contents of the map.

  • In ArcGIS Pro, network analysis layer data is stored on disk in file geodatabase feature classes. When creating a network analysis layer in a project, the layer's data will be created in a new feature dataset in the Current Workspace environment. When creating a network analysis layer in a Python script, you must first explicitly set the workspace environment to a file geodatabase where you want the layer's data to be stored using arcpy.env.workspace = "<path to file gdb>". When the layer is created, a new feature dataset containing the appropriate sublayer feature classes will be added to this file geodatabase.

Syntax

MakeRouteAnalysisLayer(network_data_source, {layer_name}, {travel_mode}, {sequence}, {time_of_day}, {time_zone}, {line_shape}, {accumulate_attributes}, {generate_directions_on_solve}, {time_zone_for_time_fields})
ParameterExplanationData Type
network_data_source

The network dataset or service on which the network analysis will be performed. Use the portal URL for a service.

Network Dataset Layer;String
layer_name
(Optional)

The name of the network analysis layer to create.

String
travel_mode
(Optional)

The name of the travel mode to use in the analysis. The travel mode represents a collection of network settings, such as travel restrictions and U-turn policies, that determine how a pedestrian, car, truck, or other medium of transportation moves through the network. Travel modes are defined on your network data source.

An arcpy.na.TravelMode object and a string containing the valid JSON representation of a travel mode can also be used as input to the parameter.

String
sequence
(Optional)

Specifies whether the input stops must be visited in a particular order when calculating the optimal route. This option changes the route analysis from a shortest-path problem to a traveling salesperson problem (TSP).

  • USE_CURRENT_ORDERThe stops will be visited in the input order. This is the default.
  • FIND_BEST_ORDERThe stops will be reordered to find the optimal route. This option changes the route analysis from a shortest-path problem to a traveling salesperson problem (TSP).
  • PRESERVE_BOTHPreserve the first and last stops by input order. The rest will be reordered to find the optimal route.
  • PRESERVE_FIRSTPreserve the first stop by input order. The rest will be reordered to find the optimal route.
  • PRESERVE_LASTPreserve the last stop by input order. The rest will be reordered to find the optimal route.
String
time_of_day
(Optional)

The start date and time for the route. Route start time is typically used to find routes based on the impedance attribute that varies with the time of the day. For example, a start time of 7:00 a.m. could be used to find a route that considers rush hour traffic. The default value for this parameter is 8:00 a.m. A date and time can be specified as 10/21/05 10:30 AM. If the route spans multiple days and only the start time is specified, the current date is used.

Instead of using a particular date, a day of the week can be specified using the following dates:

  • Today—12/30/1899
  • Sunday—12/31/1899
  • Monday—1/1/1900
  • Tuesday—1/2/1900
  • Wednesday—1/3/1900
  • Thursday—1/4/1900
  • Friday—1/5/1900
  • Saturday—1/6/1900

For example, to specify that travel should begin at 5:00 p.m. on Tuesday, specify the parameter value as 1/2/1900 5:00 PM.

After the solve, the start and end times of the route are populated in the output routes. These start and end times are also used when directions are generated.

Date
time_zone
(Optional)

Specifies the time zone of the time_of_day parameter.

  • LOCAL_TIME_AT_LOCATIONSThe time_of_day parameter refers to the time zone in which the first stop of a route is located. This is the default.If you are generating many routes that start in multiple times zones, the start times are staggered in coordinated universal time (UTC). For example, a time_of_day value of 10:00 a.m., 2 January, would mean a start time of 10:00 a.m. eastern standard time (3:00 p.m. UTC) for routes beginning in the eastern time zone and 10:00 a.m. central standard time (4:00 p.m. UTC) for routes beginning in the central time zone. The start times are offset by one hour in UTC.The arrival and departure times and dates recorded in the output Stops feature class will refer to the local time zone of the first stop for each route.
  • UTCThe time_of_day parameter refers to coordinated universal time (UTC). Choose this option if you want to generate a route for a specific time, such as now, but aren't certain in which time zone the first stop will be located.If you are generating many routes spanning multiple times zones, the start times in UTC are simultaneous. For example, a time_of_day value of 10:00 a.m., 2 January, would mean a start time of 5:00 a.m. eastern standard time (10:00 a.m. UTC) for routes beginning in the eastern time zone and 4:00 a.m. central standard time (10:00 a.m. UTC) for routes beginning in the central time zone. Both routes would start at 10:00 a.m. UTC.The arrival and departure times and dates recorded in the output Stops feature class will refer to UTC.
String
line_shape
(Optional)

Specifies the shape type for the route features that are output by the analysis.

  • ALONG_NETWORKThe output routes will have the exact shape of the underlying network sources. The output includes route measurements for linear referencing. The measurements increase from the first stop and record the cumulative impedance to reach a given position.
  • NO_LINESNo shape will be generated for the output routes.
  • STRAIGHT_LINESThe output route shape will be a single straight line between the stops.

No matter which output shape type is chosen, the best route is always determined by the network impedance, never Euclidean distance. This means that only the route shapes are different, not the underlying traversal of the network.

String
accumulate_attributes
[accumulate_attributes,...]
(Optional)

A list of cost attributes to be accumulated during analysis. These accumulated attributes are for reference only; the solver only uses the cost attribute used by your designated travel mode when solving the analysis.

For each cost attribute that is accumulated, a Total_[Impedance] property is populated in the network analysis output features.

This parameter is not available if the network data source is an ArcGIS Online service or the network data source is a service on a version of Portal for ArcGIS that does not support accumulation.

String
generate_directions_on_solve
(Optional)

Specifies whether directions will be generated when running the analysis.

  • DIRECTIONSTurn-by-turn directions will be generated on solve. This is the default.
  • NO_DIRECTIONSTurn-by-turn directions will not be generated on solve.

For an analysis in which generating turn-by-turn directions is not needed, using the NO_DIRECTIONS option will reduce the time it takes to solve the analysis.

Boolean
time_zone_for_time_fields
(Optional)

Specifies the time zone that will be used to interpret the time fields included in the input tables, such as the fields used for time windows.

  • LOCAL_TIME_AT_LOCATIONSThe dates and times in the time fields for the stop will be interpreted according to the time zone in which the stop is located. This is the default.
  • UTCThe dates and times in the time fields for the stop refer to coordinated universal time (UTC).
String

Derived Output

NameExplanationData Type
out_network_analysis_layer

The output network analysis layer.

Network Analyst Layer

Code sample

MakeRouteAnalysisLayer example 1 (Python window)

Execute the tool using only the required parameters.

network = "C:/Data/SanFrancisco.gdb/Transportation/Streets_ND"
arcpy.na.MakeRouteAnalysisLayer(network, "WorkRoute")
MakeRouteAnalysisLayer example 2 (Python window)

Execute the tool using all parameters.

network = "C:/Data/SanFrancisco.gdb/Transportation/Streets_ND"
arcpy.na.MakeRouteAnalysisLayer(network, "InspectionRoute", "Driving Time",
                        "FIND_BEST_ORDER", "1/1/1900 9:00 AM", "UTC",
                        "ALONG_NETWORK", ["Meters", "TravelTime"])
MakeRouteAnalysisLayer example 3 (workflow)

The following stand-alone Python script demonstrates how the MakeRouteAnalysisLayer tool can be used to find a best route to visit the geocoded stop locations.

# Name: MakeRouteAnalysisLayer_Workflow.py
# Description: Find a best route to visit the stop locations and save the
#              route to a layer file. The stop locations are geocoded from a
#              text file containing the addresses.
# Requirements: Network Analyst Extension

#Import system modules
import arcpy
from arcpy import env
import os

try:
    #Check out Network Analyst license if available. Fail if the Network Analyst license is not available.
    if arcpy.CheckExtension("network") == "Available":
        arcpy.CheckOutExtension("network")
    else:
        raise arcpy.ExecuteError("Network Analyst Extension license is not available.")
    
    #Set environment settings
    output_dir = "C:/Data"
    #The NA layer's data will be saved to the workspace specified here
    env.workspace = os.path.join(output_dir, "Output.gdb")
    env.overwriteOutput = True

    #Set local variables
    input_gdb = "C:/Data/SanFrancisco.gdb"
    network = os.path.join(input_gdb, "Transportation", "Streets_ND")
    layer_name = "BestRoute"
    travel_mode = "Driving Time"
    address_locator = "C:/Data/SanFranciscoLocator"
    address_table = "C:/Data/StopAddresses.csv"
    address_fields = "Street Address;City City;State State;ZIP <None>"
    out_stops = "GeocodedStops"
    output_layer_file = os.path.join(output_dir, layer_name + ".lyrx")

    #Create a new Route layer. For this scenario, the default values for all the
    #remaining parameters statisfy the analysis requirements
    result_object = arcpy.na.MakeRouteAnalysisLayer(network, layer_name,
                                                                    travel_mode)

    #Get the layer object from the result object. The route layer can now be
    #referenced using the layer object.
    layer_object = result_object.getOutput(0)

    #Get the names of all the sublayers within the route layer.
    sublayer_names = arcpy.na.GetNAClassNames(layer_object)
    #Stores the layer names that we will use later
    stops_layer_name = sublayer_names["Stops"]

    #Geocode the stop locations from a csv file containing the addresses.
    #The Geocode Addresses tool can use a text or csv file as input table
    #as long as the first line in the file contains the field names.
    arcpy.geocoding.GeocodeAddresses(address_table, address_locator,
                                     address_fields, out_stops)

    #Load the geocoded address locations as stops mapping the address field from
    #geocoded stop features as Name property using field mappings.
    field_mappings = arcpy.na.NAClassFieldMappings(layer_object,
                                                            stops_layer_name)
    field_mappings["Name"].mappedFieldName = "Address"
    arcpy.na.AddLocations(layer_object, stops_layer_name, out_stops,
                            field_mappings, "")

    #Solve the route layer, ignoring any invalid locations such as those that
    #cannot be geocoded
    arcpy.na.Solve(layer_object, "SKIP")

    #Save the solved route layer as a layer file on disk
    layer_object.saveACopy(output_layer_file)

    print("Script completed successfully")

except Exception as e:
    # If an error occurred, print line number and error message
    import traceback, sys
    tb = sys.exc_info()[2]
    print("An error occurred on line %i" % tb.tb_lineno)
    print(str(e))
MakeRouteAnalysisLayer example 4 (workflow)

This example shows how to calculate multiple routes in a single solve, a method useful for calculating distances or drive times between origin-destination pairs.

# Name: MakeRouteAnalysisLayer_MultiRouteWorkflow.py
# Description: Calculate the home-work commutes for a set of people and save
#              the output to a feature class
# Requirements: Network Analyst Extension

#Import system modules
import arcpy
from arcpy import env
import datetime
import os

try:
    #Check out Network Analyst license if available. Fail if the Network Analyst license is not available.
    if arcpy.CheckExtension("network") == "Available":
        arcpy.CheckOutExtension("network")
    else:
        raise arcpy.ExecuteError("Network Analyst Extension license is not available.")
    
    #Set environment settings
    output_dir = "C:/Data"
    #The NA layer's data will be saved to the workspace specified here
    env.workspace = os.path.join(output_dir, "Output.gdb")
    env.overwriteOutput = True

    #Set local variables
    input_gdb = "C:/Data/SanFrancisco.gdb"
    network = os.path.join(input_gdb, "Transportation", "Streets_ND")
    stops_home = os.path.join(input_gdb, "Analysis", "Commuters_Home")
    stops_work = os.path.join(input_gdb, "Analysis", "Commuters_Work")
    layer_name = "Commuters"
    out_routes_featureclass = "Commuter_Routes"
    travel_mode = "Driving Time"

    #Set the time of day for the analysis to 8AM on a generic Monday.
    start_time = datetime.datetime(1900, 1, 1, 8, 0, 0)

    #Create a new Route layer.  Optimize on driving time, but compute the
    #distance traveled by accumulating the Meters attribute.
    result_object = arcpy.na.MakeRouteAnalysisLayer(network, layer_name,
                                        travel_mode, time_of_day=start_time,
                                        accumulate_attributes=["Meters"])

    #Get the layer object from the result object. The route layer can now be
    #referenced using the layer object.
    layer_object = result_object.getOutput(0)

    #Get the names of all the sublayers within the route layer.
    sublayer_names = arcpy.na.GetNAClassNames(layer_object)
    #Stores the layer names that we will use later
    stops_layer_name = sublayer_names["Stops"]
    routes_layer_name = sublayer_names["Routes"]

    #Before loading the commuters' home and work locations as route stops, set
    #up field mapping.  Map the "Commuter_Name" field from the input data to
    #the RouteName property in the Stops sublayer, which ensures that each
    #unique Commuter_Name will be placed in a separate route.  Matching
    #Commuter_Names from stops_home and stops_work will end up in the same
    #route.
    field_mappings = arcpy.na.NAClassFieldMappings(layer_object, stops_layer_name)
    field_mappings["RouteName"].mappedFieldName = "Commuter_Name"

    #Add the commuters' home and work locations as Stops. The same field mapping
    #works for both input feature classes because they both have a field called
    #"Commuter_Name"
    arcpy.na.AddLocations(layer_object, stops_layer_name, stops_home,
                        field_mappings, "")
    arcpy.na.AddLocations(layer_object, stops_layer_name, stops_work,
                        field_mappings, "", append="APPEND")

    #Solve the route layer.
    arcpy.na.Solve(layer_object)

    # Get the output Routes sublayer and save it to a feature class
    routes_sublayer = layer_object.listLayers(routes_layer_name)[0]
    arcpy.management.CopyFeatures(routes_sublayer, out_routes_featureclass)

    print("Script completed successfully")

except Exception as e:
    # If an error occurred, print line number and error message
    import traceback, sys
    tb = sys.exc_info()[2]
    print("An error occurred on line %i" % tb.tb_lineno)
    print(str(e))

Environments

Licensing information

  • Basic: Yes
  • Standard: Yes
  • Advanced: Yes

Related topics