Skip To Content

Make Route Analysis Layer

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 using 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 layers store their data on disk in file geodatabase feature classes. When creating a new 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 new 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_na (network_data_source, {layer_name}, {travel_mode}, {sequence}, {time_of_day}, {time_zone}, {line_shape}, {accumulate_attributes})
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)

Name of the network analysis layer to create.

String
travel_mode
(Optional)

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)

Specifies a 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 a.m. could be used to find a route that considers the 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 time 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. Furthermore, 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 only the route shapes are different, not the underlying traversal of the network.

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

List of cost attributes to be accumulated during analysis. These accumulated attributes are purely for reference; the solver only uses the cost attribute used by your designated travel mode when solving your 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 a service.

String

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

  • ArcGIS Desktop Basic: Yes
  • ArcGIS Desktop Standard: Yes
  • ArcGIS Desktop Advanced: Yes

Related topics