Z-index in OpenLayers 3: layer ordering in OL3

Try something like:

map.getLayers().setAt(99, markers)

The list of layers is in an object inheriting from an ol.Collection. See the API doc for it.

Be careful, I'm pretty sure, you can't use arbitrary number like 99 in setAt: first arg is for the position in the array of layers and the second arg is for the layer element reference you want to move. To get number of layers, just use map.getLayers().getArray().length

Although you see we can get a JS array for layers, I'm not sure manipulating this array directly is the best way because layers can have events attached. You can use the ol.Collection methods instead.


It is not as easy as it used to be, but there are some helper methods for the collection. That should allow you to do similar things as ThomasG77 described above.

Assuming you have a map named map, with 4 layers i.e. [base_layer, coastlines, heatmap, markers]

Then you can get the collection via map.getLayers(), and the array of layers via map.getLayers().getArray(), and individual layers via

var heatmap = map.getLayers().getArray()[2]

You can manipulate the layer order via the collection methods. It will probably help to create some helper functions like:

function moveLayerBefore(map, old_idx, new_idx){
  var layer = map.getLayers().removeAt(old_idx);
  map.getLayers().insertAt(new_idx, layer);
}

Hopefully you have the ability to identify your layers and find them, I set an id on creation like layer.set("layer_id" 44), which can then be retrieved via layer.get("layer_id"). Then you can have a findLayer helper loop through your layer array and return the layer index.

function findLayer(map, layer_id){
  var layer_idx = -1;
  $.each(map.getLayers().getArray(), function (k,v){
    var this_layer_id = v.get("layer_id")
    if(this_layer_id == layer_id){
      layer_idx = k;
    }
  });
  return layer_idx;
}   

In this way I can have something like moveLayerBefore(map, findLayer(44), findLayer(22));

Anyway, there are a ton of methods in the collection, but hopefully this helps you get started. And sorry if there are bugs in that code, that is all mind compiled... :)


based on srussking answer I wrote the following code assuming the main map object called map and it is a global var, I preferred using find layer by name and not by id,

here is my code:

function moveLayerBefore(old_idx, new_idx){
    if((old_idx === -1) || (new_idx === -1)){
        return false;
    }

    layer = map.getLayers().removeAt(old_idx);
    map.getLayers().insertAt(new_idx, layer);
}

function findLayer(layer_name){
    var layer_idx = -1;
    $.each(map.getLayers().getArray(), function (k,v){
        var this_layer_name = v.get('name');
        if(this_layer_name == layer_name){
            layer_idx = k;
        }
    });

    return layer_idx;
}

// set name1 before name2
moveLayerBefore(findLayer('name1'),findLayer('name2'));