There will be many occasions when you will need to change the map extent. This is frequently the case when you are automating the map production process and need to create many maps of different areas or features. There are a number of ways that the map extent can be changed with arcpy
. However, for this recipe, we'll concentrate on using a definition expression to change the extent.
The DataFrame
class has an extent
property that you can use to set the geographic extent. This is often used in conjunction with the Layer.definitionQuery
property that is used to define a definition query for a layer. In this recipe, you will learn how to use these objects and properties to change the map extent.
Follow these steps to learn how to get a list of layers from a map document:
c:ArcpyBookCh2Crime_Ch2.mxd
with ArcMap.arcpy.mapping
module:import arcpy.mapping as mapping
Crime_Ch2.mxd
) and assign the reference to a variable:mxd = mapping.MapDocument("CURRENT")
for
loop that will loop through all the data frames in the map document:for df in mapping.ListDataFrames(mxd):
Crime
and a specific layer that we'll apply the definition query against:if df.name == 'Crime': layers = mapping.ListLayers(mxd,'Crime Density by School District',df)
for
loop that will loop through the layers. There will only be one, but we'll create the loop anyway. In the for
loop, create a definition query and set the new extent of the data frame:for layer in layers: query = '"NAME" = 'Lackland ISD'' layer.definitionQuery = query df.extent = layer.getExtent()
c:ArcpyBookcodeCh2ChangeMapExtent.py
:This recipe used a definition query on a layer to update the map extent. Near the end of the script, you created a new variable called query
that held the definition expression. The definition expression was set up to find school districts with a name of Lackland ISD. This query string was then applied to the definitionQuery
property. Finally, the df.extent
property was set to the returned value of layer.getExtent()
.