Add Locations (Network Analyst)
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.
When adding moving points, such as GPS coordinates captured from a receiver mounted on a vehicle, use the bearing readings and a bearing tolerance to more accurately locate the points on the network.
Syntax
Parameter | Explanation | Data 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 keywords. 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. | Value Table |
match_type (Optional) |
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.
| 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.
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) |
| 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 made up 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 ArcSDE geodatabases, shapefiles, or SDC, enclose field names in double quotes: "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 Streets_ND_Junctions source feature class. Note that the double quotes used to enclose the field name CFCC are escaped using back slash characters to avoid a parsing error from the Python interpreter. | Value Table |
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.
# Name: AddLocations_Workflow.py
# Description: The scenario shows how to calculate a travel time matrix between
# store features. 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 store features using their geometry and the destinations
# are loaded from the origins using network location fields to
# speed up the load times.
# Requirements: Network Analyst Extension
#Import system modules
import arcpy
from arcpy import env
try:
#Check out the Network Analyst extension license
arcpy.CheckOutExtension("Network")
#Set environment settings
env.workspace = "C:/data/SanFrancisco.gdb"
env.overwriteOutput = True
#Set local variables
inNetworkDataset = "Transportation/Streets_ND"
outNALayerName = "StoreTravelTimeMatrix"
impedanceAttribute = "TravelTime"
inFeatures = "Analysis/Stores"
searchTolerance = "500 Meters"
searchQuery = [["Streets",'"FREEWAY" = 0'],["Streets_ND_Junctions",""]]
odOrigins = "Origins"
outLayerFile = "C:/data/output" + "/" + outNALayerName + ".lyr"
#Create a new OD cost matrix analysis layer. For this scenario, the default
#value for all the remaining parameters statisfies the analysis requirements
outNALayer = arcpy.na.MakeODCostMatrixLayer(inNetworkDataset, outNALayerName,
impedanceAttribute)
#Get the layer object from the result object. The OD cost matrix layer can
#now be referenced using the layer object.
outNALayer = outNALayer.getOutput(0)
#Get the names of all the sublayers within the OD cost matrix layer.
subLayerNames = arcpy.na.GetNAClassNames(outNALayer)
#Stores the layer names that we will use later
originsLayerName = subLayerNames[odOrigins]
destinationsLayerName = subLayerNames["Destinations"]
#Get the origin layer object from within the OD cost matrix layer
#The first layer returned by ListLayers is the OD cost matrix layer itself
#which we don't want to use.
for layer in arcpy.mapping.ListLayers(outNALayer)[1:]:
if layer.datasetName == odOrigins:
originsLayer = layer
break
else:
raise Exception("Failed to get the origins layer object.")
#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.
#The OD cost matrix layer created previously is referred using its name.
arcpy.na.AddLocations(outNALayer,originsLayerName,inFeatures,"",
searchTolerance, exclude_restricted_elements = "EXCLUDE",
search_query = searchQuery)
#Load origins as destinations using the network locations fields from
#origins. This is much faster than loading destinations from the store
#features using their geometry as their network locations have already been
#calculated while loading them origins.
#Create a field mappings object that supports network location fields from
#origins layer using the candidate fields from origins
originsLayer = arcpy.management.MakeFeatureLayer(originsLayer,
outNALayerName+originsLayerName)
candidateFields = arcpy.ListFields(originsLayer.getOutput(0))
fieldMappings = arcpy.na.NAClassFieldMappings(outNALayer,
destinationsLayerName, True,
candidateFields)
arcpy.na.AddLocations(outNALayer,destinationsLayerName,originsLayer,
fieldMappings,"")
#Solve the od cost matrix layer. Halt the execution if there is an
#invalid location
arcpy.na.Solve(outNALayer,"HALT")
#Save the solved na layer as a layer file on disk with relative paths
arcpy.management.SaveToLayerFile(outNALayer,outLayerFile,"RELATIVE")
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 occured on line %i" % tb.tb_lineno
print str(e)