Wednesday, June 24, 2009

Create an Extent Polygon using Python

If you are like me, sometimes you want to give the user options on how they can select data. So I came up with this little number. I use this if the user does not draw a polygon, polyline, or point. If that condition is met, then the script will generate a full extent polygon and use that as it's selecting bounding box.

The function CreatePolygonExtent takes two objects: the first is the gp object, and the second is the input feature. It exports a geometry object that contains the polygon shape. The next function, InsertGeom() just is a simple insert cursor function. It takes a multiple number of inputs, and they are: gp, polyGeom, feat, ws. The gp object is the geoprocessing reference, polyGeom is the value from the CreatePolygonExtent(), feat is the name of the output feature, and ws is the saved workspace.

Outside of the two functions, the script generates a file geodatabase in the scratch workspace. This is where the temporary results will be saved.


Here is the code:

import arcgisscripting, os, sys

def CreatePolygonExtent(gp, in_Feat):
desc = gp.describe(in_Feat)
extent = desc.extent
# Create an Array object.
ary = gp.createobject("Array")
# List of coordinates.
coordList = [str(extent.xmin)+";"+str(extent.ymin),str(extent.xmin)+";"+str(extent.ymax),str(extent.xmax)+";"+str(extent.ymax),str(extent.xmax)+";"+str(extent.ymin)]
# For each coordinate set, create a point object and add the x- and
# y-coordinates to the point object, then add the point object
# to the array object.
for coordPair in coordList:
pnt = gp.createobject("Point")
x, y = coordPair.split(";")
pnt.x = x
pnt.y = y
# Create a polygon geometry object using the array object
# created from the coordinate list above.
polyGeom = gp.createobject("geometry", "polygon", ary)
return polyGeom

def InsertGeom(gp, polyGeom, feat, ws):
out_feat_class = "ExtentFeature"
gp.CreateFeatureclass(ws, feat, "POLYGON")
rows = gp.insertcursor(ws + os.sep + feat)
row = rows.newrow()
row.Shape = polyGeom
del rows, row
return feat

gp = arcgisscripting.create(9.3)
gp.scratchworkspace = r"c:\temp"
in_Feat = gp.getparameter(0)
polyGeom = CreatePolygonExtent(gp, in_Feat)
out_feat_class = "ExtentFeature"
gp.CreateFileGDB(gp.scratchworkspace, "BBoxHolder.gdb")
ws = gp.scratchworkspace + "\\BBoxHolder.gdb"
out_feat_class = "ExtentFeature"
returnFeat = InsertGeom(gp, polyGeom, out_feat_class, ws)

gp.setparameterastext(1, str(ws + os.sep + out_feat_class))