原文链接及内容

图像切片数据源触发与切片加载相关的事件。您可以监听tileloadstart
、tileloadend
和tileloaderror
类型的事件来监听切片数据加载进度。本例为这些事件注册侦听器,并在地图底部呈现一个加载进度条,进度条根据地图的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 89 90 91 92 93
| import Map from 'ol/Map.js'; import TileLayer from 'ol/layer/Tile.js'; import View from 'ol/View.js'; import XYZ from 'ol/source/XYZ.js';
function Progress(el) { this.el = el; this.loading = 0; this.loaded = 0; }
Progress.prototype.addLoading = function () { ++this.loading; this.update(); };
Progress.prototype.addLoaded = function () { ++this.loaded; this.update(); };
Progress.prototype.update = function () { const width = ((this.loaded / this.loading) * 100).toFixed(1) + '%'; this.el.style.width = width; };
Progress.prototype.show = function () { this.el.style.visibility = 'visible'; };
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 key = 'get_your_own_D6rA4zTHduk6KOKTXzGB'; const attributions = '<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> ' + '<a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>';
const source = new XYZ({ attributions: attributions, url: 'https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=' + key, tileSize: 512, });
source.on('tileloadstart', function () { progress.addLoading(); }); source.on(['tileloadend', 'tileloaderror'], function () { progress.addLoaded(); });
const map = new Map({ layers: [new TileLayer({source: source})], target: 'map', view: new View({ center: [0, 0], zoom: 2, }), });
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>Tile Load Events</title> <link rel="stylesheet" href="node_modules/ol/ol.css"> <style> .map { width: 100%; height: 400px; } .map { background: #85ccf9; } .wrapper { position: relative; } #progress { position: absolute; bottom: 0; left: 0; height: 0; box-shadow: 0px 0px 1px 2px rgb(255,204,0); width: 0; transition: width 250ms; } </style> </head> <body> <div class="wrapper"> <div id="map" class="map"></div> <div id="progress"></div> </div> <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>
|