Search code examples
javascriptopenlayers-3guide4you

GUIDE4YOU - How to add a layer and make is visible in the layermenu


I need to add an extra layer dynamically. The layer need to be visible at the layermenu also. How do I approach this?

The be more specific I do have an example:

Problem #1: layer isn't displayed on the map. What do I wrong? There are no javascript errors.

Problem #2: how can I add the layer on the layermenu?

createG4U('#g4u-map', 'conf/client.commented.json', 'conf/layers.commented.json').then(function (map) {
    map.asSoonAs('ready', true, function () {

        var openSeaMap_layer = new ol.layer.Tile({
            title: 'OpenSeaMap',
            name: 'OpenSeaMap',
            code: 'OpenSeaMap',
            datalayer: 'N',
            source: new ol.source.OSM({
                crossOrigin: null,
                url: 'http://t1.openseamap.org/seamark/{z}/{x}/{y}.png'
            })
        });

        alert('Visibility: ' + openSeaMap_layer.getVisible());

        map.get('api').addLayer(openSeaMap_layer);
        });
});

Thanks in advance!

Kind regards,

Sam


Solution

  • You have two choices to achieve that, basing on different ways to create the layer.

    First: If you like to use the api functions, you can pass layerConfigObjects that are the same like the objects in the layerConfig.json file. (They are described here: https://github.com/KlausBenndorf/guide4you/blob/31e118c8f4bc5490dec92d4a03bc53fff08258fd/src/configurators/LayerFactory.js#L37).

    Available api functions are addBaseLayer (underlying maps which deactivate each other, appear in the layerselector), addFeatureLayer (layers on top of the baselayers, can be combined, appear in the layerselector) and addFixedFeatureLayer (like FeatureLayers, but always visible and they don't appear in the layerselector). (btw. addLayer is not an api function and should throw a javascript error) (You can look at all api methods in https://github.com/KlausBenndorf/guide4you/blob/master/src/API.js)

    These functions correspond to adding the same objects directly in the layerConfig.

    Another way to do this is to create the layer as an openlayers layer (like you did in the example) and add it directly to the layergroup it should appear in. The layergroups can be accessed via map.get('baseLayers'), map.get('featureLayers'), map.get('fixedFeatureLayers'). These have an addLayer method and you can use these.

    Either way to have the layers displayed in the layerselector you have to call map.get('UIConfigurator').configureUI() to update the UI.