4

I have a map object and I am trying to move an existing layer from that map object into a newly created group layer in the same map object.

aprx = arcpy.mp.ArcGISProject("Current")
mp = aprx.listMaps()[0]
lyr = mp.listLayers()[0]
group = mp.createGroupLayer("New Group")

I cannot find any documentation describing this. On the Map Documentation page it says this:

The moveLayer method will move a layer within a map and also into and out of group layers in the same map. The move_layer and reference_layer must reside in the same map. A layer cannot be moved from one map to a different map even within the same project. Use addLayer, addLayerToGroup, or insertLayer instead.

But it doesn't describe how. I'd rather not use addLayerToGroupand then use removeLayer (to remove the original layer) as this seems inefficient.

1
  • Have you actually tried this? It seems as if "moving" would not keep the original, so your objection is moot.
    – Vince
    Commented Feb 7 at 5:23

1 Answer 1

3

You want to use addLayerToGroup... see attached example code...

aprx = arcpy.mp.ArcGISProject("CURRENT")
mp = aprx.listMaps()[0]
#mp = aprx.listMaps("Specific Map Name")[0]  Use this instead if you have multiple maps in your project

if "MyGroupLayer" not in [lyr.name for lyr in mp.listLayers()]:
    mp.createGroupLayer("MyGroupLayer")

lyr_to_move = mp.listLayers("My Layer Name")[0]
group_layer = mp.listLayers("MyGroupLayer")[0]

# Use this to move layers (but not into a group layer)
#mp.moveLayer(group_layer, lyr_to_move, "AFTER")

# Use this to move a layer into a group layer
mp.addLayerToGroup(group_layer, lyr_to_move, "AUTO_ARRANGE")
1
  • The frustrating thing here though is that you're not technically moving the layer, you're creating a copy of the layer. So the original layer remains and you've made a copy that now lives in the group layer. You will have to use mp.removeLayer(lyr_to_move) to remove the original...
    – Kat
    Commented Jul 5 at 3:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.