Add Locations (Network Analyst)

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 using the APPEND option.

  • To delete the existing network analysis objects before loading new ones, use the CLEAR option.

  • 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.

Syntax

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})
ParameterExplanationData Type
in_network_analysis_layer

The network analysis layer to which the network analysis objects will be added.

Network Analyst Layer
sub_layer

The sublayer of the network analysis layer to which the network analysis objects will be added.

String
in_table

The feature class or table that will be the source for the new network analysis objects.

Table View
field_mappings
(Optional)

The values for the properties of the network analysis objects. Properties can be set to a constant or mapped to a field from the input feature class or table.

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 instead of geometry parameter from the tool dialog box.

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.

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 on the input feature class or the table.

Field
search_criteria
[[Source, SnapType],...]
(Optional)

The sources in the network dataset that will be searched when finding locations and the portions of geometry (also known as snap types) that will be used.

The parameter value is specified as a list with nested lists. The nested list is composed of two values indicating the name and the snap type for each network source. The snap type is specified using the SHAPE, MIDDLE, END, or NONE keyword.

  • SHAPE—The point will locate on the closest point of an element in this network source.
  • MIDDLE—The point will locate on the closest midpoint of an element in this network source.
  • END—The point will locate on the closest endpoint of an element in this network source.
  • NONE—The point will not locate on elements in this network source.
For example, when finding locations, the parameter value [["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.

To specify multiple snap types for a single network source, use the combination of the snap type keywords separated by an underscore. For example, MIDDLE_END specifies that the locations can be snapped to the middle or end of the network source.

When adding line or polygon network locations, only the SHAPE snap type is used, even if other snap types are specified.

Any network source not included in this list will use its default snap type. It is safest to include all network sources in your list and explicitly set the snap type for each.

The default value is SHAPE for all network sources except system junctions, which has a default of NONE.

Value Table
match_type
(Optional)

Specifies how the network locations will be matched.

  • MATCH_TO_CLOSESTThe new network locations will be matched to the closest network source among all the sources that have a snap type specified in the search criteria. This is the default.
  • PRIORITYThe new network locations will be matched to the first network source having a snap type specified in the search criteria. The sources are searched in the priority order, and the searching stops when the location is found within the search tolerance.

The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers.

Boolean
append
(Optional)

Specifies whether new network analysis objects will be appended to existing objects.

  • APPENDThe new network analysis objects will be appended to the existing set of objects in the selected sublayer. This is the default.
  • CLEARThe existing network analysis objects will be deleted and replaced with the new objects.
Boolean
snap_to_position_along_network
(Optional)

Specifies whether the network locations will be snapped along the network dataset or at some specified offset from the network dataset.

  • NO_SNAP The geometries of the network locations are based on the geometries of the input features. This is useful if you want to use the curb approach, which requires that the network locations identify which side of the edge they are on. This is the default.
  • SNAPIf there are point features, the points will be snapped to the network, and you cannot use the curb approach. This is useful if you need to know how a vehicle approaches a stop. If your input features are lines or polygons, use this parameter value.

The parameter is not used when adding locations to sublayers with line or polygon geometry, such as Line Barriers and Polygon Barriers.

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.

Linear Unit
exclude_restricted_elements
(Optional)

Specifies whether restricted network elements will be excluded.

  • EXCLUDEThe network locations will only be placed on traversable portions of the network. This prevents placing network locations on elements that you can't reach due to restrictions or barriers. Before adding network locations using this option, ensure that you added all the restriction barriers to the input network analysis layer to get expected results. This parameter is not applicable when adding barrier objects. In such cases, use "#" as the parameter value. This is the default.
  • INCLUDEThe network locations will be placed on all the elements of the network. The network locations that are added with this parameter may be unreachable during the solve process if they are placed on restricted elements.
Boolean
search_query
[[Source, Expression],...]
(Optional)

A query that will restrict the search to a subset of the features within a source feature class. This is useful if you want to exclude 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.

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, or shapefiles, enclose field names in double quotation marks: "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.

Value Table

Derived Output

NameExplanationData Type
output_layer

The updated network analysis layer.

Network Analyst Layer

Code sample

AddLocations example 1 (Python window)

Execute the tool using only the required parameters.

hospitals = "C:/Data/SanFrancisco.gdb/Analysis/Hospitals"
arcpy.na.AddLocations("Route", "Stops", hospitals, "", "")
AddLocations example 2 (Python window)

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", ""]])
AddLocations example 3 (workflow)

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.

# 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 = layer_object.listLayers(origins_layer_name)[0]
    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

Related topics