I would like to load an AFR file into a data frame in a currently open MXD and the IMap.AddLayer function is not working as expected if the data frame in which to load the AFR file is activate.
And I need to do all this with ArcObjects and from a Python script tool in a toolbox.

Here is what I do:

  1. I apply a raster function template to a raster layer in a given data frame (a map).
  2. I give the filename of the output raster dataset an ".afr" extension to ensure an in-memory temporary AFR file is generated.
  3. I try to load the generated AFR file into my dataframe.

And it is Step 3 that is not working properly: the layer created from the .afr file quickly shows up and then disappears. Which means it seems to be added but does not remain in the data frame, in the table of contents.

At first I thought that the problem came from the .afr file I was not generated properly. But I further investigated and found out that even with a very simple layer addition the IMap.AddLayer function was not working if the targeted data frame (map) was active.

So I created a simple snippet that examplifies the problem so that people interested can reproduce the problem if they wish to.
Info: I am using Pierssen's Snippets module in order to access ArcObjects from Python. See Accessing ArcObjects from Python and Pierssen Snippet module for more information.

import Snippets
import comtypes.gen.esriArcMapUI as esriArcMapUI
import comtypes.gen.esriCarto as esriCarto

##############     MAIN     ##############

pApp = Snippets.GetCurrentApp()
pDoc = pApp.Document
pMxDoc = Snippets.CType(pDoc, esriArcMapUI.IMxDocument)

# Get list of data frames
pMaps = pMxDoc.Maps

# Get first data frame (= first map) 
pMap = pMaps.Item(0)

filePath = r'C:\Temp\myRaster.tif'

pLayer = Snippets.NewObj(esriCarto.RasterLayer, esriCarto.IRasterLayer)
pLayer.Name = "myRasterLayer"    


Table of Contents

The raster layer is then supposed to be loaded in "DataFrame_1", which is the active data frame. But it is not.
During the process it shows up very quickly but does not remain loaded in the data frame. Also, I discovered that if "DataFrame_1" is not active, the layer is properly added. Weird!
Last important point: when this code is run directly from the Python window in ArcMap, it works properly whether the target data frame is active or not.

A few software details before ending: I'm using ArcGIS 10.3, with Python 2.7.

Did someone already encounter the same problem?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.