I am trying to automate various tasks in ArcGIS Desktop (using ArcMap generally) with Python, and I keep needing a way to add a shapefile to the current map. (And then do stuff to it, but that's another story).
The best I can do so far is to add a layer file to the current map, using the following ("addLayer" is a layer file object):
def AddLayerFromLayerFile(addLayer):
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, df, addLayer
However, my raw data is always going be shapefiles, so I need to be able to open them. (Equivalently: convert a shapefile to a layer file without opening it, but I'd prefer not to do that).
Answer
Here's what I found worked:
import arcpy
from arcpy import env
# get the map document
mxd = arcpy.mapping.MapDocument("CURRENT")
# get the data frame
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]
# create a new layer
newlayer = arcpy.mapping.Layer(path_to_shapefile_or_feature_class)
# add the layer to the map at the bottom of the TOC in data frame 0
arcpy.mapping.AddLayer(df, newlayer,"BOTTOM")
The dataframe (variable df) that this code will put the new layer into is the first dataframe in the map document. Also note that this code adds the data as a new layer at the bottom of the TOC. You can also use the other arrangement options, which are "AUTO_ARRANGE" and "TOP".
No comments:
Post a Comment