原文链接及内容

运行界面

图像数据源触发与图像加载相关的事件。您可以监听imageloadstartimageloadendimageloaderror类型的事件来监控图像的加载进度。本例为这些事件注册侦听器,并在地图底部渲染图像加载进度条,进度条根据地图的loadstart和loadend事件显示和隐藏。

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import ImageLayer from 'ol/layer/Image.js';
import ImageWMS from 'ol/source/ImageWMS.js';
import Map from 'ol/Map.js';
import View from 'ol/View.js';

/**
* Renders a progress bar.
* @param {HTMLElement} el The target element.
* @class
*/
function Progress(el) {
this.el = el;
this.loading = 0;
this.loaded = 0;
}

/**
* Increment the count of loading tiles.
*/
Progress.prototype.addLoading = function () {
++this.loading;
this.update();
};

/**
* Increment the count of loaded tiles.
*/
Progress.prototype.addLoaded = function () {
++this.loaded;
this.update();
};

/**
* Update the progress bar.
*/
Progress.prototype.update = function () {
const width = ((this.loaded / this.loading) * 100).toFixed(1) + '%';
this.el.style.width = width;
};

/**
* Show the progress bar.
*/
Progress.prototype.show = function () {
this.el.style.visibility = 'visible';
};

/**
* Hide the progress bar.
*/
Progress.prototype.hide = function () {
const style = this.el.style;
setTimeout(function () {
style.visibility = 'hidden';
style.width = 0;
}, 250);
};

const progress = new Progress(document.getElementById('progress'));

const source = new ImageWMS({
url: 'https://ahocevar.com/geoserver/wms',
params: {'LAYERS': 'topp:states'},
serverType: 'geoserver',
});

source.on('imageloadstart', function () {
progress.addLoading();
});
source.on(['imageloadend', 'imageloaderror'], function () {
progress.addLoaded();
});

const map = new Map({
layers: [new ImageLayer({source: source})],
target: 'map',
view: new View({
center: [-10997148, 4569099],
zoom: 4,
}),
});

map.on('loadstart', function () {
progress.show();
});
map.on('loadend', function () {
progress.hide();
});

界面布局文件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
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Load Events</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
.map {
background: #E0ECED;
}
.wrapper {
position: relative;
}
#progress {
position: absolute;
bottom: 0;
left: 0;
height: 2px;
background: rgba(0, 60, 136, 0.4);
width: 0;
transition: width 250ms;
}
</style>
</head>
<body>
<div class="wrapper">
<div id="map" class="map"></div>
<div id="progress"></div>
</div>
<!-- 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>