Layer definition query and symbology not updating using arcpy

3986
14
08-06-2018 11:28 AM
AdelaideZumwalt1
Occasional Contributor II

Layer definition query and symbology not updating using arcpy - what am I missing?

import arcpy, os
arcpy.env.overwriteOutput = True
grab = arcpy.GetParameterAsText(0)
prep_list = grab.split(";")

mxd_c = arcpy.mapping.MapDocument(r"T:\GIS\Projects\GIS\Online\MapDocuments\FeederMapCover.mxd")
lyrs_c = arcpy.mapping.ListLayers(mxd_c)

feederList = ["HB2", "HB3"]
print "got feeder list"
arcpy.AddMessage("...starting map book...")

for feeder in feederList:
        arcpy.env.overwriteOutput = True
        for lyr in arcpy.mapping.ListLayers(mxd_c):
            if lyr.name == "Overhead":
                lyr.definitionQuery = "esUplineFeeder = '" + feeder + "'"
            if lyr.name == "Primary Underground Conductor":
                lyr.definitionQuery = "esUplineFeeder = '" + feeder + "'"
        print "Definition Queries Set" + feeder
        # Find Overview Data Frame and Zoom to the Map Index
        df = arcpy.mapping.ListDataFrames(mxd_c, "Layers")[0]
        zoomLayer = arcpy.mapping.ListLayers(mxd_c, "Overhead", df)[0]
        df.extent = zoomLayer.getSelectedExtent(False)
        df.scale = df.scale * 1.5
        print "Zoomed Successfully"

        # Make and Add the FeederMapIndexLAYER feature layer to the map and refresh the view
        arcpy.env.workspace = r"T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb"
        FeederMap = "T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb\FeederMapIndex"
        arcpy.MakeFeatureLayer_management(FeederMap"FeederMapIndexLAYER")
        print "Feature Layer Created"
        addLayer = arcpy.mapping.Layer('FeederMapIndexLAYER')
        print "Feature Layer Added to Map"
        arcpy.mapping.AddLayer(df, addLayer)
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()

        # Field Calculator InMap = 0
        arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression= 0 )
        print "Index Field Calculator Worked"

        # Select FeederMapIndexLayer polygons that intersect Overhead Lines and Calculate FeederMapIndex = 1
        Selection = arcpy.SelectLayerByLocation_management('FeederMapIndexLAYER', 'INTERSECT', 'Overhead')
        print "Index Selection Completed"
        arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression= 1 )
        print "Index Field Calculator Worked"

        #Set FeederMapIndex Layer Definition Query and Refresh Map
        for lyr in arcpy.mapping.ListLayers(mxd_c):
            if lyr.name == "FeederMapIndexLAYER":
                lyr.definitionQuery = "InMap = 1"
                arcpy.RefreshTOC()
                arcpy.RefreshActiveView()
                print "Index Definition Query Worked"

        #Export the Map to a PDF
        arcpy.ApplySymbologyFromLayer_management('FeederMapIndexLAYER', 'C:/Users/azumwalt.UECOOP/Desktop/FeederMapIndex.lyr')
        arcpy.RefreshTOC()
        arcpy.RefreshActiveView()
        outputPath = r"Z:\FeederMaps\PDFs\Map" + feeder + "Cover.pdf"
        arcpy.mapping.ExportToPDF(mxd_c, outputPath)
        print"Map Book Printed" + feeder

print "complete"
0 Kudos
14 Replies
AdelaideZumwalt1
Occasional Contributor II

Hi Xander,

I updated the code so the feature layer is created before I iterated through the feeders - thank you!

Now when I open up the first mxd (TEST1) - having only run the code up until this point. The definition queries are present. When I manually type in the code into ArcMap (see screenshot) it works! Yay!

BUT.... When I run the code until the second mxd (TEST2) with seemingly the same code that was manually entered in ArcMap and open the map... It is obvious a selection was made before the CalculateField_managemenet tool was run (although nothing is selected when I open the map), and instead of just the overhead with the def. query being used during SelectLayerByLocation, ALL of the overhead was used. So every index that intersected an overhead line (1032/2032) is now InMap = 1. There should only be 17. 

I'm not sure why what I'm running in ArcMap is not doing the same thing in my code. Am I missing something obvious?

Updated Code:

import arcpy
arcpy.env.overwriteOutput = True
grab = arcpy.GetParameterAsText(0)
prep_list = grab.split(";")

mxd_c = arcpy.mapping.MapDocument(r"T:\GIS\Projects\GIS\Online\MapDocuments\FeederMapCover.mxd")
lyrs_c = arcpy.mapping.ListLayers(mxd_c)
df = arcpy.mapping.ListDataFrames(mxd_c)[0]

feederList = ["HB2", "HB3"]
print "got feeder list"
arcpy.AddMessage("...starting map book...")

# Make and Add the FeederMapIndexLAYER feature layer to the map
arcpy.env.workspace = r"T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb"
FeederMap = "T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb\FeederMapIndex"
arcpy.MakeFeatureLayer_management(FeederMap, "FeederMapIndexLAYER")
print "Feature Layer Created"
layer = arcpy.mapping.Layer("FeederMapIndexLAYER")
arcpy.mapping.AddLayer(df,layer,"AUTO_ARRANGE")
print "Feature Layer Added to Map"

for feeder in feederList:
        arcpy.env.overwriteOutput = True
        for lyr in arcpy.mapping.ListLayers(mxd_c):
            if lyr.name == "Overhead":
                lyr.definitionQuery = "esUplineFeeder = '" + feeder + "'"
            if lyr.name == "Underground":
                lyr.definitionQuery = "esUplineFeeder = '" + feeder + "'"
        mxd_c.saveACopy("Z:\FeederMaps\MXDs\TEST1_" + feeder + ".mxd")
        arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression=0)
        arcpy.SelectLayerByLocation_management('FeederMapIndexLAYER', 'INTERSECT', 'Overhead')
        arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression=1)
        mxd_c.saveACopy("Z:\FeederMaps\MXDs\TEST2_" + feeder + ".mxd")
0 Kudos
AdelaideZumwalt1
Occasional Contributor II

I'm at a loss. I can't get these two lines to work properly outside of ArcMap.

The arcpy.SelectLayerByLocation_management tool does not recognize any definition queries set either in the code or in the map beforehand. Does anyone else have this issue? Is this a bug? 

arcpy.SelectLayerByLocation_management('FeederMapIndexLAYER', 'INTERSECT', 'OverheadLAYER')
arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression=1)
0 Kudos
DanPatterson_Retired
MVP Emeritus

the only thing you haven't tried is saving the layers to disk (ie as .lyrx files) prior to selectlayerbylocation

0 Kudos
AdelaideZumwalt1
Occasional Contributor II

You mean doing this in Pro instead?

0 Kudos
AdelaideZumwalt1
Occasional Contributor II

I ended up just using this (albeit long) workaround: 

Make Overhead a Layer

Add Layer to Map (probably could remove this step)

FeatureClassToFeatureClass (with expression)

Make New Feature Class a Layer

SelectLayerByLocation using new Layer

- I'm also going to have to delete the new feature class at some point. 

import arcpy
arcpy.env.overwriteOutput = True
grab = arcpy.GetParameterAsText(0)
prep_list = grab.split(";")

mxd_c = arcpy.mapping.MapDocument(r"T:\GIS\Projects\GIS\Online\MapDocuments\FeederMapCover.mxd")
lyrs_c = arcpy.mapping.ListLayers(mxd_c)
df = arcpy.mapping.ListDataFrames(mxd_c)[0]

print "got feeder list"
arcpy.AddMessage("...starting map book...")

# Make and Add the FeederMapIndexLAYER feature layer to the map
FeederMap = "T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb\FeederMapIndex"
Overhead =  "Database Connections\ElectricModel - azumwalt.sde\ElectricModel.DBO.UEC\ElectricModel.DBO.Overhead"
arcpy.MakeFeatureLayer_management(FeederMap, "FeederMapIndexLAYER")
arcpy.MakeFeatureLayer_management(Overhead, "OverheadLAYER")
layer = arcpy.mapping.Layer("FeederMapIndexLAYER")
layerOH = arcpy.mapping.Layer("OverheadLAYER")
arcpy.mapping.AddLayer(df,layer,"AUTO_ARRANGE")
arcpy.mapping.AddLayer(df,layerOH,"BOTTOM")
expression = "esUplineFeeder = 'HB2'"
arcpy.FeatureClassToFeatureClass_conversion(Overhead, "T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb","OverheadDeleteMe",expression)
arcpy.MakeFeatureLayer_management("T:\GIS\Projects\GIS\Online\SpatialData\FeederMaps.gdb\OverheadDeleteMe","OverheadDeleteMe", )
overheadDeleteMe = arcpy.mapping.Layer("OverheadDeleteMe")
arcpy.mapping.AddLayer(df,overheadDeleteMe,"BOTTOM")

print "Feature Layer Added to Map"
for lyr in arcpy.mapping.ListLayers(mxd_c):
    if lyr.name == "Overhead":
        lyr.definitionQuery = "esUplineFeeder = 'HB2'"
arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression=0)
arcpy.SelectLayerByLocation_management('FeederMapIndexLAYER', 'INTERSECT', "OverheadDeleteMe")
arcpy.CalculateField_management("FeederMapIndexLAYER", "InMap", expression=1)
mxd_c.saveACopy("Z:\FeederMaps\MXDs\SHORTTEST_.mxd")

Not sure this is really a "correct answer" but more of a workaround. 

Also - I'm not using Pro yet to do this as I want to create a tool and upload it using WebAppBuilder and I believe with Pro you have to have Portal and we are not quite there yet. (Correct me if I'm wrong).