Wednesday, March 27, 2013

Creating Data Frame Extents (ArcPy 10.1)

I read your comments, and thank you for posting them.  I was asked how do you clip all layers in a map document by the current data frame's extent.

In a previous post, I discussed how to create extent polygons for feature classes and individual features.  The same method applies for creating an extent polygon using data frames.

The data frame object has a whole host of properties and methods which can be found here.  To get the extent of a data frame, just reference the extent property to obtain the data frame's current extent.  Create the extent polygon or feature class, and clip by the extent geometry.

# Clip layers by extent of data frame (assuming in arcmap session)
import os
import arcpy
from arcpy import env
from arcpy import mapping
mxd = mapping.MapDocument("CURRENT")
df = mxd.activeDataFrame
extent = df.extent
array = arcpy.Array()
array.add(extent.lowerLeft)
array.add(extent.lowerRight)
array.add(extent.upperRight)
array.add(extent.upperLeft)
array.add(extent.lowerLeft)
polygon = arcpy.Polygon(array, df.spatialReference)
array.removeAll()
del array
for layer in mapping.ListLayers(mxd, data_frame=df):
    clipped_fc = env.scratchGDB + os.sep + layer.datasetName + "_clipped"
    arcpy.Clip_analysis(in_features=layer, 
                        clip_features=polygon,
                        out_feature_class=clipped_fc)
    del layer
del mxd
del df
del extent

This code is just a quick re-hash of old concepts applied to a new method. The extent object creates a polygon, which is used to clip the layers in that data frame.