import * as maptalks from 'maptalks' import FnTask from './Task.js' import Event from './Event' // 从远程中获取数据 function getRemoteData (url) { return new Promise((resolve, reject) => { maptalks.Ajax.getJSON(url, (err, data) => { if (err || !data || !data.features.length) { reject() } else { resolve(data.features) } }) }) } const LOADDING = 1; const SUCCESS = 2; class Reveal extends Event { constructor() { super() this.urlStatue = {} this.cache = {} this.loaddingGeos = {} this.remoteTask = new FnTask({maxParallel: 3}) this.loadTask = new FnTask({maxParallel: 5}) } // 获取数据先从内存,再从远程获取 preloadingFeatures(url) { this.urlStatue[url] = LOADDING this.remoteTask.push( async () => { try { return await getRemoteData(url) } catch (e) { delete this.urlStatue[url] return null } }, data => { this.emit(url, data) } ) } checkFeatureState (id) { for (let key in this.loaddingGeos) { if (~this.loaddingGeos[key].indexOf(id)) return true } } // 分批加载 async inBatches(url, features, addArchitecture) { if (this.urlStatue[url] === LOADDING) { for (let i = 0, len = features.length; i < len; i++) { if (this.checkFeatureState(features[i].id)) { features.splice(i, 1) i-- len-- } else { } } this.loaddingGeos[url] = features.map(f => f.id) this.cache[url] = await addArchitecture(features) this.urlStatue[url] = SUCCESS } } // 加载模型 async loaddingFeatures(url, cb) { this.loadTask.push(async () => { this.preloadingFeatures(url) this.off(url) this.once(url, features => { if (features) { if (document.hidden) { this.once('visibilityshow', () => this.inBatches(url, features, cb)) } else { this.inBatches(url, features, cb) } } }) }) } async loadRegion(urls, loadCb) { for (let key of urls) { if (this.urlStatue[key]) continue this.loaddingFeatures(key, loadCb) } } eliminate (urls) { if (!Array.isArray(urls)) { urls = [urls] } urls.forEach(url => { delete this.urlStatue[url] delete this.cache[url] delete this.loaddingGeos[url] }) } } const reveal = new Reveal() document.addEventListener('visibilitychange', function () { if (!document.hidden) { reveal.emit('visibilityshow') } }); export default reveal