Getting started with arcpy.mapping tutorial (arcpy.mapping)

Komplexität: Einsteiger Datenanforderung: Eigene Daten verwenden

This tutorial walks you through some very common arcpy.mapping workflows and introduces some important concepts along the way. It is aimed to help users that are completely new to Python scripting and arcpy.mapping. The steps are generic enough to work with any data and all license levels.

HinweisHinweis:

The only requirement is that you have a feature layer file (.lyr) before starting the tutorial.

The steps below present a very high-level overview of arcpy.mapping. Throughout the tutorial, there are links to detailed help topics that provide much more information about the concepts involved, and in nearly all cases, the topics include additional sample snippets of code.

Python window

The easiest place to start learning arcpy.mapping is in the Python window. The Python window is part of the ArcMap framework and provides autocompletion so you can easily read the names and order of the function parameters. The steps below show you how to set up the Python window for a satisfactory end-user experience and also to match the screen captures throughout this document.

Schritte:
  1. Open a new, empty map document in ArcMap.
  2. Click Geoprocessing > Python.
  3. If it is your first time opening the Python window, it appears as floating over the application. The next steps are to dock the Python window and modify the help placement.

  4. Click the title bar of the Python window and hold down your left mouse button.
  5. Drag the Python window to the docking anchor located at the bottom of the ArcMap application and release the button.
  6. Click in the code pane (with the >>> characters) of the Python window. You should see some help text appear in the help pane to the right.
  7. Right-click the code pane and choose Help Placement > Bottom. Now the help should appear below the code pane. You may need to adjust the divider between the two panes so there is enough space to type code and see the help.
  8. Now type the following statement (be careful, Python is case sensitive):
  9. >>> arcpy.mapping.ExportToPDF(
    
    The Python window should look similar to the graphic below. The first required parameter, called map_document, is highlighted. If you enter a comma, the second parameter becomes highlighted. There are only two required parameters: map_document and out_pdf. Optional parameters are surrounded in curly brackets—{}.
    Screen capture of ExportToPDF syntax
  10. Right-click the code pane and click Clear All to clear the code pane.

Referencing an existing map document

Typically, one of the first operations you do with an arcpy.mapping script is reference an existing map document (.mxd) or layer file (.lyr) that you want to do something with. In this section, you'll reference a map document.

There are two ways to reference a map document. The first is to reference it on disk by providing a path to the .mxd file. If you are building a script that is to be run outside the ArcGIS environment, you must reference a map document using its path. The second way is to reference the map document that is currently loaded into the ArcMap application (in this case, your untitled.mxd). When working in the Python window within ArcMap, it is convenient to reference the currently loaded map document because changes made to it can be seen directly in the application. The following steps will reference the map document currently loaded into ArcMap.

Schritte:
  1. In the Python window, type the following and press ENTER when done:
  2. >>> mxd = arcpy.mapping.MapDocument("CURRENT")
    
    The MapDocument function returns a MapDocument object reference to a variable called mxd. The string CURRENT is a keyword used to reference the currently loaded map document. In place of CURRENT, this is where you could also provide a path to the map document.
  3. In the Python window, type the following:
  4. >>> mxd.
    
    After typing the dot, you should see a long list of methods and properties available to the MapDocument object.
  5. In the Python window, type the following and press ENTER when done:
  6. >>> mxd.author = "YOUR NAME GOES HERE"
    
    The MapDocument object has a property called author. You just set its value to a string.
  7. In ArcMap, click File > Map Document Properties.
  8. You should see that the author property is set to your string. You just interacted directly with the MapDocument object through the variable called mxd. There are many other methods and properties on the MapDocument object. Now you will save your changes.
  9. Click Cancel when done with the Map Document Properties dialog box.
  10. In the Python window, type the following and press ENTER when done:
  11. >>> mxd.save()
    
    Because it is an unsaved map document, a dialog box appears prompting you to provide a path and file name. The save() method does not have any parameters, but because it is a method, you must still include the open/close parentheses. Realistically, you would work with an already existing map document and wouldn't need to deal with a pop-up save dialog box. To verify the location of where the map document was saved, try the following:
  12. In the Python window, type the following and press ENTER when done:
  13. >>> print mxd.filePath
    
    You should see the path printed to the code pane:
    Screen capture of mxd.filePath results in Python window

Add a layer file to the map document

Now that you have a reference to a map document, the next thing you will do is add a layer file (.lyr) to the map document. This can be done with the arcpy.mapping AddLayer function.

Schritte:
  1. In the Python window, type the following:
  2. >>> arcpy.mapping.AddLayer(
    
    Screen capture of AddLayer syntax in Python window
    The autocompletion shows that there are two required parameters. The first is a reference to a data frame in a map document. The second is a reference to the layer you want to add. This can be a layer in a map document or a layer file. The third parameter is optional and controls the placement of the layer in the table of contents. Because it is the first and only layer, you'll ignore the third parameter and go with its default value.
    Before you can add the layer, you need to reference the appropriate objects. First you'll reference the data frame.
  3. In the Python window, backspace to remove the AddLayer function, type the following, then press ENTER when done:
  4. >>> df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
    
    The ListDataFrames function requires a reference to a map document and, optionally, a wildcard filter. You are providing the full name of the data frame to search on. You could also have typed something like "lay*".
    All ArcPy List functions return Python List objects. The items returned in the list are zero based, meaning that the first item in the list has an index value of 0 and the second is 1, all the way to n-1. Because you want the df variable to reference a DataFrame object and not a Python List object, you must append an index number after the function. Appending a [0] at the end of the function returns the first data frame in the list. In your case, it is the only data frame in the list. If you uniquely name your data frames within the map document and use the appropriate wildcard value to isolate the item, you should always return a list with only one item, and index [0] will work. If you have two data frames in a map document and want to reference the second data frame without using a wildcard value, you would need to use a [1] at the end of the function, for example, df2 = arcpy.mapping.ListDataFrames(mxd)[1].
    Next you need to reference a layer file before you can use the AddLayer function. The process of referencing a layer file is identical to referencing a map document when providing a full path to the .mxd, except you use the Layer function instead of the MapDocument function.
    HinweisHinweis:

    For the following steps, you need to locate an existing layer file. If you don't have one, you will need to author one.

  5. In the Python window, type the following and press ENTER when done. The path you provide will most likely be different than the example below.
  6. >>> lyrFile = arcpy.mapping.Layer(r"C:\Project\data\Rivers.lyr")
    
    In the step above, a reference to an existing layer file was created, and that reference is stored in a variable called lyrFile.
    Notice how the path has a small r placed in front of the string. This is a special character in Python that stands for raw. It means to interpret the string as it is and to ignore any other special characters within the string. The small r was used because the path has backslashes within the string. Backslashes in Python are also special characters. For example, \t within a string is converted to a tab and \n is converted into a new line. In the example above, you don't want special characters to be used; you want the raw, literal string. There are two other equivalent ways to type the same path in Python. First, use forward slashes (for example, "C:/Project/States.lyr"). Python does not try to interpret forward slashes, and they are a cross-platform standard. Second, use double backslashes (for example, "C:\\Project\\Lakes.lyr"). The first backslash cancels out the second. The small r technique is important to remember because when you copy system paths on a Windows platform, backslashes are included.
    All the necessary variable references have been created. Next, the AddLayer function will be used to add your layer file to the current map document.
  7. In the Python window, type the following and press ENTER when done:
  8. >>> arcpy.mapping.AddLayer(df, lyrFile)
    
    Your layer should have been added to the table of contents and data view and your Python window should look similar to the graphic below:
    Screen capture of AddLayer results in Python window

Export a map document to PDF

Exporting a map document to PDF is incredibly easy and only requires a single line of code. You already saw the syntax for the ExportToPDF function near the beginning of the tutorial. Now you will complete the syntax.

Schritte:
  1. In the Python window, type the following and press ENTER when done. The path you provide will most likely be different than the example below.
  2. >>> arcpy.mapping.ExportToPDF(mxd, r"C:\Project\Doc1.pdf")
    
    There are many parameters that match the same settings available in ArcMap. Only two parameters are required: map_document and out_pdf.
    A PDF document should have been created at the location you specified, and the Python window should look similar to the graphic below:
    Screen capture of ExportToPDF results in Python window

Reference a layer using the ListLayers function, change layer properties

There are many properties and methods available for working with layers in a map document. Earlier you added a layer to a map document from a layer file. The variable you created called lyrFile references the layer added to the map document. With this variable, you can modify some of the properties of the layer you added.

Schritte:
  1. In the Python window, type the following:
  2. >>> lyrFile.
    
    After entering the dot, notice all the different properties and methods on the Layer object. With the lyrFile variable, you could change these properties in the map document, and when you call the save() method, it would save the changes to the layer file (.lyr) on disk.
    Not all possible layer properties are available on the Layer object, only those that are most common for map automation scenarios. Many more properties can be modified by authoring those properties in a layer file and using the arcpy.mapping UpdateLayer function.
    You are not always going to add layer files. Most of the time, your map document will already have existing layers. In these next steps, you will reference the layer again as if it were already in the map document. Referencing a layer in a map document is very similar to referencing a data frame.
  3. In the Python window, backspace over the current text, type the following, then press ENTER:
  4. >>> lyr = arcpy.mapping.ListLayers(mxd)[0]
    
    The ListLayers function requires that you provide a map document reference. It has two additional parameters: one to perform a wildcard search and the second to specify a data frame. Because you only have one layer and one data frame, it isn't necessary to provide the other parameters. Again, the [0] index value is required at the end of the statement so a Layer object is returned rather than a Python List object.
    With the new lyr variable, you will update some layer properties.
  5. In the Python window, type the following two lines, pressing ENTER after each one:
  6. >>> lyr.name = "Some New Name"
    >>> lyr.visible = False
    
    You won't see a change immediately. Not all property changes or methods automatically update the application. This is by design so the application isn't constantly having to refresh. When using CURRENT to reference the currently loaded map document within ArcMap, you sometimes need to refresh the table of contents or the active view (data view or layout view).
  7. In the Python window, type the following two lines, pressing ENTER after each one:
  8. >>> arcpy.RefreshTOC()
    >>> arcpy.RefreshActiveView()
    
    The table of contents and data view refresh.
    HinweisHinweis:

    If you are running stand-alone scripts outside ArcMap, these additional functions are not needed.

    Your Python window should look similar to the graphic below:
    Screen capture of refresh results in Python window

Change data frame extent

In this section you will change the data frame extent to match the extent of selected features. In a script, this would typically be done using a function like SelectlayerByAttribute. To simplify the experience, you will graphically select some features. First you'll need to turn your layer visibility back on using Python.

Schritte:
  1. In the Python window, type the following three lines, pressing ENTER after each one:
  2. >>> lyr.visible = True
    >>> arcpy.RefreshTOC()
    >>> arcpy.RefreshActiveView()
    
  3. In ArcMap, graphically select one or more features in your layer.
  4. Next, you will create a variable that stores the extent of the selected features and apply that extent to the extent parameter for the DataFrame object you already have referenced.
  5. In the Python window, type the following two lines, pressing ENTER after each one:
  6. >>> lyrExtent = lyr.getSelectedExtent()
    >>> df.extent = lyrExtent
    
    Your Python window should look similar to the graphic below:
    Screen capture of df.extent results in Python window

Export a map document to PDF (again)

You are going to export to PDF again. This time you are creating a second PDF document that will eventually be appended to a new document along with the first document.

Schritte:
  1. In the Python window, type the following and press ENTER when done. The path you provide will most likely be different than the example below.
  2. >>> arcpy.mapping.ExportToPDF(mxd, r"C:\Project\Doc2.pdf")
    
    Your Python window should look similar to the graphic below:
    Scrren capture of ExportToPDF results in Python window

Create a new PDF document and append your two pages

The arcpy.mapping module contains some PDF document management functions that are perfect for creating multiple-page documents. Complete map books, for example, often include pages in addition to the standard reference map pages generated by Data Driven Pages. The use of arcpy.mapping is a necessary step for building complete map books.

This part of the tutorial will simulate the creation of a multipage report. First you will create a new PDF document and then append the PDFs that you created in earlier steps. Imagine that those PDF documents are simply the individual documents that make up a map book. Perhaps Doc1.pdf could be a multipage PDF representing a title page, table of contents, and so on. The second PDF document could be the results of exporting all your Data Driven Pages map pages to a single multipage PDF.

The first step is to create a new PDF document.

Schritte:
  1. In the Python window, type the following and press ENTER when done:
  2. >>> PDFdoc = arcpy.mapping.PDFDocumentCreate(r"C:\Project\Final.pdf")
    
    A variable called PDFdoc references a PDFDocument object in memory. It will not exist on disk until you save and close the document.
    The next steps are to append the appropriate pages.
  3. In the Python window, type the following three lines, pressing ENTER after each one:
  4. >>> PDFdoc.appendPages(r"C:\Project\Doc1.pdf")
    >>> PDFdoc.appendPages(r"C:\Project\Doc2.pdf")
    >>> PDFdoc.saveAndClose()
    
    The first two lines append each PDF to the newly created PDF document. The last line is what commits the changes and creates the final PDF on disk.
    A PDF document should have been created at the location you specified, and the Python window should look similar to the graphic below:
    Screen capture of saveAndClose results in Python window

Related topics

Introduction to arcpy.mapping

Guidelines for arcpy.mapping

You have completed a very simple, yet common workflow using arcpy.mapping. The next steps are to apply these workflows against your own map documents and layers. Also take some time and dig deeper into the arcpy.mapping help topics. There are 100's of small code samples at the ends of each topic that can be easily copied and pasted into the Python window. Also perform a search within the Resource Center on arcpy.mapping to find more advanced arcpy.mapping applications.

9/11/2013