Help with using list layers and select by location with arcpy

520
3
02-10-2022 02:52 PM
ColeNelson
New Contributor III

Hello, I am trying to develop a tool that will generate 2 individual line feature classes.

Capture.PNG

I want to create individual feature class from the Lines_Selected layer in the contents pane, based on the spatial relationships from the feature classes found in the NewHydrants.gdb.  Essentially I want to generate  line feature classes for both Kuna and for Middleton.

My thought for doing this was to create a list for the feature classes found in the the NewHydrants.gdb then use the select by location function to copy the features into their own feature classes.  So far my code works great till I get to the last line, here is the code so far.

import arcpy

arcpy.env.overwriteOutput = True

arcpy.env.workspace =  r"C:\UpdateDevelopmentPython\ForDeveloping\ForDeveloping.gdb"
EnterWaterSysID = arcpy.GetParameterAsText(0).split(";")
Hydrant_FC = "Hydrants"
WaterSystems = "WaterSystems"
Streetmap = r"C:\UpdateDevelopmentPython\Streetmap Premium\FGDB\StreetMap_Data\NorthAmerica.gdb\Routing\Routing_ND"

qry = "{0} IN ({1})".format(arcpy.AddFieldDelimiters(datasource= Hydrant_FC, field = 'WaterSysID'), ', '.join(EnterWaterSysID))

arcpy.SelectLayerByAttribute_management(in_layer_or_view=Hydrant_FC, where_clause=qry)
arcpy.SelectLayerByLocation_management(Hydrant_FC,"Within",WaterSystems,None,"SUBSET_SELECTION","INVERT")

arcpy.env.workspace = r"C:\UpdateDevelopmentPython\ForDeveloping\ForDeveloping.gdb"
Service_Area = arcpy.na.MakeServiceAreaAnalysisLayer(network_data_source=Streetmap,
                                                       layer_name="Service Area",
                                                       travel_mode="Driving Distance",
                                                       travel_direction="FROM_FACILITIES",
                                                       cutoffs=[0.189394],
                                                       time_of_day="",
                                                       time_zone="LOCAL_TIME_AT_LOCATIONS",
                                                       output_type="LINES",
                                                       polygon_detail="STANDARD",
                                                       geometry_at_overlaps="SPLIT",
                                                       geometry_at_cutoffs="RINGS",
                                                       polygon_trim_distance="100 Meters",
                                                       exclude_sources_from_polygon_generation=[],
                                                       accumulate_attributes=["Miles"],
                                                       ignore_invalid_locations="SKIP")[0]

Updated_Service_Area = arcpy.na.AddLocations(in_network_analysis_layer=Service_Area,
                                             sub_layer="Facilities",
                                             in_table=Hydrant_FC,
                                             field_mappings="",
                                             search_tolerance="5000 Meters",
                                             sort_field="",
                                             search_criteria=[["Routing_Streets", "SHAPE"],
                                                             ["Routing_Streets_Override", "NONE"],
                                                             ["Routing_ND_Junctions", "NONE"]],
                                             match_type="MATCH_TO_CLOSEST",
                                             append="APPEND",
                                             snap_to_position_along_network="NO_SNAP",
                                             snap_offset="5 Meters",
                                             exclude_restricted_elements="EXCLUDE",
                                             search_query=[])[0]

Solve_Succeeded = arcpy.na.Solve(in_network_analysis_layer=Updated_Service_Area,
                                 ignore_invalids="SKIP",
                                 terminate_on_solve_error="TERMINATE",
                                 simplification_tolerance="",
                                 overrides="")

Lines = arcpy.Select_analysis("Lines","Lines_Selected")

arcpy.SelectLayerByAttribute_management(Hydrant_FC, "CLEAR_SELECTION")

Lines_Extracted = r"C:\UpdateDevelopmentPython\ForDeveloping\ForDeveloping.gdb\Lines_Selected"
p = arcpy.mp.ArcGISProject("CURRENT")
m = p.listMaps("Map")[0]
m.addDataFromPath(Lines_Extracted)

arcpy.env.workspace = r"C:\UpdateDevelopmentPython\ForDeveloping\NewHydrants.gdb"

HydrantLines = arcpy.ListFeatureClasses()
for fc in HydrantLines:
    arcpy.SelectLayerByLocation_management("Lines_Selected","WITHIN_A_DISTANCE",HydrantLines,"1000 Feet")
 
When I get to the very last line of the code it keeps giving me the following error:
 
Traceback (most recent call last):
File "C:\UpdateDevelopmentPython\DevelopmentScripts\ExtractStreets.py", line 68, in <module>
arcpy.SelectLayerByLocation_management("Lines_Selected","WITHIN_A_DISTANCE",HydrantLines,"1000 Feet")
File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py", line 10448, in SelectLayerByLocation
raise e
File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\management.py", line 10445, in SelectLayerByLocation
retval = convertArcObjectToPythonObject(gp.SelectLayerByLocation_management(*gp_fixargs((in_layer, overlap_type, select_features, search_distance, selection_type, invert_spatial_relationship), True)))
File "C:\Program Files\ArcGIS\Pro\Resources\ArcPy\arcpy\geoprocessing\_base.py", line 512, in <lambda>
return lambda *args: val(*gp_fixargs(args, True))
RuntimeError: Object: Error in executing tool
 
At this point I'm not sure what is causing this error and have been stuck on this for awhile, any help would be greatly appreciated.  Thank you.
 

0 Kudos
3 Replies
DanPatterson
MVP Esteemed Contributor

"Lines_Selected" shouldn't this be from line X

Lines = arcpy.Select_analysis("Lines","Lines_Selected")

Code formatting ... the Community Version - Esri Community

for line numbers


... sort of retired...
ColeNelson
New Contributor III
import arcpy
import os

arcpy.env.overwriteOutput = True

arcpy.env.workspace =  r"C:\UpdateDevelopmentPython\ForDeveloping\ForDeveloping.gdb"
EnterWaterSysID = arcpy.GetParameterAsText(0).split(";")
Hydrant_FC = "Hydrants"
WaterSystems = "WaterSystems"
Streetmap = r"C:\UpdateDevelopmentPython\Streetmap Premium\FGDB\StreetMap_Data\NorthAmerica.gdb\Routing\Routing_ND"

qry = "{0} IN ({1})".format(arcpy.AddFieldDelimiters(datasource= Hydrant_FC, field = 'WaterSysID'), ', '.join(EnterWaterSysID))

arcpy.SelectLayerByAttribute_management(in_layer_or_view=Hydrant_FC, where_clause=qry)
arcpy.SelectLayerByLocation_management(Hydrant_FC,"Within",WaterSystems,None,"SUBSET_SELECTION","INVERT")

arcpy.env.workspace = r"C:\UpdateDevelopmentPython\ForDeveloping\ForDeveloping.gdb"
Service_Area = arcpy.na.MakeServiceAreaAnalysisLayer(network_data_source=Streetmap,
                                                       layer_name="Service Area", 
                                                       travel_mode="Driving Distance", 
                                                       travel_direction="FROM_FACILITIES", 
                                                       cutoffs=[0.189394], 
                                                       time_of_day="", 
                                                       time_zone="LOCAL_TIME_AT_LOCATIONS", 
                                                       output_type="LINES", 
                                                       polygon_detail="STANDARD", 
                                                       geometry_at_overlaps="SPLIT", 
                                                       geometry_at_cutoffs="RINGS", 
                                                       polygon_trim_distance="100 Meters", 
                                                       exclude_sources_from_polygon_generation=[], 
                                                       accumulate_attributes=["Miles"], 
                                                       ignore_invalid_locations="SKIP")[0]

Updated_Service_Area = arcpy.na.AddLocations(in_network_analysis_layer=Service_Area,
                                             sub_layer="Facilities", 
                                             in_table=Hydrant_FC, 
                                             field_mappings="", 
                                             search_tolerance="5000 Meters", 
                                             sort_field="", 
                                             search_criteria=[["Routing_Streets", "SHAPE"], 
                                                             ["Routing_Streets_Override", "NONE"], 
                                                             ["Routing_ND_Junctions", "NONE"]], 
                                             match_type="MATCH_TO_CLOSEST", 
                                             append="APPEND", 
                                             snap_to_position_along_network="NO_SNAP", 
                                             snap_offset="5 Meters", 
                                             exclude_restricted_elements="EXCLUDE", 
                                             search_query=[])[0]

Solve_Succeeded = arcpy.na.Solve(in_network_analysis_layer=Updated_Service_Area, 
                                 ignore_invalids="SKIP", 
                                 terminate_on_solve_error="TERMINATE", 
                                 simplification_tolerance="", 
                                 overrides="")

Lines = arcpy.Select_analysis("Lines","Lines_Selected")

arcpy.SelectLayerByAttribute_management(Hydrant_FC, "CLEAR_SELECTION")

Lines_Extracted = r"C:\UpdateDevelopmentPython\ForDeveloping\ForDeveloping.gdb\Lines_Selected"
p = arcpy.mp.ArcGISProject("CURRENT")
m = p.listMaps("Map")[0]
m.addDataFromPath(Lines_Extracted)

gdb = r"C:\UpdateDevelopmentPython\ForDeveloping\NewHydrants.gdb"

HydrantLines = arcpy.ListFeatureClasses()
for fc in HydrantLines:
    desc = arcpy.da.Describe(fc)
    HydrantFeatures = os.path.join(gdb,desc["baseName"])
    arcpy.MakeFeatureLayer_management(fc,HydrantFeatures)
    arcpy.SelectLayerByLocation_management("Lines_Selected","WITHIN_A_DISTANCE",HydrantFeatures,"1000 Feet")
    
HydrantPoints = arcpy.ListFeatureClasses()
for fcs in HydrantPoints:
    desc1 = arcpy.da.Describe(fcs)
    arcpy.SpatialJoin_analysis("Lines_Selected",fcs, HydrantFeatures)
    arcpy.Copy_management("Lines_Selected",HydrantFeatures)
0 Kudos
ColeNelson
New Contributor III

Just read your article for code formatting, this looks a lot better and easier for others to read, thank you for that as well.

0 Kudos