Select to view content in your preferred language

Adding layer created using Python to the active data frame will not work

4628
16
Jump to solution
10-26-2015 08:10 AM
GerryGabrisch
Frequent Contributor

I have Python code that uses a Model Builder Feature Set as an input to prompt the user to manually create a line inside the data view of the active data frame.  Then Python code calculates the grid north azimuth and the true north azimuth of the line and prints those values to the geoprocessing results window.  The feature set (and code) create in_memory data using CreateFeatureclass_management....That all works fine but what I want to do is add the in_memory data to the active data frame.

I can get the name of the data frame using mxd.activeDataFrame.name but adding the layer is not working.  See my code around line 72 - 74.

Any help is appreciated.

try:
    import sys, traceback
    import arcpy
    import time, math
    
    arcpy.AddMessage("\nGet the Azimuth From A User Defined Line.")
    arcpy.AddMessage("Created by Gerry Gabrisch GISP, GIS Manager Lummi Indian Business Council, geraldg@lummi-nsn.gov\n")
    arcpy.env.overwriteOutput = True
    
    inFC = arcpy.GetParameterAsText(0)
    
    outFL = "outFL"
    outlayer = "outlayer"
    arcpy.MakeFeatureLayer_management(inFC, outFL)
    arcpy.SaveToLayerFile_management(outFL, outlayer)

    def cart2pol(x, y):
        rho = math.sqrt(x**2 + y**2)
        phi = math.atan2(y, x)
        return(rho, phi)
    
    def UnitCircleDegreesToTrueNorthAzimuth(theta):
        '''Converts Arithmatic Degrees (East = 0 then counter clockwise)
        to Geographic Degrees (North = 0 then clockwise).'''
        import math
        #theta = math.degrees(theta)
        theta = theta - 90.0
        if theta < 0:
            theta = theta + 360.0
        theta = -1*(theta * 2 * math.pi / 360.0)
        return 360.0 + math.degrees(theta)
    
    for row in arcpy.da.SearchCursor(inFC, ["OID@", "SHAPE@"]):
    #Set start point
        startpt = row[1].firstPoint
        startX = startpt.X
        startY = startpt.Y
        endpt = row[1].lastPoint
        endX = endpt.X
        endY = endpt.Y
    
    arcpy.AddMessage("Normalizing coordinates...")
    x = endX - startX
    y = endY - startY
    
    arcpy.AddMessage("Radians, degrees, and grid convergence, oh my!\n")
    pol = cart2pol(x, y)
    degs = math.degrees(pol[1])
    
    azi = UnitCircleDegreesToTrueNorthAzimuth(degs)
    
    mxd = arcpy.mapping.MapDocument("CURRENT")
    spacRef = mxd.activeDataFrame.spatialReference
    
    tempFC = arcpy.CreateFeatureclass_management("in_memory", "tempFC", geometry_type = "POINT", spatial_reference = spacRef )
    arcpy.AddField_management(tempFC, "angle", "DOUBLE")
    
    cursor = arcpy.da.InsertCursor(tempFC, ["SHAPE@XY"])
    xy = (startX, startY)
    cursor.insertRow([xy])
    
    arcpy.CalculateGridConvergenceAngle_cartography(tempFC, "angle")
    
    for row in arcpy.da.SearchCursor(tempFC, ["angle"]):
        convergence = row[0]
    
    arcpy.AddMessage("Line azimuth from grid north in degrees = " + str(azi))
    azi = str(azi + convergence)
    arcpy.AddMessage("Line azimuth from true north in degrees= " + azi)
    
    
    arcpy.mapping.AddLayer(mxd.activeDataFrame.name, tempFC, "TOP")
    arcpy.RefreshActiveView()
    arcpy.RefreshTOC()
    
    time.sleep(10)
    arcpy.AddMessage("\nClosing")

except arcpy.ExecuteError: 
    msgs = arcpy.GetMessages(2) 
    arcpy.AddError(msgs)  
    arcpy.AddMessage(msgs)
except:
    tb = sys.exc_info()[2]
    tbinfo = traceback.format_tb(tb)[0]
    pymsg = "PYTHON ERRORS:\nTraceback info:\n" + tbinfo + "\nError Info:\n" + str(sys.exc_info()[1])
    print pymsg


0 Kudos
16 Replies
GerryGabrisch
Frequent Contributor

Luke, sorry, nope, neither solutions worked..

arcpy.mapping.AddLayer(mxd.activeDataFrame, tempFC,"TOP")

arcpy.mapping.AddLayer(mxd.activeDataFrame, "in_memory\\tempFC","TOP")

...but you are right about the two different error handlers.  I have been using that method (copied from the ESRI arcpy examples) for years.

0 Kudos
LukeSturtevant
Frequent Contributor

Gerry what is the error message giving you exactly?

0 Kudos
GerryGabrisch
Frequent Contributor

I don't get any errors, the code executes fine, but nothing is added to the TOC.

0 Kudos
LukeSturtevant
Frequent Contributor

Oh wait I didn't notice this before, but in addition to changing to a data frame object you also need to generate a mapping layer object to add to your TOC first:

lyr = arcpy.mapping.Layer(tempFC)

arcpy.mapping.AddLayer(mxd.activeDataFrame, lyr ,"TOP")

Hopefully that will solve the issue.

0 Kudos
GerryGabrisch
Frequent Contributor

Luke, shouldn't that be:

lyr = arcpy.mapping.Layer(tempFC)

arcpy.mapping.AddLayer(mxd.activeDataFrame, lyr,"TOP")

In any case, it is still not working.

0 Kudos
LukeSturtevant
Frequent Contributor

Yes you are correct. I should have referenced the layer object. Did you try this yet:

lyr = arcpy.mapping.Layer("in_memory\\tempFC")

arcpy.mapping.AddLayer(mxd.activeDataFrame, lyr,"TOP")

GerryGabrisch
Frequent Contributor

Worked!  Thanks, Luke!

0 Kudos