I have this JSFiddle that can turn the OSM data on and off, the only issue being when it adds it back in the layer is added on top of everything else.

I know this is a relatively simple fix using the insertAt from the maps layer collection but I can't seem to get it working with this example.Perhaps i'm placing the map.insertAt in the wrong place?

2 Answers 2


If you don't want to use the setVisible command, you can also remove the layer entirely.

//to remove the layer at position 0

//to add it again to position 0 (layerName is the variable name you assigned the layer to
map.getLayers().insertAt(0, layerName);

If you are unsure about the position of a layer, you can check them by running:

for (var i=0; i<map.getLayers().getArray().length; i++){
    console.log(i + ' ' + map.getLayers().getArray()[i].getProperties().name)

OpenLayers 3.9 introduced the z-index attribute to map layers, which lets you specify the drawing order of layers. Before 3.9, the layers are drawn in the order they are added to the map, as you have noticed.

This kind of issue is however more properly solved by using the setVisibile method on the layer, since all you want to do is controlling it's visibility.

$('#addOSM').on('click', function() {
$('#removeOSM').on('click', function() {
  • I'd seen the update to 3.9 but still using 3.1 for this particular app, nice answer! Commented Sep 17, 2015 at 21:19

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.