1

How can I get all child layers of a given layer group in Openlayers?

I go as far as establishing that a given layer is in fact a group, but then I get stumped:

// Handle visibility control
$('i').on('click', function() {
    var layername = $(this).closest('li').data('layerid');
    var layer = findBy(map.getLayerGroup(), 'name', layername);
    var flagGroup = layer instanceof ol.layer.Group;
    if (flagGroup) {
       ...
    }
});

2 Answers 2

2

childLayers = layer.getLayers()

https://openlayers.org/en/latest/apidoc/ol.layer.Group.html#getLayers

1
  • tks! worked. will post how i accessed them as an aletrnate answer. UPVOTED AND CHOSEN
    – tony gil
    Commented Jul 21, 2017 at 21:30
2

Following up on Marc's answer, this is how implemented it:

// Handle visibility control
$('i').on('click', function() {
    var layername = $(this).closest('li').data('layerid');
    var layer = findBy(map.getLayerGroup(), 'name', layername);
    var flagGroup = layer instanceof ol.layer.Group;
    if (flagGroup) {
       var childLayerArray = layer.getLayers();
       childLayerArray.forEach(function (childLayer) { myFunction(childLayer);});
    }
});

function myFunction(childIn) {
     console.log("Child Layer is named: "+childIn.get('name'));
}

function findBy(layer, key, value) {

    if (layer.get(key) === value) {
        return layer;
    }

    // Find recursively if it is a group
    if (layer.getLayers) {
        var layers = layer.getLayers().getArray(),
                len = layers.length, result;
        for (var i = 0; i < len; i++) {
            result = findBy(layers[i], key, value);
            if (result) {
                return result;
            }
        }
    }

    return null;
}
1
  • 1
    What does the method findBy do? Commented Feb 18, 2018 at 21:06

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.