UNPKG

1.92 kBJavaScriptView Raw
1goog.require('ol.Map');
2goog.require('ol.View');
3goog.require('ol.layer.Tile');
4goog.require('ol.source.TileJSON');
5
6
7/**
8 * Renders a progress bar.
9 * @param {Element} el The target element.
10 * @constructor
11 */
12function Progress(el) {
13 this.el = el;
14 this.loading = 0;
15 this.loaded = 0;
16}
17
18
19/**
20 * Increment the count of loading tiles.
21 */
22Progress.prototype.addLoading = function() {
23 if (this.loading === 0) {
24 this.show();
25 }
26 ++this.loading;
27 this.update();
28};
29
30
31/**
32 * Increment the count of loaded tiles.
33 */
34Progress.prototype.addLoaded = function() {
35 var this_ = this;
36 setTimeout(function() {
37 ++this_.loaded;
38 this_.update();
39 }, 100);
40};
41
42
43/**
44 * Update the progress bar.
45 */
46Progress.prototype.update = function() {
47 var width = (this.loaded / this.loading * 100).toFixed(1) + '%';
48 this.el.style.width = width;
49 if (this.loading === this.loaded) {
50 this.loading = 0;
51 this.loaded = 0;
52 var this_ = this;
53 setTimeout(function() {
54 this_.hide();
55 }, 500);
56 }
57};
58
59
60/**
61 * Show the progress bar.
62 */
63Progress.prototype.show = function() {
64 this.el.style.visibility = 'visible';
65};
66
67
68/**
69 * Hide the progress bar.
70 */
71Progress.prototype.hide = function() {
72 if (this.loading === this.loaded) {
73 this.el.style.visibility = 'hidden';
74 this.el.style.width = 0;
75 }
76};
77
78var progress = new Progress(document.getElementById('progress'));
79
80var source = new ol.source.TileJSON({
81 url: 'https://api.tiles.mapbox.com/v3/mapbox.world-bright.json?secure',
82 crossOrigin: 'anonymous'
83});
84
85source.on('tileloadstart', function() {
86 progress.addLoading();
87});
88
89source.on('tileloadend', function() {
90 progress.addLoaded();
91});
92source.on('tileloaderror', function() {
93 progress.addLoaded();
94});
95
96var map = new ol.Map({
97 logo: false,
98 layers: [
99 new ol.layer.Tile({source: source})
100 ],
101 target: 'map',
102 view: new ol.View({
103 center: [0, 0],
104 zoom: 2
105 })
106});