Route

Resumen

An ArcPy class for performing a route analysis.

Debate

A route analysis allows you to calculate the shortest path along a network between a sequence of stops.

Learn more about route analysis

Sintaxis

Route (in_network)
ParámetroExplicaciónTipo de datos
in_network

The network dataset or service that will be used for the network analysis. The argument can be specified using the catalog path to the network dataset, a network dataset layer object, the string name of the network dataset layer, or a portal URL for a network analysis service. The network must have at least one travel mode.

To use a portal URL, you must be signed in to the portal with an account that has routing privileges.

Solving an analysis will consume credits when the object uses ArcGIS Online as the in_network. For more information, see Service Credits Overview

String

Propiedades

PropiedadExplicaciónTipo de datos
accumulateAttributeNames
(Lectura y escritura)

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.

The default is an empty list.

String
allowSaveLayerFile
(Lectura y escritura)

Specifies whether to permit saving the analysis result as a layer file using the saveAsLayerFile method on the result object. A value of True means that you can save a layer file. A value of False means that you cannot. The default is True if the analysis references a network dataset and False if it references a portal service. Allowing a layer file to be saved may slow down the analysis when the analysis references a portal service.

Boolean
allowSaveRouteData
(Lectura y escritura)

Specifies whether to permit saving the analysis result to a ZIP file using the saveRouteData method on the result object. A value of True means that you can save the route data. A value of False means that you cannot. The default is True if the analysis references a network dataset and False if it references a portal service. Allowing the route data to be saved may slow down the analysis when the analysis references a portal service.

Boolean
directionsDistanceUnits
(Lectura y escritura)

The units to use when reporting travel distance in the output turn-by-turn directions. The property is returned and set as a member of the DistanceUnits enumeration and is applicable only when the returnDirections property is True. The default is the units of the distance attribute in the travel mode used for the analysis.

Object
directionsLanguage
(Lectura y escritura)

The language in which the output turn-by-turn directions text will appear. The property is returned and set as a string using one of the two- or five-character language codes representing supported directions languages. The list of available directions languages can be obtained from the arcpy.nax.ListDirectionsLanguages function. The default value is either en (English) or the language of the currently activated language pack. The property is applicable only when the returnDirections property is True.

String
directionsStyle
(Lectura y escritura)

The style to be used for the output turn-by-turn directions text. The property is returned and set as a member of the DirectionsStyle enumeration and is applicable only when the returnDirections property is True.

The default value is Desktop.

Object
distanceUnits
(Lectura y escritura)

The units to use when reporting the travel distance in the analysis output. Regardless of the units of the cost attributes in the network dataset, the output will be transformed to and reported in the units set in this property. The property is returned and set as a member of the DistanceUnits enumeration. The default is DistanceUnits.Kilometers.

Object
findBestSequence
(Lectura y escritura)

A value of False indicates that the stops should be visited in the order specified in the input. A value of True indicates that the input stops should be reordered to minimize the overall travel cost. This option changes the route analysis from a shortest-path problem to a traveling salesperson problem (TSP). The default is False.

Boolean
ignoreInvalidLocations
(Lectura y escritura)

Specifies whether invalid input locations will be ignored. A value of True indicates that invalid input locations will be ignored so that the analysis will succeed using only valid locations. A value of False indicates that invalid locations will not be ignored and will cause the analysis to fail.

Heredado:

Routing services based on portals running versions of ArcGIS Enterprise older than 10.9 always ignore invalid input locations. The method returns a ValueError exception if you set ignoreInvalidLocations to False and the service does not support this option.

Boolean
networkDataSource
(Sólo lectura)

The full catalog path to the network dataset used for the analysis.

String
overrides
(Lectura y escritura)

Specify additional settings that can influence the behavior of the solver when finding solutions for the network analysis problems.

The value for this parameter must be specified in JavaScript Object Notation (JSON). For example, a valid value is of the following form: {"overrideSetting1" : "value1", "overrideSetting2" : "value2"}. The override setting name is always enclosed in double quotation marks. The values can be either a number, Boolean, or string.

The default value for this parameter is no value, which indicates to not override any solver settings.

Overrides are advanced settings that should be used only after careful analysis of the results obtained before and after applying the settings. A list of supported override settings for each solver and their acceptable values can be obtained by contacting Esri Technical Support.

String
preserveFirstStop
(Lectura y escritura)

When stops are reordered because the findBestSequence property is set to True, a value of True for this property preserves the order of the first stop. The rest of the stops will be reordered to find the optimal route. This is useful if the route begins at a garage or depot. The default is False.

Boolean
preserveLastStop
(Lectura y escritura)

When stops are reordered because the findBestSequence property is set to True, a value of True for this property preserves the order of the last stop. The rest of the stops will be reordered to find the optimal route. This is useful if the route must end at a garage or depot. The default is False.

Boolean
returnDirections
(Lectura y escritura)

Specifies whether turn-by-turn directions will be generated. A value of True means that turn-by-turn directions will be generated when solving the analysis. A value of False means that directions will not be generated. Generating directions may slow down the analysis. The default is False.

Boolean
returnRouteEdges
(Lectura y escritura)

Specifies whether route edges will be returned. Route edges are the individual segments of a route indicating which network edges were traversed. A value of True means that route edges will be saved and returned when solving the analysis. A value of False means that route edges will not be preserved. The default is True if the Route object references a network dataset and False if it references a portal service. Returning route edges may slow down the analysis when the analysis references a portal service.

Boolean
returnRouteJunctions
(Lectura y escritura)

Specifies whether network junctions traversed by the route will be returned. A value of True means that junctions will be saved and returned when solving the analysis. A value of False means that junctions will not be preserved. The default is True if the Route object references a network dataset and False if it references a portal service. Portal services do not support returning junctions.

Boolean
returnRouteTurns
(Lectura y escritura)

Specifies whether network turns traversed by the route will be returned. A value of True means that turns will be saved and returned when solving the analysis. A value of False means that turns will not be preserved. The default is True if the Route object references a network dataset and False if it references a portal service. Portal services do not support returning turns.

Boolean
returnToStart
(Lectura y escritura)

A value of True indicates that the route should return to the starting location at the end of the route. A value of False means that the route will end with the final stop. The default is False.

Boolean
routeShapeType
(Lectura y escritura)

The type of shape to be generated to represent output routes. The routes are always calculated along the network; however, you can choose to represent them by shapes that do not reflect the network paths. The property is returned and set as a member of the RouteShapeType enumeration. The default is RouteShapeType.TrueShapeWithMeasures.

Object
searchQuery
(Lectura y escritura)

When locating inputs on the network, specifies a query to restrict the search to a subset of the features within a source feature class. This is useful if you don't want to find features that may be unsuited for a network location. For example, if you are loading centroids of polygons and don't want to locate on local roads, you can define a query that searches for major roads only.

Learn more about locating inputs on the network

The parameter value is specified as a list with nested lists. The nested list is composed of two values indicating the name and the SQL expression for all of the network sources. The syntax for the SQL expression differs slightly depending on the type of the network source feature class. For example, if you're querying source feature classes stored in file or enterprise geodatabases, shapefiles, or SDC, enclose field names in double quotation marks: "CFCC". If you're querying source feature classes stored in personal geodatabases, enclose fields in square brackets: [CFCC].

If you don't want to specify a query for a particular source, use "#" as the value for the SQL expression or exclude the source name and the SQL expression from the parameter value. If you don't want to specify a query for all of the network sources, use "#" as the parameter value.

For example, the parameter value [["Streets","\"CFCC\" = 'A15'"], ["Streets_ND_Junctions",""]] specifies an SQL expression for the Streets source feature class and no expression for the Streets_ND_Junctions source feature class. Note that the double quotation marks used to enclose the field name CFCC are escaped using backslash characters to avoid a parsing error from the Python interpreter.

By default, no query is used.

List
searchTolerance
(Lectura y escritura)

The maximum search distance to use when locating the input features on the network. The property is returned and set as a double, and the units of this value are accessed through the searchToleranceUnits property. The default is 5000.

Learn more about locating inputs on the network

Double
searchToleranceUnits
(Lectura y escritura)

The units of the searchTolerance property. The property is returned and set as a member of the DistanceUnits enumeration. The default is DistanceUnits.Meters.

Object
timeOfDay
(Lectura y escritura)

The time of day to use for the analysis. The default is None, which means that the analysis will be time neutral.

DateTime
timeUnits
(Lectura y escritura)

The units to use when reporting the travel time in the analysis output. Regardless of the units of the cost attributes in the network dataset, the outputs will be transformed to and reported in the units set in this property. The property is returned and set as a member of the TimeUnits enumeration. The default is TimeUnits.Minutes.

Object
timeZone
(Lectura y escritura)

Indicates whether the time specified in the timeOfDay property will be interpreted as the local time at the input locations or as coordinated universal time (UTC). The property is returned and set as a member of the TimeZoneUsage enumeration and is applicable only when the timeOfDay property is not None. The default is TimeZoneUsage.LocalTimeAtLocations.

Object
timeZoneForTimeWindows
(Lectura y escritura)

Indicates whether the times specified in the time windows of the input stops should be interpreted as the local time at the input locations or as Coordinated Universal Time (UTC). The property is returned and set as a member of the TimeZoneUsage enumeration. The default is TimeZoneUsage.LocalTimeAtLocations.

Object
travelMode
(Lectura y escritura)

The travel mode to use for the analysis.

The value is returned and set as an arcpy.nax.TravelMode object, but it can also be set using the string name of the travel mode or a string containing the valid JSON representation of a travel mode. The default is the default travel mode defined on the network dataset used for the analysis.

Learn more about travel modes

Object

Descripción general del método

MétodoExplicación
addFields (input_type, field_description)

Adds custom fields to the designated input class. These fields will be included in the field mapping dictionary created by the fieldMappings method and will also be available for use with the insertCursor method.

count (input_type)

Returns the number of rows added for an input type.

fieldMappings (input_type, {use_location_fields}, {list_candidate_fields})

Generates an NAClassFieldMappings dictionary that maps the field names of the input type to arcpy.nax.NAClassFieldMap objects that allow you to map fields from your input data to the properties of the solver. The dictionary can be used as input to the load method's field_mappings argument.

fieldNames (input_type, {use_location_fields})

Get a list of field names supported by the specified input type.

insertCursor (input_type, field_names, {append})

Establishes a write cursor on the specified input type. This cursor can be used to add rows directly to the input.

load (input_type, features, {field_mappings}, {append}, {max_features})

Set input features to use for the analysis.

solve ()

Perform the route analysis using the properties set on the Route object and the loaded inputs.

Métodos

addFields (input_type, field_description)
ParámetroExplicaciónTipo de datos
input_type

The type of input to which the fields should be added.

The parameter should be set using the RouteInputDataType enumeration.

Object
field_description
[field_description,...]

The fields and their properties that will be added to the input class. The value should be constructed as a list of lists with each row containing the following items:

  • Field name—The name of the field that will be added to the input class.
  • Field type—The type of the new field.
  • Field alias—The alternate display name given to the field name.
  • Field length—The length of the field being added. This sets the maximum number of allowable characters for each record of the field. This option is only applicable to fields of type text; the default length is 255.
  • Default value—The default value of the field.
  • Field domain—The geodatabase domain that will be assigned to the field.

Available field types are as follows:

  • TEXT—Any string of characters.
  • FLOAT—Fractional numbers between -3.4E38 and 1.2E38.
  • DOUBLE—Fractional numbers between -2.2E308 and 1.8E308.
  • SHORT—Whole numbers between -32,768 and 32,767.
  • LONG—Whole numbers between -2,147,483,648 and 2,147,483,647.
  • DATE—Date or time.

The method will return an error if the field already exists in the table or if any of the field properties are invalid.

List
count (input_type)
ParámetroExplicaciónTipo de datos
input_type

The type of input features to count.

The parameter should be set using the RouteInputDataType enumeration.

Object
Valor de retorno
Tipo de datosExplicación
Integer

The number of rows.

fieldMappings (input_type, {use_location_fields}, {list_candidate_fields})
ParámetroExplicaciónTipo de datos
input_type

The type of input for which the field mappings are returned.

The parameter should be set using the RouteInputDataType enumeration.

See descriptions of the fields available for each input type

Object
use_location_fields

Indicates whether network location fields should be included in the returned field mappings dictionary. Network location fields describe the point on the network where an object is located. You can use network location fields to more precisely control how your analysis inputs locate on the network and to save time when calling the solve method because the solver will not have to calculate the location fields from the geometry of the inputs. You can calculate location fields for a feature class using the Calculate Locations tool.

Learn more about network location fields and how inputs are located on the network

When this argument is set to True, the returned field mappings dictionary will contain network location fields. The default is False; the field mapping dictionary will not include network location fields.

(El valor predeterminado es False)

Boolean
list_candidate_fields
[list_candidate_fields,...]

Use this parameter to map additional, non-default fields from your input data into your analysis inputs. For example, if your input feature class contains a field named MyField, and you want this field to be included in your analysis inputs, pass the MyField field object to the list_candidate_fields parameter. MyField will be included in the returned field mapping dictionary and automatically mapped. When you call the load method using these field mappings, MyField will be included in the analysis inputs along with all the default fields. In many cases, these extra fields will be passed to the analysis output as well.

The parameter should be specified as a list of arcpy.Field objects, which can be obtained from a given feature class or table using the arcpy.ListFields function.

Learn more about best practices for setting up analysis inputs

(El valor predeterminado es None)

Field
Valor de retorno
Tipo de datosExplicación
Dictionary

An NAClassFieldMappings dictionary in which the keys are the field names and values are arcpy.nax.NAClassFieldMap objects.

fieldNames (input_type, {use_location_fields})
ParámetroExplicaciónTipo de datos
input_type

The type of input for which the supported field names are returned.

The parameter should be set using the RouteInputDataType enumeration.

See descriptions of the fields available for each input type

Object
use_location_fields

Indicates whether network location fields will be included in the returned list of field names. Network location fields describe the point on the network where an object is located. You can use network location fields to more precisely control how your analysis inputs locate on the network and to save time when calling the solve method because the solver will not have to calculate the location fields from the geometry of the inputs. You can calculate location fields for a feature class using the Calculate Locations tool.

Learn more about network location fields and how inputs are located on the network

When this argument is set to True, the returned list of field names will contain network location fields. The default is False; the list of field names will not include network location fields.

(El valor predeterminado es False)

Boolean
Valor de retorno
Tipo de datosExplicación
String

A list of field names supported by the specified input type.

insertCursor (input_type, field_names, {append})
ParámetroExplicaciónTipo de datos
input_type

The type of input into which the cursor can be used to insert rows.

The parameter should be set using the RouteInputDataType enumeration.

Object
field_names
[field_names,...]

A list of field names of the input type whose values you want to set when inserting rows using the cursor. You can get the names of the fields supported by an input type by using the fieldNames method.

See descriptions of the fields available for each input type

In addition to regular fields, you can also set the geometry of the input using one of the following geometry tokens:

  • SHAPE@XYUna tupla de las coordenadas x,y del centroide de la entidad.
  • SHAPE@XYZUna tupla de las coordenadas x, y, z del centroide de la entidad.
  • SHAPE@JSONLa cadena de caracteres JSON de Esri que representa la geometría.
  • SHAPE@WKBRepresentación binaria conocida (WKB) para geometría OGC. Ofrece una representación portátil de un valor de geometría como una transmisión contigua de bytes.
  • SHAPE@WKTRepresentación en texto conocida (WKB) para geometría OGC. Ofrece una representación portátil de un valor de geometría como cadena de caracteres.
  • SHAPE@Objeto de geometría para la entidad.

The SHAPE@XY and SHAPE@XYZ tokens are only supported for point-based input types. When using the SHAPE@XY and SHAPE@XYZ tokens, the x-, y-, and z-values should be specified in the spatial reference of the network data source being used in the analysis.

String
append

Specifies whether the features being inserted should be appended to the existing set of features for the input type. A value of True indicates that the new features should be appended; the existing features will be preserved. This is the default. A value of False indicates that any existing features for the input type should be deleted and replaced with the features currently being inserted.

(El valor predeterminado es True)

Boolean
Valor de retorno
Tipo de datosExplicación
Object

A SolverInsertCursor object that can be used to write features.

load (input_type, features, {field_mappings}, {append}, {max_features})
ParámetroExplicaciónTipo de datos
input_type

The type of input feature to load.

The parameter should be set using the RouteInputDataType enumeration.

Object
features

The input features to load. This parameter accepts the following input types:

  • Catalog path to a feature class or a table
  • Layer object
  • String representing the name of a layer
  • FeatureSet or RecordSet object

For layer inputs, only selected features will be loaded. If a layer has a definition query, only the subset of features visible with the definition query will be loaded. The method also honors the Extent geoprocessing environment; only features in the specified extent will be loaded.

String
field_mappings

An NAClassFieldMappings dictionary that maps the field names of the input type to arcpy.nax.NAClassFieldMap objects representing the mapping of fields from the input features. Valid input for this parameter can be constructed using the fieldMappings method.

If field mappings are not specified, all fields from the input features that have the same name as the supported fields for the input type will be mapped.

(El valor predeterminado es None)

Dictionary
append

Indicates whether the features being loaded should be appended to the existing set of features for the input type. A value of True indicates that the new features should be appended; the existing features will be preserved. This is useful if you want to load inputs from multiple feature classes or tables to use in a single analysis. This is the default. A value of False indicates that any existing features for the input type should be deleted and replaced with the features currently being loaded.

(El valor predeterminado es True)

Boolean
max_features

The maximum number of features that can be loaded into the input type. This is useful if you are creating a tool or service and want an error returned if the size of the input exceeds the available resources. The load method will return an arcpy.nax.LimitError if the number of input features exceeds the max_features limit.

If a value is not specified, no limit is enforced for the count of the input features.

(El valor predeterminado es None)

Integer
solve ()
Valor de retorno
Tipo de datosExplicación
Object

An arcpy.nax.RouteResult object that can be used to access outputs and solver messages.

Muestra de código

Route example

Perform route analysis using a feature class for input stops.

# An example showing how to perform route analysis using a feature class for input stops.
import arcpy
arcpy.CheckOutExtension("network")

nds = "C:/data/NorthAmerica.gdb/Routing/Routing_ND"
nd_layer_name = "Routing_ND"
input_stops = "C:/data/io.gdb/Stops"
output_routes = "C:/data/io.gdb/Routes"

# Create a network dataset layer and get the desired travel mode for analysis
arcpy.nax.MakeNetworkDatasetLayer(nds, nd_layer_name)
nd_travel_modes = arcpy.nax.GetTravelModes(nd_layer_name)
travel_mode = nd_travel_modes["Driving Time"]

# Instantiate a Route solver object
route = arcpy.nax.Route(nd_layer_name)
# Set properties
route.timeUnits = arcpy.nax.TimeUnits.Minutes
route.travelMode = travel_mode
route.routeShapeType = arcpy.nax.RouteShapeType.TrueShapeWithMeasures
# Load inputs
route.load(arcpy.nax.RouteInputDataType.Stops, input_stops)
# Solve the analysis
result = route.solve()

# Export the results to a feature class
if result.solveSucceeded:
    result.export(arcpy.nax.RouteOutputDataType.Routes, output_routes)
else:
    print("Solved failed")
    print(result.solverMessages(arcpy.nax.MessageSeverity.All))