Skip To Content

Add Locations

Summary

Adds network analysis objects to a network analysis layer. The objects are added to specific sublayers such as Stops and Barriers. Objects are input as features or records.

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

  • If you want 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_na (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

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 the table that is the source for the new network analysis objects.

Table View
field_mappings

Sets 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 NAClassFieldMappings class is used to specify the parameter value. The NAClassFieldMappings object is a collection of NAClassFieldMap objects that allows 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 need to specify the field mappings for the remaining network location properties to avoid a tool execution error.

Network Analyst Class FieldMap
search_tolerance

The search tolerance for locating 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 parameter is not used when adding locations to the Line Barriers or Polygon Barriers sublayers. In such cases, use "#" as the parameter value.

Linear Unit
sort_field
(Optional)

A 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)

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

The parameter value is specified as a list with nested lists. The nested list is made up 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.

Value Table
match_type
(Optional)
  • MATCH_TO_CLOSESTMatches the new network locations to the closest network source among all the sources that have a snap type specified in the search criteria. This is the default.
  • PRIORITYMatches the new network locations 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 the Line Barriers or Polygon Barriers sublayers. In such cases, use "#" as the parameter value.

Boolean
append
(Optional)

Specifies whether or not to append new network analysis objects to existing objects.

  • APPENDAdds the new network analysis objects to the existing set of objects in the selected sublayer.
  • CLEARDeletes the existing network analysis objects and replaces them with the new objects.
Boolean
snap_to_position_along_network
(Optional)

Specifies that you want to snap the network locations 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 know which side of the edge they are on.
  • SNAP if you have point features, the point will be snapped to the network and you will not be able to use curb approach. This is useful if you don't care 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 the Line Barriers or Polygon Barriers sublayers. In such cases, use "#" as the parameter value.

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 the Line Barriers or Polygon Barriers sublayers. In such cases, use "#" as the parameter value.

Linear Unit
exclude_restricted_elements
(Optional)
  • EXCLUDESpecifies that the network locations are only 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 your network locations using this option, make sure that you have already 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.
  • INCLUDESpecifies that the network locations are placed on all the elements of the network. The network locations that are added with this option may be unreachable during the solve process if they are placed on restricted elements.
Boolean
search_query
[[Source, Expression],...]
(Optional)

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.

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.

Value Table

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

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

Related topics