Example of setting a layer source after construction.
Typically, the source for a layer is provided to the layer constructor. If you need to set a layer source after construction, this can be done with the layer.setSource()
method.
The layer in the map above is constructed with no source. Use the links below to set/unset the layer source. A layer is not rendered until its source is set.
<!DOCTYPE html>
<html>
<head>
<title>Lazy Source</title>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://openlayers.org/en/v3.9.0/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.9.0/build/ol.js"></script>
<style>
button.code {
font-family: Monaco,Menlo,Consolas,"Courier New",monospace;
font-size: 12px;
padding: 5px;
margin: 0 5px;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="span12">
<div id="map" class="map"></div>
</div>
</div>
<button id="set-source" class="code">layer.setSource(source)</button>
<button id="unset-source" class="code">layer.setSource(null)</button>
</div>
<script>
var source = new ol.source.MapQuest({layer: 'sat'});
var layer = new ol.layer.Tile();
var map = new ol.Map({
layers: [layer],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
document.getElementById('set-source').onclick = function() {
layer.setSource(source);
};
document.getElementById('unset-source').onclick = function() {
layer.setSource(null);
};
</script>
</body>
</html>