Q:

Dynamically add layer(s) to Layer Group

I have an Openlayers 3 app and users can retrieve stored routes from a web service and display them on a map. Currently each route is added to the top of the index but I'd like them to be inserted into an existing Layer Group.
I've tried using these to methods so far but to no avail:
var collection = map.getLayerGroup(plannerLayers);
collection.push(loadedRoute);

map.addLayer(loadedRoute); // this is the only method which works

map.getLayerGroup(plannerLayers).addLayer(loadedRoute);

Layer management in general is something I seem to be struggling with and ideally I'd like to just be able to interrogate the map for vector layers and add discrete functionality to them. Is there a way to programmatically add/remove layers to a group or even move between groups?

A:

For anyone else that might come across this problem, it turns out (quite obviously to some) that because a Layer Group is an Object containing other Objects but also an array of Objects, this must be identified and the new layer can then be pushed into this. Example below:
/*********************/
/* Get Planner Group */
/*********************/
function getPlannerGroup() {
    var layers = map.getLayers();
    var length = layers.getLength(), l;
    for (var i = 0; i < length; i++) {
        l = layers.item(i);
        var lt = l.get('title');
        // check for layers within groups
        if (lt === 'Planner') { // Title of Group
                if (l.getLayers) {
                var innerLayers = l.getLayers().getArray();
                return innerLayers;
                }
        }
    }
}

...

var collection = getPlannerGroup();
collection.push(loadedRoute);

I hope this helps anyone looking to do something similar ;)

