Tutorial: Get started with arcpy.mp
This tutorial walks you through common Mapping module workflows and introduces important concepts. It is aimed to help users who are new to Python scripting and the arcpy.mp module but have a basic understanding of ArcGIS Pro. The steps are generic enough to work with any data and all license levels.
In this tutorial, you will learn to do the following:
Reference a project, change its default geodatabase, and save.
Reference a map and add a layer file (*
.lyrx).Reference a layout and modify a text element string.
Reference a map frame on a layout and change its extent to the extent of the added layer.
Export the layout to PDF.
Save your code to a Python file (*
.py).
Estimated time: 60 minutes
Note:
The steps below present a high-level overview of the Mapping module. Throughout the tutorial, there are links to detailed help topics that provide more information about the concepts involved, and in nearly all cases, the topics include additional sample code snippets.
Create a simple project
Before you can start writing arcpy.mp code, you need to create a simple project that contains a single map and a layout with a map frame and a text element.
Open a new, blank project.
On the Insert tab, in the Project group, click the New Map drop-down menu and choose New Map.
Name the new map Tutorial Map.
You will reference the map using this name later in the tutorial to add a layer file.
On the Insert tab, click New Layout and select a layout from the gallery.
Name the new layout Tutorial Layout.
You will reference the layout using this name later in the tutorial to modify layout elements and export the layout to a PDF.
On the Insert tab, in the Map Frames group, choose the Map Frame drop-down menu and select a map frame that includes an extent with an associated scale and add it to the layout.
Name the new map frame element Tutorial Map MapFrame.
You will reference the map frame element using this name later in the tutorial to modify its extent.
On the Insert tab, in the Graphics and Text group, choose the Straight text control from the tool gallery and insert a text element on the layout.
Leave the default string value and text size as is; they will be modified with code later.
Name the new text element Title.
You will reference the text element using this name later in the tutorial to modify its text string.
On the Project tab, click Save.
Depending on how you created the project, you may be required to save it to a location.
Use the Python window
You can start learning arcpy.mp in the Python window. It allows you to perform small Python-based workflows and work through concepts directly in the application before being refined in larger scripts. The Python window is part of the ArcGIS Pro application and provides autocomplete and command syntax so you can quickly enter the appropriate parameter information in the correct order. For more information, check out the Python window help topic.
On the View tab, click Python Window.
If this is the first time you have opened it, the Python window may appear docked at the bottom of the application. Keep it docked in this location or dock it where you prefer.
The Python window includes prompt and transcript sections. The prompt is at the bottom of the window, where code is written and entered. The transcript is above the prompt and provides a record of previously entered Python code.
Click in the prompt section where it says Enter Python code here.
A blinking pointer appears where you can type code.
Note:
This tutorial was written to work with the Python window using a single command prompt. You can also use the Python Notebook option in the application but understand that the code would need to be run from a single cell to mimic the tutorial steps. To open a Python notebook, select the Analysis tab, click the Python drop-down menu and select Python Notebook. For more information, see the Notebooks in ArcGIS Pro help topic.
Reference an existing project
Typically, one of the first operations you perform with an arcpy.mp script is reference an existing project (.aprx) or layer file (.lyrx or .lyr) that you want to manipulate. In this section, you will reference a project.
There are two ways to reference a project. The first is to reference it on disk by providing a path to the .aprx file. If you are building a script that is to be run outside the ArcGIS environment, you must reference a project using its full system path. The second way is to reference the project that is currently loaded into ArcGIS Pro. When working in the Python window, it is convenient to reference the currently loaded project because changes made to it can be seen directly in the application. The following steps reference a project currently loaded into ArcGIS Pro.
In the Python window, type the following line of code and press Enter.
aprx = arcpy.mp.ArcGISProject("CURRENT")The above
ArcGISProjectfunction returns anArcGISProjectobject reference to a variable calledaprx. Keep in mind that Python variable names, functions, and properties are case sensitive. TheCURRENTstring is a keyword used to reference the currently loaded project. Again, if you wanted to run a script outside of the application, you would need to provide a full path to the project file instead.In the Python window, type the following:
aprx.After typing the dot, you'll see a long list of methods and properties available to the
ArcGISProjectobject.Note:
For the following steps, locate an existing geodatabase that you can use to be set as your default geodatabase.
In the Python window, continue to type the following and press Enter. Provide your own path to an existing geodatabase.
aprx.defaultGeodatabase = r"path to a geodatabase"For example, type:
aprx.defaultGeodatabase = r"C:\Projects\YosemiteNP\Data\Yosemite.gdb"When a new project is created, its default geodatabase is set to an empty geodatabase created with the same name as your project and in the same folder location. The
defaultGeodatabaseproperty allows you to get or set the default geodatabase. In this example, it is being modified to reference a geodatabase that contains data.Note:
Notice how the path has a lowercase
rin 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 lowercaseris used because the path has backslashes within the string. Backslashes in Python are special escape characters. For example, a\twithin a string is converted to a tab, and a\nis converted to a new line. In the example above, you don't want special characters to be interpreted because it could render the path as invalid; 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:/Projects/YosemiteNP/Data/Yosemite.gdb"). Python works well with forward slashes; they are a cross-platform standard. Second, use double backslashes (for example,"C:\\Projects\\YosemiteNP\\Data\\Yosemite.gdb"). The first backslash escapes the second. The lowercasertechnique is important to remember because, when you copy system paths on a Windows platform using the Copy as path command, backslashes are included so you can add therinstead of having to modify the backslashes.To see the change you made to the project, click the Project tab and select Options.
The Current settings panel displays the change you made to the Default geodatabase setting.
Click Cancel.
Another way to verify the default geodatabase was changed is to expand the Databases connection in the Catalog pane. The new geodatabase is listed, and the home icon is next to that database.
In the Python window, type the following and press Enter:
aprx.save()The
save()method does not have any parameters, but because it is a method, you must include the parentheses. Now confirm the path is correct. Check that the timestamp on your project file is updated to the current date and time.Note:
If you don't want to save changes directly to the current project, you could use the
aprx.saveACopy(file_name)method to save the changes to a new location, but your Python variables will continue to reference the current project.In the Python window, type the following and press Enter:
print(aprx.filePath)Your project path is printed to the transcript.
Add a layer file to the map
Now that you have a reference to a project, you will add a layer file (.lyr or .lyrx) to the map you previously added.
Note:
For the following steps, create or locate a vector layer file that contains only one layer.
In the Python window, type the following and press Enter:
m = aprx.listMaps("Tutorial Map")[0]All
arcpyList 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 m variable to reference aMapobject 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 map in the list. In this case, it is the only map in the list because you also provided the unique name of the map as awildcardparameter. If you uniquely name your maps in the project and use the appropriatewildcardvalue to isolate the item, you see a list with only one item, and index[0]will work.In the Python window, type the following:
m.After typing the dot, this time you will see a long list of methods and properties available to the
Mapobject.Before you can use the
addLayermethod on theMapobject, you must reference a layer file. The process of referencing a layer file is identical to referencing a project, except you use theLayerFilemethod.In the Python window, backspace to remove the
m.or anything else you entered, type the following, and press Enter:lyrFile = arcpy.mp.LayerFile(r"path to a layer file")For example, type:
lyrFile = arcpy.mp.LayerFile(r"C:\Projects\YosemiteNP\LYRS\Boundary.lyrx")In the step above, a reference to an existing layer file was created, and that reference is stored in a variable named
lyrFile.In the Python window, type the following:
lyr = m.addLayer(The autocompletion shows that there is one required parameter named
add_layer_or_layerfileand one optional parameter (surrounded by { } brackets) namedadd_position. The first parameter can reference an existing layer in a project or in a layer file. The second parameter is optional and controls the placement of the layer in the Contents pane.In the Python window, type the following and press Enter:
lyr = m.addLayer(lyrFile)[0]Your layer is added to the map and is referenced with the
lyrvariable and uses the defaultadd_position.A layer file can contain one or many layers. Because of this, the
addLayermethod returns a Python List of the layers, even if there is only one layer. To reference a specificLayerobject, an index number is needed. The index value[0]will return the first layer.
Modify existing layout elements
All elements on a layout can be referenced using the listElements method on the Layout object. The collection of properties and methods will differ based on the element type. In this section, you will first update the string associated with a text element and then you will change the extent of the map frame element to be based on the extent of the layer you added.
In the Python window, type the following and press Enter:
lyt = aprx.listLayouts("Tutorial Layout")[0]The above code uses the same logic as referencing a map but uses the
listLayoutsmethod on theArcGISProjectobject instead.Now that you have a reference to the
Layoutobject with thelytvariable, you can reference the elements in the layout.In the Python window, type the following and press Enter:
title = lyt.listElements("TEXT_ELEMENT", "Title")[0]Again, all
arcpyList functions return Python List objects, so it is important to include the index number. ThelistElementsmethod takes two optional parameters that help filter the resulting list. The first parameter is calledelement_typeand it will only take a value from a constants list. In this case, it usesTEXT_ELEMENT. The second parameter is calledwildcardand works similarly to previous list functions. If you named the text element appropriately, you will reference the one and only text element correctly.Now that you have a reference to the text element with the
titlevariable, you can modify its text string and change its text size.In the Python window, type the following and press Enter after each line:
title.text = "My first arcpy.mp title" title.textSize = 36The text should update in the layout. You can change the text size again if they current value doesn't work well for your string.
Using a similar technique as above, you will now reference the map frame on the layout.
In the Python window, type the following and press Enter:
mf = lyt.listElements("MapFrame_Element", "*frame")[0]The above code also uses the
listElementsfunction but note a couple of syntax uses. First, notice theelement_typestring has mixed case. Mostarcpykeywords in constant lists are not case sensitive. Second, notice the special wildcard character"*"used in thewildcardparameter. When the wildcard character is used, the entire string is not case sensitive; otherwise, the string must match the case exactly. In this example, themfvariable will properly reference the map frame namedTutorial Map MapFramebecause the name ends withframe. The wildcard character can be used in a variety of ways.Now that you have a reference to the layer and a map frame element, you can modify its extent using the extent based on the layer.
In the Python window, type the following code and press Enter after each line:
ext = mf.getLayerExtent(layer = lyr, selection_only = False) mf.camera.setExtent(ext) mf.camera.scale = mf.camera.scale * 1.1The first line uses the
getLayerExtentmethod on theMapFrameElementobject. The first parameter is the layer reference and the second parameter determines if the extent is based on all features or only the selected features. The second line sets the map frame extent to the extent object returned from the first line. The last line modifies the scale by 10 percent so that the features are not immediately against edges of the map frame.
Export a layout to PDF
Exporting a layout to PDF requires a few lines of code. You must create the export format you want generate and then export the layout to that format. The layout you are going to export is already referenced with the variable lyt.
In the Python window, type the following and press Enter after each line:
pdf = arcpy.mp.CreateExportFormat("PDF", r"C:\Temp\Yosemite.pdf") lyt.export(pdf)The first parameter on the
CreateExportFormatfunction is calledformatand supports 11 file format options. The second parameter allows you to specify the export location.A file is generated in the location you set.
Save code to a Python file
Everything that is displayed in the Python window transcript pane can be saved to a Python file (* .py). This can be really useful if you are happy with the code you experimented with and want to preserve it. The downside is it also includes all your typos and lines of code that might have thrown an error due to mistakes. Those lines may need to be removed from the result.
In the Python window, click in the transcript pane, right-click, and choose
Save Transcript.Browse to a location to save your file as
ArcPyMP_Tutorial.py.You can open a Python file in an Integrated Development Environment (IDE) such as Visual Studio Code, PyCharm, Notepad ++ and many more. If Python was installed with ArcGIS Pro, you have an IDE called IDLE. The following step will assume IDLE is available through a context menu; otherwise, you must open the file using an IDE.
In File Explorer, right-click the file and select Edit with IDLE (ArcGIS Pro) in the context menu.
This is what the content of the Python file will look like if mistakes not were made along the way. The first line is automatically inserted when you export to a Python file.
# coding: utf-8
aprx = arcpy.mp.ArcGISProject("CURRENT")
aprx.defaultGeodatabase = r"C:\Projects\YosemiteNP\Data\Yosemite.gdb"
aprx.save()
print(aprx.filePath)
# C:/Temp/Tutorial/Turorial.aprx
m = aprx.listMaps("Tutorial Map")[0]
lyrFile = arcpy.mp.LayerFile(r"C:\Projects\YosemiteNP\LYRS\Boundary.lyrx")
lyr = m.addLayer(lyrFile)[0]
lyt = aprx.listLayouts("Tutorial Layout")[0]
title = lyt.listElements("TEXT_ELEMENT", "Title")[0]
title.text = "My first arcpy.mp title"
mf = lyt.listElements("MapFrame_Element", "*frame")[0]
ext = mf.getLayerExtent(layer = lyr, selection_only = False)
mf.camera.setExtent(ext)
mf.camera.scale = mf.camera.scale * 1.1
pdf = arcpy.mp.CreateExportFormat("PDF", r"C:\Temp\Yosemite.pdf")
lyt.export(pdf)
This tutorial explained how to complete common workflows using the Mapping module. The next step is to apply these basic workflows to your projects, maps, layers, and more. The arcpy.mp module has more than 60 object and class types, each with collections of unique properties and methods. Class help topics have multiple code samples to help you write productive automation scripts.