Select to view content in your preferred language

SelectLayerByLocation returning incorrect

1884
1
02-07-2013 07:57 PM
by Anonymous User
Not applicable
Original User: ahrensd

Have been trying for some time now to create a script to extract the polygons whithin a extent, but unable to get the same result as when i use the UI manual method.
Maybe someone can see the fault of my script, have striped it down to the minimum for simplicity.

import arcpy

layer = arcpy.GetParameterAsText(0)
top = arcpy.GetParameterAsText(1)
left = arcpy.GetParameterAsText(2)
bottom = arcpy.GetParameterAsText(3)
right = arcpy.GetParameterAsText(4)
outputFeature = arcpy.GetParameterAsText(5)

# Determine if Layer is a Layer
desc = arcpy.Describe(layer)
if hasattr(desc, "layer"):
     lyr = layer
     arcpy.AddMessage('Parameter was layer: {0}'.format(lyr))
else:
     lyr = arcpy.MakeFeatureLayer_management(layer,"in_memory\\source_layer")
     arcpy.AddMessage('Parameter made to layer: {0}'.format(lyr))
     
sr = arcpy.CreateSpatialReference_management("",lyr,"","","","")

lowerLeft = arcpy.Point(left,bottom)
upperLeft = arcpy.Point(left,top)
upperRight = arcpy.Point(right,top)
lowerRight = arcpy.Point(right,bottom)

a = arcpy.Array([lowerLeft,lowerRight,upperRight,upperLeft,lowerLeft])
thepoly = arcpy.Polygon(a,sr)

arcpy.AddMessage('Selecting form lyr by polygon: {0}'.format(thepoly))
selection = arcpy.SelectLayerByLocation_management(lyr, "WITHIN", thepoly, "", "NEW_SELECTION")

matchcount = int(arcpy.GetCount_management(selection).getOutput(0)) 
if matchcount == 0:
    arcpy.AddMessage('no features matched spatial and attribute criteria')
else:
    if matchcount < 1000:
        arcpy.CopyFeatures_management(selection, outputFeature)
        arcpy.AddMessage('{0} objects that matched criteria written to {1}'.format(matchcount, outputFeature))
0 Kudos
1 Reply
by Anonymous User
Not applicable
Original User: Wayne_Whitley

Yes, well, aren't you getting the point object's XY parameters at the beginning of the script as text?  The webhelp doc explicitly states you have to feed in double data types....so I think in Python you'd need to convert to float, as in (using IDLE):

>>> text = '123.456'
>>> type(text)
<type 'str'>
>>> 
>>> num = float(text)
>>> type(num)
<type 'float'>
>>> 
>>> # text cannot be used directly in, say, math operations:
>>> text + 1.0

Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    text + 1.0
TypeError: cannot concatenate 'str' and 'float' objects
>>> 
>>> 
>>> # However, the converted value can:
>>> num + 1.0
124.456
>>> 


Fix that, see if it runs...

Enjoy,
Wayne
0 Kudos