AnsweredAssumed Answered

Update symbology using arcpy.UpdateLayer

Question asked by WarrenDz on Jun 11, 2015

Hi There,

 

I'm having trouble updating the symbolization of a raster layer in my mxd using python. The script is executed from a python addin tool and has the user drag a bounding box around some features and then reads an attribute field named 'PATH_TO_IMAGE' and adds this image to the map (it's a georeferenced .png). Adding it to the project works fine but it is added with some default coloUr ramp that is not B&W. I attempt to update this symbolization using a layer file I have packaged with the addin but for some reason the colour ramp will not change and the arcpy.UpdateLayer does not print messages for me to figure out why.

 

*Note: I attempt to update the symbolization of line 81.

 

Can anyone see where I am going wrong? It seems like lots of people get hung on on this...

 

import arcpy
import pythonaddins
import os
# set relative path of addin installation
relPath = os.path.dirname(__file__)

class ImageAdder(object):
    """Implementation for IndexAssistant_addin.ImageAdder (Tool)"""
    def __init__(self):
        self.enabled = False
        self.shape = "Rectangle"
        self.cursor = 3 # Crosshair

    def onRectangle(self, rectangle_geometry):
        # Construct rectangle geometry
        ext = rectangle_geometry

        lowerLeft = ext.lowerLeft
        upperLeft = ext.upperLeft
        lowerRight = ext.lowerRight
        upperRight = ext.upperRight

        array = arcpy.Array()
        array.add(upperLeft)
        array.add(upperRight)
        array.add(lowerRight)
        array.add(lowerLeft)
        array.add(upperLeft)

        poly = arcpy.Polygon(array)

        # Get the 1st Data Frame
        mxd = arcpy.mapping.MapDocument('current')
        df = arcpy.mapping.ListDataFrames(mxd)[0]

        # Set the Index from IndexSelector combo box
        indexSelection = IndexSelector.selection

        # Find layer to match the selected index
        indexLayer = arcpy.mapping.ListLayers(mxd,indexSelection,df)[0]
        indexPath = indexLayer.dataSource
        # Make feature layer to do the work on
        arcpy.MakeFeatureLayer_management(indexLayer,'indexlyr')

        # Select features based on polygon rectangle
        arcpy.SelectLayerByLocation_management('indexlyr','INTERSECT',poly)

        # Count number of selected features and print to python window
        result = arcpy.GetCount_management('indexlyr')
        count = int(result.getOutput(0))
        print('There were {} feature(s) selected in the {} layer.'.format(count,indexLayer))

        # Try to get path
        ## path = indexLayer.

        # Test for number of features and end if too many
        if count > 0:
            c = 0
            # Open Search Cursor to read the image pathes of the selected features
            with arcpy.da.SearchCursor('indexlyr',"PATH_TO_IMAGE") as cursor:
                for row in cursor:
                    if c <= count:
                        try:
                            # Manipulate the path to remove a few characters that are printed
                            pathToImage = str(row)
                            pathToImage1 = pathToImage.replace("(u'",'')
                            pathToImage2 = pathToImage1.replace("',)",'')
                            # Instantiate the path as a layer object
                            addLayer = arcpy.mapping.Layer(pathToImage2)
                            try:
                                # Add the raster layer to the map
                                arcpy.mapping.AddLayer(df,addLayer,"BOTTOM")
                                # Set the source of the layer file with the correct B&W colour ramp
                                symbolLayer = os.path.join(relPath,'B_W.lyr')
                                try:
                                    ##updateLayer = arcpy.mapping.ListLayers(mxd, updateLayer, df)[0]
                                    # Instantiate the path to the template colour ramp as a layer object
                                    sourceLayer = arcpy.mapping.Layer(symbolLayer)
                                    updateLayer = arcpy.mapping.ListLayers(mxd, addLayer, df)[0]
                                    print('Update Layer: {}\nSource Layer: {}\nSymbol Layer: {}'.format(updateLayer,sourceLayer,symbolLayer))
                                    arcpy.mapping.UpdateLayer(df,updateLayer,symbolLayer,True)
                                except:
                                    print('Symbology could not be changed.')
                            except:
                                pythonaddins.MessageBox('The georeferenced plan {} could not be added to the map, check the path name and ensure it exists.'.format(addLayer))

                            # Refresh TOC with new layer
                            arcpy.Delete_management('indexlyr')
                            arcpy.RefreshActiveView()
                            arcpy.RefreshTOC()
                            c += 1
                        except:
                            pythonaddins.MessageBox("An error has occured while trying to add plans to the ArcMap project, please report this problem","Error Adding Plans")
                    else:
                        pass
        else:
            pythonaddins.MessageBox("There were no feature selected. Please select one and try again.","No Selection")

Outcomes