AnsweredAssumed Answered

How to use "arcpy.SelectLayerByLocation_management" efficiently?

Question asked by suryakant on Jul 8, 2015
Latest reply on Jul 14, 2015 by jkt5y

I have two layer Parcels(polygon) with fields objectid, parcel_name, parcel_id and location and Sites(point) with objectid field. I want to write a csv file with the Sites objectid field with the parcel_name and parcel_id if the point falls inside any parcel polygon like 2034, ABC, ABC_12 (Site's objectid, Parcels's parcel_name, Parcels's parcel_id).

 

import arcpy
import os

arcpy.env.overwriteOutput = True


def main():
    """ main function"""
    try:
        fc = r'Database Connections\Test.sde\UserName.AllData\UserName.Parcels' # arcpy.GetParameter(0)
        parcel_name = 'Parcel_Name' #arcpy.GetParameterAsText(1)
        parcel_id = 'Parcel_ID' #arcpy.GetParameterAsText(2)
        sites_fc = r'Database Connections\Test.sde\UserName.AllData\UserName.Sites' #arcpy.GetParameter(3)
        output_path = os.path.join(os.path.dirname(__file__), 'Name_and_ID.csv')


        ftr_name = os.path.basename(str(sites_fc)).split('.')[-1]
        sites_fc_local = arcpy.MakeFeatureLayer_management(sites_fc, ftr_name)

        with open(output_path, 'w') as file_:
            file_.write('OBJECTID, {}, {}\n'.format(parcel_name, parcel_id))


        with arcpy.da.SearchCursor(fc, (parcel_name, parcel_id), sql_clause=('DISTINCT', None)) as cursor:
            for row in cursor:
                arcpy.AddMessage('Writing information for: {}'.format(row[0]))
                temp_ftr = arcpy.MakeFeatureLayer_management(fc, row[0], "{} = '{}'".format(parcel_name, row[0]), workspace='in_memory')
                selected = arcpy.SelectLayerByLocation_management(building_ftr_local, 'HAVE_THEIR_CENTER_IN', temp_ftr,
                                                                  selection_type='NEW_SELECTION')
                with arcpy.da.SearchCursor(selected, 'OID@') as cur:
                    for r in cur:
                        with open(output_path, 'a') as file_:
                            file_.write("{}, {}, {}\n".format(r[0], row[0], row[1]))
        arcpy.SetParameter(4, output_path)
    except Exception as error:
        arcpy.AddError(error)


if __name__ == '__main__':
    main()

Outcomes