Summary
Adds input features or records to a network analysis layer. The inputs are added to specific sublayers such as stops and barriers.
Learn more about how the Add Locations tool locates analysis inputs on the network
Usage
This tool can be run repeatedly to append network analysis objects to the same sublayer. For example, if stops for a route layer come from two feature classes, the tool can be called twice, once for each feature class. The second time, check the Append parameter (append = "APPEND" in Python).
To delete the existing network analysis objects before loading new objects, uncheck the Append parameter (append = "CLEAR" in Python).
When locating inputs, the network analysis layer's travel mode and existing barriers are considered. Consequently, it is recommended that you set the travel mode for the analysis and load barriers before loading other analysis inputs.
This tool runs significantly faster if the feature classes used as the network sources in the network dataset have a valid and up-to-date spatial index.
If your analysis layer references a portal service, the location fields are not calculated until you solve the analysis. For these layers, the Add Locations tool appends the inputs to your analysis layer without calculating location fields. Consequently, some tool parameters do not apply to these layers and will be hidden in the tool dialog box or ignored in Python.
Syntax
arcpy.na.AddLocations(in_network_analysis_layer, sub_layer, in_table, {field_mappings}, {search_tolerance}, {sort_field}, {search_criteria}, {match_type}, {append}, {snap_to_position_along_network}, {snap_offset}, {exclude_restricted_elements}, {search_query})
Parameter | Explanation | Data Type |
in_network_analysis_layer | The network analysis layer to which the network analysis objects will be added. | Network Analyst Layer |
sub_layer | The name of the sublayer of the network analysis layer to which the network analysis objects will be added. | String |
in_table | The feature class or table containing the locations to be added to the network analysis sublayer. | Table View |
field_mappings (Optional) | The mapping between the input fields of the network analysis sublayer to which you're adding locations and the fields in your input data or specified constants. Input sublayers of network analysis layers have a set of input fields that you can modify or populate according to the needs of your analysis. When adding locations to the sublayer, you can use this parameter to map field values from your input table to these fields in the sublayer. You can also use field mappings to specify a constant default value for each property. If neither the Field value nor the Default value is specified for a property, the resulting network analysis objects will have null values for that property. A complete list of input fields for each sublayer for each network analysis layer type is available in the documentation for each layer. For example, examine the Route layer's Stops sublayer's input fields. An NAClassFieldMappings object obtained from the NAClassFieldMappings class is used to specify the parameter value. The NAClassFieldMappings object is a collection of NAClassFieldMap objects that allow you to specify the default values or map a field name from the input features for the properties of the network analysis object. If the data you are loading contains network locations or location ranges based on the network dataset used for the analysis, map the network location fields from your input features to the network location properties. Specifying the network location fields in the field mappings is similar to using the Use Network Location Fields option in the tool dialog box. Learn more about network location fields Caution:If you specify the field mapping for any of the network location properties, you must specify the field mappings for the remaining network location properties to avoid a tool execution error. | Network Analyst Class FieldMap |
search_tolerance (Optional) | The search tolerance that will be used to locate the input features on the network. Features that are outside the search tolerance are left unlocated. The parameter includes a value and units for the tolerance. The default is 5000 meters. The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers. This parameter is not used when the input network analysis layer's network data source is a portal service. | Linear Unit |
sort_field (Optional) | The field on which the network analysis objects are sorted as they are added to the network analysis layer. The default is the ObjectID field in the input feature class or the table. | Field |
search_criteria [[Source, SnapType],...] (Optional) | The sources in the network dataset that will be searched when calculating network locations and the portions of geometry (also known as snap types) that will be used. For example, if the network dataset references separate feature classes representing streets and sidewalks, you can choose to locate inputs on streets but not on sidewalks. The following are the available snap type choices for each network source:
The MIDDLE and END options are maintained for backward compatibility. Use the SHAPE option to locate your inputs on a particular network source; otherwise, use NONE. When calculating locations for line or polygon features, only the SHAPE snap type is used, even if other snap types are specified. The default value is SHAPE for all network sources except override junctions created by running the Dissolve Network tool and system junctions, which have a default of NONE. This parameter is not used when the network data source is a portal service. The parameter value is specified as a list with nested lists. The nested lists are composed of two values indicating the name and snap type of each network source. For example, a parameter value of [["Streets","SHAPE"],["Streets_ND_Junctions","NONE"]] specifies that the search can locate on the shape of the Streets source but not on the Streets_ND_Junctions source. Any network source that is not included in this list will use its default snap type. It is recommended that you include all network sources in your list and explicitly set the snap type for each. For geodatabase network datasets, the snap types can be specified for each subtype of the network source. For example, if the network has a source called Streets, and that source has a subtype called Local Streets, specify the snap type for local streets using ["Streets : Local Streets", "SHAPE"]. | Value Table |
match_type (Optional) | Specifies how the network locations will be matched.
The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers. This parameter is not used when the input network analysis layer's network data source is a portal service. | Boolean |
append (Optional) | Specifies whether new network analysis objects will be appended to existing objects.
| Boolean |
snap_to_position_along_network (Optional) | Specifies whether the inputs will be snapped to their calculated network locations or will be represented at their original geographic location. To use curb approach in your analysis to control which side of the road a vehicle must use to approach a location, do not snap the inputs to their network locations, or use a snap offset to ensure that the point remains clearly to one side of the road. The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers. This parameter is not used when the input network analysis layer's network data source is a portal service. Note:If, after adding locations, you change the network analysis layer's travel mode or add or remove barriers, the network locations of affected points are automatically recalculated at solve time to ensure that they remain valid. This automatic recalculation process will not consider any settings, such as search queries, used previously when calculating network locations. Instead, it uses only the geometry of the input feature and the network analysis layer's travel mode and barriers. To make it more likely that the same network locations will be chosen if the point's network locations are automatically recalculated, use this parameter to snap the inputs to the network locations calculated while running this tool. In this way, the desired network location will be preserved in the geometry of the input point.
| Boolean |
snap_offset (Optional) | When snapping a point to the network, you can apply an offset distance. An offset distance of zero means the point will be coincident with the network feature (typically a line). To offset the point from the network feature, enter an offset distance. The offset is in relation to the original point location; that is, if the original point was on the left side, its new location will be offset to the left. If it was originally on the right side, its new location will be offset to the right. The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers. The default is 5 meters. However, this parameter is ignored if snap_to_position_along_network is set to NO_SNAP. The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers. This parameter is not used when the input network analysis layer's network data source is a portal service. | Linear Unit |
exclude_restricted_elements (Optional) | Specifies whether restricted network elements will be excluded.
This parameter is not used when the input network analysis layer's network data source is a portal service. | Boolean |
search_query [[Source, Expression],...] (Optional) | Defines a query that will restrict the search to a subset of the features in a source feature class. This is useful if you don't want to locate on features that may be unsuitable for your analysis. For example, you can use the query to exclude all features with a particular road class. A separate SQL expression can be specified per source feature class of the network dataset. By default, no query is used for any source. This parameter is not used when the network data source is a portal service. The parameter value is specified as a list of nested lists. The nested lists are composed of two values indicating the name and the SQL expression for all of the network sources. For more information on SQL syntax, see SQL reference for query expressions used in ArcGIS. Any network source not included in this list will have no query applied. Similarly, an expression specified as an empty string will also be interpreted as no query. For example, the parameter value [["Streets", "\"CFCC\" = 'A15'"], ["Streets_ND_Junctions", ""]] specifies a query for the Streets source feature class to only locate inputs on streets where the CFCC field has a value of A15. No query is applied to the Streets_ND_Junctions source feature class. | Value Table |
Derived Output
Name | Explanation | Data Type |
output_layer | The updated network analysis layer. | Network Analyst Layer |
Code sample
Execute the tool using only the required parameters.
hospitals = "C:/Data/SanFrancisco.gdb/Analysis/Hospitals"
arcpy.na.AddLocations("Route", "Stops", hospitals, "", "")
Execute the tool using all parameters.
hospitals = "C:/Data/SanFrancisco.gdb/Analysis/Hospitals"
arcpy.na.AddLocations("Route", "Stops", hospitals,
"Name Name #;Attr_Minutes VisitTime 0;CurbApproach # 0",
"2 Miles", "FID",
[["Streets", "SHAPE"], ["Streets_ND_Junctions", "NONE"]],
"MATCH_TO_CLOSEST", "CLEAR", "SNAP", "10 Feet", "EXCLUDE",
[["Streets", '"FREEWAY" = 0'],
["Streets_ND_Junctions", ""]])
The following stand-alone Python script demonstrates how the AddLocations tool can be used to load origins and destinations into an OD Cost Matrix layer.
Legacy:
The GetNASublayer function can be used to retrieve the sublayers of a network analysis layer. It was introduced in ArcGIS Pro 2.7. In prior software versions, the best way to retrieve a sublayer object of a network analysis layer was to use the listLayers method of the network analysis Layer object using the sublayer name as a wildcard.
# Name: AddLocations_Workflow.py
# Description: Calculate a travel time matrix between stores. Use the Add
# Locations tool to load origins and destinations into an OD Cost
# Matrix layer. Since the origins and destinations are the same in
# this case, the origins are first loaded from the stores feature
# class using geometry, and the destinations are loaded from the
# origins using network location fields in order to speed up the
# load times.
# 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 inputs and outputs
input_gdb = "C:/Data/SanFrancisco.gdb"
network = os.path.join(input_gdb, "Transportation", "Streets_ND")
layer_name = "StoreTravelTimeMatrix"
travel_mode = "Driving Time"
stores = os.path.join(input_gdb, "Analysis", "Stores")
search_tolerance = "500 Meters"
search_query = [["Streets", '"FREEWAY" = 0'], ["Streets_ND_Junctions", ""]]
output_layer_file = os.path.join(output_dir, layer_name + ".lyrx")
# Create a new OD cost matrix analysis layer. For this scenario, the default
# value for all the remaining parameters statisfies the analysis requirements
result_object = arcpy.na.MakeODCostMatrixAnalysisLayer(network, layer_name,
travel_mode)
# Get the layer object from the result object. The OD cost matrix layer can
# now be referenced using the layer object.
layer_object = result_object.getOutput(0)
# Get the names of all the sublayers within the OD layer.
sublayer_names = arcpy.na.GetNAClassNames(layer_object)
# Store the layer names for later use
origins_layer_name = sublayer_names["Origins"]
destinations_layer_name = sublayer_names["Destinations"]
# Load store features as origins using the geometry of store features.
# Ensure that the stores are not located on freeways by using a search query.
arcpy.na.AddLocations(layer_object, origins_layer_name, stores, "",
search_tolerance,
exclude_restricted_elements="EXCLUDE",
search_query=search_query)
# Because we want our origins and destinations to be the same, load the
# origins as destinations using the network locations fields. Loading using
# existing network location fields is much faster than loading using geometry
# because the network locations have already been calculated.
# Create a field mappings object that supports network location fields using
# the candidate fields from origins
origins_sublayer = arcpy.na.GetNASublayer(layer_object, "Origins")
candidate_fields = arcpy.ListFields(origins_sublayer)
field_mappings = arcpy.na.NAClassFieldMappings(layer_object,
destinations_layer_name, True,
candidate_fields)
arcpy.na.AddLocations(layer_object, destinations_layer_name,
origins_sublayer, field_mappings, "")
# Solve the od cost matrix layer. Halt the execution if there is an
# invalid location
arcpy.na.Solve(layer_object, "HALT")
# Save the solved OD cost matrix 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))
Environments
Licensing information
- Basic: Yes
- Standard: Yes
- Advanced: Yes