Add Locations (Network Analyst)

License Level:BasicStandardAdvanced

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

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.

CautionCaution:

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.

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

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

Environments

Related Topics

Licensing Information

ArcGIS for Desktop Basic: Yes
ArcGIS for Desktop Standard: Yes
ArcGIS for Desktop Advanced: Yes
1/20/2015