[GIS] Select by location based on selected features with ArcPy

arcpyselect-by-location

Is there a way with Python to do Select by Location with the Use selected feature option?

I'm trying to automate a process and am running into barriers.

I need to be able to select the 2 lines within the same feature class that intersect a point, but I need to do this 1 at a time so I can capture the field attributes for each line. The 2 lines will then be dissolved and eventually appended back into the original line feature. Basically, I'm trying to merge the lines and keep the attributes. The exact tool I need is the Merge tool in the Editor drop down, but apparently that isn't accessible with Python for some dumb reason.

There's also an Unsplit tool but of course it's only for Advanced, which I don't have.

What I'm trying to do:

From the Points feature class, get a list of the OBJECTID values and then use Select by attributes to select each point one at a time. But then I need to be able to do Select by Location on the Line using only the Selected point feature.

Then once the 2 lines are selected, I'll copy their field attributes and dissolve them and then append them back into the original line and add the values back.

enter image description here

I think I got it to work finally. The only thing I haven't figured out yet is how to delete the original lines that are being replaced when I append the newly dissolved lines. Because I think the only way I can use the Select by Location is when a layer file and not a feature class, so I'm not sure how to go about it yet.

Best Answer

In order to use select layer by location (or attribute), you need to operate on a feature layer. Then you can use SQL to select by FID. You place this in a loop that loops over the number of entries in the attribute table. MakeFeatureLayer can be also used to select by attributes. Just make sure to delete the layer after using it to get ready for the next loop.

line_lyr = arcpy.MakeFeatureLayer_management(line_input, "line layer")
entries = int(arcpy.GetCount_management(point_input).getOutput(0))

for i in xrange(entries):
    pt_lyr = arcpy.MakeFeatureLayer_management(point_input, "point layer", "\"FID\"={}".format(str(i)))
    arcpy.SelectLayerByLocation_management(line_lyr, "INTERSECT", pt_lyr, "", "NEW_SELECTION")
    if arcpy.Exists(pt_lyr): arcpy.Delete_management(pt_lyr) 
    #Rest of the code here....

Edit: There is an optional parameter for the Dissolve tool that gives some of the basic functionality of Unsplit Line.

Related Question