Sunday 27 August 2017

arcgis 10.2 - Checking if layers in dataframe using ArcPy?


I working on mxd (I work with ArcMap 10.2.2 & python 2.7.5.) that have 100 layers. I'm trying with python script to add layers to dataframe and check if the layers are within the dataframe. if it within I want that python will add the layers to the table of content, and if it not within the dataframe- the python will remove the layers. Manually I can do it by adding each layer and see if it in the dataframe and then start to choose what to remove, but it will take a lot of time. I also can use this option:


legend properties-->legend


and it also will take a lot of time. I have this script:


import arcpy
from arcpy import env
area= '162000 631000 172000 641000'
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]
df.extent = area
for lyr in arcpy.mapping.ListLayers(mxd, "",df):
if lyr.name == "residence":
addLayer = arcpy.mapping.Layer(r"C:\project\layers\residence.lyr")
arcpy.mapping.AddLayerToGroup(df, lyr, addLayer, "BOTTOM")
else lyr.dataSource == r"F:\GIS\topo_50000\50000.sid":

arcpy.mapping.RemoveLayer(df, lyr)

if lyr.name == "rivers2":
addLayer = arcpy.mapping.Layer(r"C:\project\layers\rivers2.lyr")
arcpy.mapping.AddLayerToGroup(df, lyr, addLayer, "BOTTOM")
mxd.save()
del mxd

I hope someone can describe an easy way to accomplish what I'm after with python script?



Answer




Using the statement below, you could create a temp polygon layer that correspondes to the dataframe extent, iterate and select (select by location) each layer in the map, if selection is > 0 than layer exists within dataframe extent if not then remove.


# create temp polygon layer to dataframe extent
dfAsFeature = arcpy.Polygon(arcpy.Array([df.extent.lowerLeft, df.extent.lowerRight, df.extent.upperRight, df.extent.upperLeft]),df.spatialReference)

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...