index.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. if (!window) {
  2. throw Error("AMap JSAPI can only be used in Browser.");
  3. }
  4. let status = "notload";
  5. let config = {
  6. key: "",
  7. version: "1.4.15",
  8. plugins: []
  9. };
  10. const onloadCBKs = [];
  11. const onload = function(callback) {
  12. if (typeof callback == "function") {
  13. if (status == "loaded") {
  14. callback(window.AMap);
  15. return;
  16. }
  17. onloadCBKs.push(callback);
  18. }
  19. };
  20. const load = function(options) {
  21. return new Promise((resolve, reject) => {
  22. if (status == "notload") {
  23. //初次加载
  24. const { key, version, plugins } = { ...config, ...options };
  25. if (!key) {
  26. reject("请填写key");
  27. return;
  28. }
  29. if (window.AMap) {
  30. reject("禁止多种API加载方式混用");
  31. }
  32. config = { key, version, plugins };
  33. status = "loading";
  34. const parentNode = document.body || document.head;
  35. window.___onAPILoaded = function(err) {
  36. delete window.___onAPILoaded;
  37. if (err) {
  38. status = "failed";
  39. reject(err);
  40. } else {
  41. status = "loaded";
  42. resolve(window.AMap);
  43. }
  44. while (onloadCBKs.length) {
  45. onloadCBKs.splice(0, 1)[0]();
  46. }
  47. };
  48. const script = document.createElement("script");
  49. script.type = "text/javascript";
  50. script.src =
  51. "https://webapi.amap.com/maps?callback=___onAPILoaded&v=" +
  52. version +
  53. "&key=" +
  54. key +
  55. "&plugin=" +
  56. plugins.join(",");
  57. script.onerror = e => {
  58. status = "failed";
  59. reject(e);
  60. };
  61. parentNode.appendChild(script);
  62. } else {
  63. //deal multi load
  64. if (options.key && options.key !== config.key) {
  65. reject("多个不一致的 key");
  66. return;
  67. }
  68. if (options.version && options.version !== config.version) {
  69. reject("不允许多个版本 JSAPI 混用");
  70. return;
  71. }
  72. if (status == "failed") {
  73. reject("前次加载已经失败");
  74. }
  75. const newPlugins = [];
  76. if (options.plugins) {
  77. for (var i = 0; i < options.plugins.length; i += 1) {
  78. if (config.plugins.indexOf(options.plugins[i]) == -1) {
  79. newPlugins.push(options.plugins[i]);
  80. }
  81. }
  82. }
  83. if (status == "loaded") {
  84. if (newPlugins.length) {
  85. window.AMap.plugin(newPlugins, () => {
  86. resolve(window.AMap);
  87. });
  88. } else {
  89. resolve(window.AMap);
  90. }
  91. } else if (status == "loading") {
  92. onload(() => {
  93. if (newPlugins.length) {
  94. window.AMap.plugin(newPlugins, () => {
  95. resolve(window.AMap);
  96. });
  97. } else {
  98. resolve(window.AMap);
  99. }
  100. });
  101. }
  102. }
  103. });
  104. };
  105. export default { load };