Masthead

Mapping

arcpy allows you to manipulate mxd files including adding and removing layers. From within ArcGIS, you can maniplate the layers that are being displayed to the user. If we're running code outside ArcGIS, we cannot manuipurlate what is shown to the user, but we can create new mxd files and manipulate the layers wihtin them. You might want to do this to add a large number of shapefiles to an mxd or to make a number of mxd files with different contents.

1. Getting the Map Document

You need to have an existing "mxd" file which we will manipulate and then save as a new file. The code below will get the map document and then gain access to the first data frame within the document.

NewDocument=arcpy.mapping.MapDocument("C:\\Temp\\Initial.mxd")
DataFrames=arcpy.mapping.ListDataFrames(NewDocument, "*")
DataFrame=DataFrames[0]

Now we need to make a layer file (".lyr") and save it to a file.

# create the new layer and add it to the map
arcpy.management.MakeFeatureLayer(TheShapefilePath,LayerName)
arcpy.SaveToLayerFile_management(LayerName, LayerPath, "ABSOLUTE") 

Then, we load the layer into a Layer object and add it to the frame.

WhaleLayer = arcpy.mapping.Layer(WhaleLayerPath)
arcpy.mapping.AddLayer(DataFrame, WhaleLayer)

Finally, we save the mxd as a new file

NewDocument.saveACopy(r"C:\\Temp\\" + TheFileName + ".mxd")

If you wish to reuse the map document, you'll need to remove the layers with the following function. If you add additional layers, they will also need to have unique names or ArcGIS will throw an error.

arcpy.mapping.RemoveLayer(DataFrame, TheLayer)

Note: while this looks rather cumbersome, it is the only approach we found that worked either in ArcGIS 10 or 10.1.

 

 

 

© Copyright 2018 HSU - All rights reserved.