I did a few changes to my code to get it to work.
First I declared var baselayers as new ol.layer.Group at the beginning.
Added empty baselayers to the map and then
I defined the layers one after the other and added them to the baselayer.
Beside this I wrapped my code in
function init() {
document.removeEventListener('DOMContentLoaded', init);
and removed the body onload = "initialize()"-function instead.
here how the js-code looks like:
function init() {
document.removeEventListener('DOMContentLoaded', init);
var parser = new ol.format.WMTSCapabilities();
var baselayers= new ol.layer.Group({
title: 'Background-Layers',
layers: []
});
var toplayers = new ol.layer.Group({
title: 'Regions',
layers: []
});
fetch('http://wmts1.geoportail.lu/opendata/wmts/1.0.0/WMTSCapabilities.xml').then(function(response) {
return response.text();
}).then(function(text) {
var result = parser.read(text);
var hybrid_s = ol.source.WMTS.optionsFromCapabilities(result, {
layer: 'hybrid',
matrixSet: 'EPSG:3857'
});
var ortho_2016_s = ol.source.WMTS.optionsFromCapabilities(result, {
layer: 'ortho_2016',
matrixSet: 'EPSG:3857'
});
var osm = new ol.layer.Tile({
source: new ol.source.OSM(),
opacity: 1.0,
title: 'OpenStreetMap',
baseLayer: true,
visible: false,
});
var hybrid = new ol.layer.Tile({
opacity: 1.0,
title: 'Hybrid',
baseLayer: true,
visible: true,
source: new ol.source.WMTS(/** @type {!olx.source.WMTSOptions} */ (hybrid_s))
});
var ortho_2016 = new ol.layer.Tile({
opacity: 1.0,
title: 'Ortho 2016',
baseLayer: true,
visible: false,
source: new ol.source.WMTS(/** @type {!olx.source.WMTSOptions} */ (ortho_2016_s))
});
baselayers.setLayers(new ol.Collection([osm, hybrid, ortho_2016]));
});
var map = new ol.Map({
target: 'map',
view: new ol.View({
center: [685000,6380000],
zoom: 11
}),
controls: ol.control.defaults().extend([
new ol.control.LayerSwitcher() // http://viglino.github.io/ol3-ext/examples/map.switcher.html
]),
layers: [baselayers, toplayers],
interactions: ol.interaction.defaults().extend([
new ol.interaction.Select({
layers: [baselayers, toplayers]
})
]);
}
document.addEventListener('DOMContentLoaded', init);
Best Answer
If you move your
<script>
tags containing your .js file into<body>
the map will show.