| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- if (!window) {
- throw Error("AMap JSAPI can only be used in Browser.");
- }
- let status = "notload";
- let config = {
- key: "",
- version: "1.4.15",
- plugins: []
- };
- const onloadCBKs = [];
- const onload = function(callback) {
- if (typeof callback == "function") {
- if (status == "loaded") {
- callback(window.AMap);
- return;
- }
- onloadCBKs.push(callback);
- }
- };
- const load = function(options) {
- return new Promise((resolve, reject) => {
- if (status == "notload") {
- //初次加载
- const { key, version, plugins } = { ...config, ...options };
- if (!key) {
- reject("请填写key");
- return;
- }
- if (window.AMap) {
- reject("禁止多种API加载方式混用");
- }
- config = { key, version, plugins };
- status = "loading";
- const parentNode = document.body || document.head;
- window.___onAPILoaded = function(err) {
- delete window.___onAPILoaded;
- if (err) {
- status = "failed";
- reject(err);
- } else {
- status = "loaded";
- resolve(window.AMap);
- }
- while (onloadCBKs.length) {
- onloadCBKs.splice(0, 1)[0]();
- }
- };
- const script = document.createElement("script");
- script.type = "text/javascript";
- script.src =
- "https://webapi.amap.com/maps?callback=___onAPILoaded&v=" +
- version +
- "&key=" +
- key +
- "&plugin=" +
- plugins.join(",");
- script.onerror = e => {
- status = "failed";
- reject(e);
- };
- parentNode.appendChild(script);
- } else {
- //deal multi load
- if (options.key && options.key !== config.key) {
- reject("多个不一致的 key");
- return;
- }
- if (options.version && options.version !== config.version) {
- reject("不允许多个版本 JSAPI 混用");
- return;
- }
- if (status == "failed") {
- reject("前次加载已经失败");
- }
- const newPlugins = [];
- if (options.plugins) {
- for (var i = 0; i < options.plugins.length; i += 1) {
- if (config.plugins.indexOf(options.plugins[i]) == -1) {
- newPlugins.push(options.plugins[i]);
- }
- }
- }
- if (status == "loaded") {
- if (newPlugins.length) {
- window.AMap.plugin(newPlugins, () => {
- resolve(window.AMap);
- });
- } else {
- resolve(window.AMap);
- }
- } else if (status == "loading") {
- onload(() => {
- if (newPlugins.length) {
- window.AMap.plugin(newPlugins, () => {
- resolve(window.AMap);
- });
- } else {
- resolve(window.AMap);
- }
- });
- }
- }
- });
- };
- export default { load };
|