Monday, July 16, 2012

Constructing Polygons at 10.1

Polygon geometries are closes paths forms from a series of X,Y coordinates.  A polygon geometry object can be constructed from using an Array object containing the arcpy.Point(X,Y) values.

In this example, I will construct the extent of a feature class as a polygon to clip another datasource:
import arcpy
dsParcel = r"c:\temp\sample.gdb\Parcels"
dsLandUse = r"c:\temp\sample.gdb\LULC"


pnt = arcpy.Point()
array = arcpy.Array()
extentParcel = arcpy.Describe(dsParcel).extent
coords = [[extentParcel.XMin,extentParcel.YMin],[extentParcel.XMax,extentParcel.YMin],
                [extentParcel.XMax,extentParcel.YMax],[extentParcel.XMin,extentParcel.YMax]]
outLU = r"c:\temp\sample.gdb\clipLULC"
#  Create Spatial Reference
sr = arcpy.SpatialReference()
sr.factoryCode = 4326
sr.create()
# Load the Location
for coord in coords:
    pnt.X = coord[0]
    pnt.Y = coord[1]
    array.add(pnt)
polygon = arcpy.Polygon(array,sr)

arcpy.Clip_analysis(dsLandUse,polygon,outLU)


Notice how we didn't have the close the polygon!  The object does it for us.

Enjoy

1 comment:

Anonymous said...

Could tighten that up a bit with a list comp, and bunching up the geometry creation.
Also we can pass in the factorycode as an argument to spatialref at 10.1 now too.

i.e., something like this:
polygon = arcpy.Polygon(arcpy.Array([arcpy.Point(x,y) for x,y in coords]),
arcpy.SpatialReference(4326))