Change layer order

208
1
04-27-2021 07:54 AM
GaryB
by
New Contributor III

I'm trying to implement functionality so the user can change the order of layers.  My "move-layer-up" functionality works but I cannot get the "move-layer-down" functionality working and the layer always seems to end up in some random spot.  Any pointers would be appreciated.

 

layerList.on("trigger-action", function (event) {

    if (event.action.id === "move-layer-up") {

        var layerToMoveName = event.item.title;
        var layerToMoveIdx = -1

        for (var i = 0; i < layerList.viewModel.operationalItems.length; i++) {
            var item = layerList.viewModel.operationalItems.getItemAt(i)
            if (item.title === layerToMoveName) {
                layerToMoveIdx = i
            }
        }

        if (layerToMoveIdx > 0) {
            layerList.viewModel.moveListItem(event.item, null, null, layerToMoveIdx);
        }
    }
    else if (event.action.id === "move-layer-down") {

        var layerToMoveName = event.item.title;
        var layerToMoveIdx = -1

        for (var i = 0; i < layerList.viewModel.operationalItems.length; i++) {
            var item = layerList.viewModel.operationalItems.getItemAt(i)
            if (item.title === layerToMoveName) {
                layerToMoveIdx = i
            }
        }

        if (layerToMoveIdx < layerList.viewModel.operationalItems.length) {
            layerList.viewModel.moveListItem(event.item, null, null, layerToMoveIdx + 1);
        }

    }

}

 

0 Kudos
1 Reply
MichaelBoschert
New Contributor III

Hey @GaryB 

I had the same problem today.

My solution was to assign each layer an id which is equal to his initial position in the layer.
Surely you could also use another layer attribute.

//sample layers
const graphicsLayer1 = new GraphicsLayer({
  title: "samplelayer1",
  id: 1
});
map.add(graphicsLayer1);
const graphicsLayer2 = new GraphicsLayer({
  title: "samplelayer2",
  id: 2
});
map.add(graphicsLayer2);

//triggeraction-part
else if (id === "move-layer-up"){
              position = event.item.layer.id;
              if (1 !== +position){
                new_position = +position - +1;
                event.item.layer.id = new_position;
                console.log("new position: "+event.item.layer.id)
                layerList.viewModel.moveListItem(event.item, null, null, new_position);
              }
            }
            else if (event.action.id === "move-layer-down") {
              maxPosition = layerList.viewModel.operationalItems.length
              console.log("maxPosition:"+maxPosition);
              position = event.item.layer.id;
              if (maxPosition !== +position){
                new_position = +position + +1;
                event.item.layer.id = new_position;
                console.log("new position: "+event.item.layer.id)
                layerList.viewModel.moveListItem(event.item, null, null, new_position);
              }
            }