installVueMapApi.js 985 Bytes
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,
	});
}