原文链接及内容

运行界面

通常情况下,我们在构建图层对象时就为其设置数据源,如果您需要在图层构建后设置图层数据源,可以使用layer.setsource()方法完成。
上图中的图层是在没有数据源的情况下构建的,使用下面的按钮来设置/取消设置图层数据源。一个图层只有配置好数据源之后才会被渲染。

main.js代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import TileLayer from 'ol/layer/Tile.js';
import View from 'ol/View.js';

const source = new OSM();

const layer = new TileLayer();

const map = new Map({
layers: [layer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});

document.getElementById('set-source').onclick = function () {
layer.setSource(source);
};

document.getElementById('unset-source').onclick = function () {
layer.setSource(null);
};

界面布局文件index.html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lazy Source</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
button.code {
font-family: Monaco,Menlo,Consolas,"Courier New",monospace;
font-size: 12px;
padding: 5px;
margin: 0 5px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<button id="set-source" class="code">layer.setSource(source)</button>
<button id="unset-source" class="code">layer.setSource(null)</button>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>