zIndex helps in managing the stack order of layers. When you add multiple layers in OpenLayers web application, all layers are stored as stack data structure. The layer which is added first, will be at the bottom of stack and layer which is added recently or last, will be on top of stack as shown in below image.
This means when you visualize those layers on map, layer 5 will be on the top and all other layers will be beneath it and they will be rendered accordingly. This is default behavior of OpenLayers. Initially, their zindex is determined by the order in which layers are added. Layer 1 will have smallest zindex and Layer 5 will have highest zindex value.
Basically, zindex decides which layer should be above or beneath the particular layer. Let’s take layers from above image. If zindex of layer 1 is small as compared to layer 2, layer 1 will be beneath the layer 2. If it is greater than layer 2, layer 1 will be above 2. If layer 1 and layer 2 have same zindex value, then layer 2 will be above the layer 1 because it is added recently.
Changing the layer’s zindex value:
You can change the zindex value of a layer using setZIndex method of layer. In below code gist, we are defining three layers at line number 14, 21 and 28. At line number 34, we are adding those layers in map.
If you see at line number 34, I am adding layer_1 first and then layer_2 and layer_3. Initially, layer_1 will have smallest zindex and layer_3 will have largest zindex. So, layer_3 will be at the top.
To change the zindex value of layer, we will use setZIndex method of a layer. At line number, 36, 37 and 38, we are changing the zindex value using this method.
For layer_3, we set 1 as zindex value, for layer_2 we set 2 as zindex value and for layer_1 we set 3 as zindex value. Now, layer_1 has the largest zindex value and layer_3 has the lowest zindex value. Now, layer_1 is on the top and layer_3 is on the bottom.