installVueMapApi.js
985 Bytes
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
import GLMapSdk from "@/common/glsk-mapapi-sdk";
let singleton = null;
function attachReady(sdk) {
if (typeof sdk.ready === "function") return;
sdk.ready = function mapApiReady(timeoutMs = 30000) {
const inst = this;
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
function tick() {
if (inst.GLMap) {
resolve(inst);
return;
}
if (Date.now() >= deadline) {
reject(new Error("Map SDK load timeout"));
return;
}
setTimeout(tick, 50);
}
tick();
});
};
}
function getOrCreateSdk() {
if (!singleton) {
singleton = new GLMapSdk();
attachReady(singleton);
}
return singleton;
}
/**
* 注册 Vue.prototype.$mapapi:首次访问再实例化 GLMapSdk,并补全 glsk-mapapi-sdk 未提供的 ready()(轮询 GLMap)。
*/
export function installVueMapApi(Vue) {
Object.defineProperty(Vue.prototype, "$mapapi", {
get() {
return getOrCreateSdk();
},
configurable: true,
});
}