2

I am a complete beginner to OpenLayers and web mapping in general. I am trying to change the layers' order of my map by modifying the layers' index value, but I cannot get my code to work.

Any hint on what the problem is?

Here is the code:

<!doctype html>
<html lang="en">
<head>
<title>Simple example</title>
<link rel="stylesheet" href="../assets/ol3/css/ol.css" type="text/css" />  
<link rel="stylesheet" href="../assets/css/samples.css" type="text/css" />
</head>
<body>
<button onclick="doSwitch();">Switch layer</button>
<div id="map" class="map"></div>
<script src="../assets/ol3/js/ol.js"> </script> 
<script>
    /* Layers */
    var osmLayer = new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'osm'}),
    });
    var satLayer = new ol.layer.Tile({
        source: new ol.source.MapQuest({layer: 'sat'}),
    });

    /* View and map */
    var view = new ol.View({
        center: ol.proj.transform([-1.8118500054456526, 52.4431409750608], 'EPSG:4326', 'EPSG:3857'),
        zoom: 6
    });
    var map = new ol.Map({
        target: 'map',
    });

    map.addLayer(osmLayer);
    map.addLayer(satLayer);
    map.setView(view);

    /* Switch function */
    function doSwitch(){
        var satIndex = map.getLayerIndex(satLayer);
        if (satIndex === 1) {
            map.setLayerIndex(osmLayer, 1);
            map.setLayerIndex(satLayer, 0);
        } else {
            map.setLayerIndex(osmLayer, 0);
            map.setLayerIndex(satLayer, 1);
        }
    }
</script>
</body>
</html>

Edit

This works on OL 3.10.

        /* Switch function */
    function doSwitch(){
        var satIndex = satLayer.getZIndex();
        if (satIndex === 1) {
            osmLayer.setZIndex(1);
            satLayer.setZIndex(0);
        } else {
            osmLayer.setZIndex(0);
            satLayer.setZIndex(1);
        }
    }
2

You are mixing OpenLayers 2 and OpenLayers 3 code. OpenLayers 3 is not backwards compatible, and you should not expect its API to equal OpenLayers 2.

In OpenLayers 3, layer render ordering is controlled by the zIndex property and the setZIndex method of each layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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