Monday, 2 November 2015

arcpy - How to remove layers that are not in visible df extent


I am working on ArcMap 10.3 and I have a map with 50 layers in it.


I am trying to check if layers are in a data frame.


Unlike How to check if layers in a dataframe with Arcpy, I want to define the area to the current data frame.



My code is:


import arcpy,os,sys,string
import arcpy.mapping
from arcpy import env


env.workspace = r"C:\Project"
for mxdname in arcpy.ListFiles('*.mxd'):
print mxdname
mxd = arcpy.mapping.MapDocument(r"C:\Project\\" + mxdname)

df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
data_frame = df
for lyr in arcpy.mapping.ListLayers(mxd,"",df):
if lyr in data_frame == False:
arcpy.mapping.RemoveLayer(df, lyr)
print lyr
mxd.save()
del mxd

and I get:



 >>> 
Project.mxd
>>>

but no layers have been removed.



Answer



The Extent object supports a 'disjoint' (i.e. does not intersect) method.


Try something like:


for mxdname in arcpy.ListFiles('*.mxd'):


print mxdname
mxd = arcpy.mapping.MapDocument(os.path.join(env.workspace, mxdname))
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
for lyr in arcpy.mapping.ListLayers(mxd, "" ,df):
if df.extent.disjoint(lyr.getExtent()):
arcpy.mapping.RemoveLayer(df, lyr)
print lyr

mxd.save()


del mxd

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...