Wednesday, July 13, 2011

Creating Extent Polygons Using ArcPy

Awhile ago I wrote an article about creating extent polygons using the old arcgisscripting geoprocessing framework at version 931.  I've decided to update the posting because ArcPy makes it easy because you can easily get the extent object of a geometry and directly grab the extent point objects from the extent object.

To create an extent of the whole dataset use the describe method:

import arcpy
from arcpy import env
import os

inFC = r"c:\temp\USA.gdb\States"
extentPoly = str(env.scratchWorkspace) + os.sep + "extent.shp"
# Feature extent
#
extent = arcpy.Describe(inFC).extent
# Array to hold points
#
array = arcpy.Array()
# Create the bounding box
array.add(extent.lowerLeft)
array.add(extent.lowerRight)
array.add(extent.upperRight)
array.add(extent.upperLeft)
# ensure the polygon is closed
array.add(extent.lowerLeft)
# Create the polygon object
polygon = arcpy.Polygon(array)
array.removeAll()
# save to disk
arcpy.CopyFeatures_management(polygon, extentPoly)
del polygon

That should create a box around all your data in a feature class. Very simple!

Next, let's say you need the bounding box for each feature. In the example, I will continue with using a states polygon:

import arcpy
from arcpy import env
import os


env.overwriteOutput = True

inFC = r"c:\temp\USA.gdb\States"
extentPoly = str(env.scratchWorkspace) + os.sep + "extent.shp"
ptList = []
rows = arcpy.SearchCursor(inFC)

for row in rows:
   extent = row.Shape.extent
   array.add(extent.lowerLeft)
   array.add(extent.lowerRight)
   array.add(extent.upperRight)
   array.add(extent.upperLeft)
   array.add(extent.lowerLeft)
   polygon = arcpy.Polygon(array)
   ptList.append(polygon)
   array.removeAll()
del rows
arcpy.CopyFeatures_management(ptList, extentPoly)

In this code sample, it loops through the feature class and write the bounding box geometry to a python list. That list is then given as an input to CopyFeatures() and it writes it to disk. Notice that you can get the extent right from the Shape value from the row object. This makes life easy.

Here is a image of what the lower 48 would look like as extents:
The white lines are the extents.

Enjoy