Network Analyst - Pyhton export sublayers to a FeatureClass, each one.

2881
2
Jump to solution
01-15-2016 04:08 PM
Jose_LuisGarcinuno-Oporto
New Contributor III

This is my problem: How I can export to a feature class my sublayer Routes from outNALayer.

I been able to export just the tabular data but NOT the geometry. Down below is the code or part of the script.

Thanks

# Process: Create a Closest Facility Layer. Optimize on Travel Time but  compute the distance traveled by accumulating the meters attribute.

    outRouteResultObject = arcpy.na.MakeClosestFacilityLayer(Transportation_ND, "Closest_Facility", "Miles", "TRAVEL_TO", "", "1", "Miles", "ALLOW_UTURNS", "Oneway", "NO_HIERARCHY", "", "NO_LINES", "", "NOT_USED")

    print "Creating Closest Facility Layer"

    # Get the layer object from the result object. The route layer can now be referenced using the layer object.

    outNALayer = outRouteResultObject.getOutput(0)

    print "outNALayer : " + str(outNALayer)

    # Get the names of all sublayers within the route layer.

    subLayerNames = arcpy.na.GetNAClassNames(outNALayer)

    print "subLayerNames : " + str(subLayerNames)

    # Store the layer names that we will use later - Facilities

    facilityLayerName = subLayerNames["Facilities"]

    print "facilityLayerName : " + str(facilityLayerName)

    # Store the layer names that we will use later - incidents

    incidentsLayerName = subLayerNames["Incidents"]

    print "incidentsLayerName : " + str(incidentsLayerName)

    # Store the layer names that we will use later

    routeLayerName = subLayerNames["CFRoutes"]

    print "routeLayerName : " + str(routeLayerName)

# Process: Add destination points.

    arcpy.na.AddLocations(outRouteResultObject, facilityLayerName, Facilities, "", "1000 Meters", "", "test_area SHAPE;Transportation_ND_Junctions NONE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "test_area #;Transportation_ND_Junctions #")

    print "Adding Faclitities to the Closest Facility layer"

   

    # Process: Add Origin points.

    arcpy.AddLocations_na(outRouteResultObject, incidentsLayerName, Incidents, "", "1000 Meters", "", "test_area SHAPE;Transportation_ND_Junctions NONE", "MATCH_TO_CLOSEST", "CLEAR", "NO_SNAP", "5 Meters", "INCLUDE", "test_area #;Transportation_ND_Junctions #")

    print "Adding Incidents to the Closest Facilty layer"

   

    # Process: Solve

    arcpy.na.Solve(outNALayer, "SKIP", "TERMINATE", "")

    print "Solving the Problem"

     RoutesSubLayer = arcpy.mapping.ListLayers(outNALayer,routeLayerName)[0]

    print "Selected sublayer : " + str(RoutesSubLayer)

        #arcpy.FeatureClassToFeatureClass_conversion(RoutesSubLayer, network)

0 Kudos
1 Solution

Accepted Solutions
FreddieGibson
Regular Contributor II

The below snippet should be enough to get you started. It shows how I'm able to export each sublayer of the network analyst layer to its own feature class. I modified this sample from the online sample.

# Name: MakeRouteLayer_Workflow.py
# Description: Find a best route to visit the stop locations and save the 
#              route to a layer file. The stop locations are geocoded from a 
#              text file containing the addresses.
# Requirements: Network Analyst Extension 


#Import system modules
import arcpy
from arcpy import env
from arcpy import mapping as m
from os import path as p


srcPath = p.join(p.dirname(__file__), "data")


try:
    #Check out the Network Analyst extension license
    arcpy.CheckOutExtension("Network")


    #Set environment settings
    env.workspace = p.join(srcPath, "SanFrancisco.gdb")
    env.overwriteOutput = True
    
    #Set local variables
    inNetworkDataset = "Transportation/Streets_ND"
    outNALayerName = "BestRoute"
    impedanceAttribute = "TravelTime"


    resGDB = p.join(srcPath, "Results.gdb")
    
    if arcpy.Exists(resGDB):
        arcpy.management.Delete(resGDB)    
    arcpy.management.CreateFileGDB(*p.split(resGDB))
    
    #Create a new Route layer. For this scenario, the default value for all the
    #remaining parameters statisfies the analysis requirements
    outNALayer = arcpy.na.MakeRouteLayer(inNetworkDataset, outNALayerName,
                                         impedanceAttribute)
    
    #Get the layer object from the result object. The route layer can now be
    #referenced using the layer object.
    outNALayer = outNALayer.getOutput(0)
    
    #Get the names of all the sublayers within the route layer.
    subLayerNames = arcpy.na.GetNAClassNames(outNALayer)
    #Stores the layer names that we will use later
    stopsLayerName = subLayerNames["Stops"]
    
    #Load the geocoded address locations as stops mapping the address field from
    #geocoded stop features as Name property using field mappings.
    fieldMappings = arcpy.na.NAClassFieldMappings(outNALayer, stopsLayerName)
    fieldMappings["Name"].mappedFieldName = "NAME"
    arcpy.na.AddLocations(outNALayer, stopsLayerName, "Analysis/CandidateStores", fieldMappings,
                          "", exclude_restricted_elements = "EXCLUDE")
    
    #Solve the route layer, ignore any invalid locations such as those that
    #can not be geocoded
    arcpy.na.Solve(outNALayer,"SKIP")
    
    # List sublayers in NALayer Group and export each
    for lyr in m.ListLayers(outNALayer):
        if lyr.isGroupLayer:
            continue
        
        arcpy.management.CopyFeatures(lyr, p.join(resGDB, lyr.name))
        
    
    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)

View solution in original post

2 Replies
DanPatterson_Retired
MVP Esteemed Contributor

Have you tried

Save To Layer File—Help | ArcGIS for Desktop

Copy Features—Help | ArcGIS for Desktop

The only reason I as is that most of the NA arcpy code and function examples use it ... for example

RouteSolverProperties—Help | ArcGIS for Desktop

FreddieGibson
Regular Contributor II

The below snippet should be enough to get you started. It shows how I'm able to export each sublayer of the network analyst layer to its own feature class. I modified this sample from the online sample.

# Name: MakeRouteLayer_Workflow.py
# Description: Find a best route to visit the stop locations and save the 
#              route to a layer file. The stop locations are geocoded from a 
#              text file containing the addresses.
# Requirements: Network Analyst Extension 


#Import system modules
import arcpy
from arcpy import env
from arcpy import mapping as m
from os import path as p


srcPath = p.join(p.dirname(__file__), "data")


try:
    #Check out the Network Analyst extension license
    arcpy.CheckOutExtension("Network")


    #Set environment settings
    env.workspace = p.join(srcPath, "SanFrancisco.gdb")
    env.overwriteOutput = True
    
    #Set local variables
    inNetworkDataset = "Transportation/Streets_ND"
    outNALayerName = "BestRoute"
    impedanceAttribute = "TravelTime"


    resGDB = p.join(srcPath, "Results.gdb")
    
    if arcpy.Exists(resGDB):
        arcpy.management.Delete(resGDB)    
    arcpy.management.CreateFileGDB(*p.split(resGDB))
    
    #Create a new Route layer. For this scenario, the default value for all the
    #remaining parameters statisfies the analysis requirements
    outNALayer = arcpy.na.MakeRouteLayer(inNetworkDataset, outNALayerName,
                                         impedanceAttribute)
    
    #Get the layer object from the result object. The route layer can now be
    #referenced using the layer object.
    outNALayer = outNALayer.getOutput(0)
    
    #Get the names of all the sublayers within the route layer.
    subLayerNames = arcpy.na.GetNAClassNames(outNALayer)
    #Stores the layer names that we will use later
    stopsLayerName = subLayerNames["Stops"]
    
    #Load the geocoded address locations as stops mapping the address field from
    #geocoded stop features as Name property using field mappings.
    fieldMappings = arcpy.na.NAClassFieldMappings(outNALayer, stopsLayerName)
    fieldMappings["Name"].mappedFieldName = "NAME"
    arcpy.na.AddLocations(outNALayer, stopsLayerName, "Analysis/CandidateStores", fieldMappings,
                          "", exclude_restricted_elements = "EXCLUDE")
    
    #Solve the route layer, ignore any invalid locations such as those that
    #can not be geocoded
    arcpy.na.Solve(outNALayer,"SKIP")
    
    # List sublayers in NALayer Group and export each
    for lyr in m.ListLayers(outNALayer):
        if lyr.isGroupLayer:
            continue
        
        arcpy.management.CopyFeatures(lyr, p.join(resGDB, lyr.name))
        
    
    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)