Lazy 数据源
Lazy 数据源示例。 数据源
通常,图层的数据源会在构造图层时提供。如果需要在图层创建之后再设置数据源,可以通过 layer.setSource() 方法完成。
上方地图中的图层在构造时没有数据源。使用下面的链接可以设置或取消设置图层的数据源。在数据源被设置之前,图层不会被渲染。
main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import TileLayer from 'ol/layer/Tile.js';
import OSM from 'ol/source/OSM.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
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lazy 数据源</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>
<script type="module" src="main.js"></script>
</body>
</html>package.json
json
{
"name": "lazy-source",
"dependencies": {
"ol": "10.11.0"
},
"devDependencies": {
"vite": "^8.1.5"
},
"scripts": {
"start": "vite",
"build": "vite build"
}
}