Restricting the layout elements returned by ListLayoutElements()

Layouts can contain a large number of elements, many of which you won't need for a particular geoprocessing script. The ListLayoutElements() function can restrict the layout elements returned, by passing a parameter that defines the type of element that should be returned along with an optional wildcard, which finds elements using a portion of the name.

Getting ready

There are many different types of layout elements, including graphics, legends, pictures, text, and data frames. When you return a list of layout elements, you can restrict (filter) the types of elements that are returned. In this recipe, you will write a script that filters the layout elements returned by element type and wildcard.

How to do it…

Follow these steps to learn how to restrict the list of layers returned by the ListLayoutElements() function through the use of optional parameters, which define the type of element that should be returned along with a wildcard that can also restrict the elements that are returned:

  1. Open C:ArcpyBookCh4Crime_Ch4.mxd in ArcMap.
  2. Open the Python window.
  3. Import the arcpy.mapping module:
    import arcpy.mapping as mapping
  4. Reference the currently active document (Crime_Ch4.mxd) and assign this reference to a variable:
    mxd = mapping.MapDocument("CURRENT")
  5. Use the ListLayoutElements() function with a restriction of only legend elements, as well as a wildcard that returns elements with a name containing the Crime text anywhere in the name:
    for el in mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT","*Crime*"):
      print(el.name)
  6. You can check your work by examining the c:ArcpyBookcodeCh4RestrictLayoutElements.py solution file.
  7. Run the script. In this case, only a single layout element will be returned:
    Crime Legend
    

How it works...

ListLayoutElements() is a versatile function, which in its most basic form is used to return a list of all the layout elements on the page layout of a map document. However, there are two optional parameters that you can supply to filter this list. The first type of filter is an element type filter in which you specify that you only want to return one of the layout element types. You can also apply a wildcard to filter the returned list. These two types of filters can be used in combination. For example, in this recipe, we are specifying that we only want to return LEGEND_ELEMENT objects with the Crime text anywhere in the element name. This results in a highly filtered list that only contains a single layout element.

Note

ListLayoutElements() can be filtered using one of these element types: DATAFRAME_ELEMENT, GRAPHIC_ELEMENT, LEGEND_ELEMENT, MAPSURROUND_ELEMENT, PICTURE_ELEMENT, or TEXT_ELEMENT.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset