APILoader.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const DEFAULT_CONFIG = {
  2. v: '1.4.0',
  3. hostAndPath: 'webapi.amap.com/maps',
  4. key: 'f97efc35164149d0c0f299e7a8adb3d2',
  5. callback: '__amap_init_callback',
  6. useAMapUI: false
  7. }
  8. let mainPromise = null
  9. let amapuiPromise = null
  10. let amapuiInited = false
  11. export default class APILoader {
  12. constructor({ key, useAMapUI, version, protocol }) {
  13. this.config = { ...DEFAULT_CONFIG, useAMapUI, protocol }
  14. if (typeof window !== 'undefined') {
  15. if (key) {
  16. this.config.key = key
  17. } else if ('amapkey' in window) {
  18. this.config.key = window.amapkey
  19. }
  20. }
  21. if (version) {
  22. this.config.v = version
  23. }
  24. this.protocol = protocol || window.location.protocol
  25. if (this.protocol.indexOf(':') === -1) {
  26. this.protocol += ':'
  27. }
  28. }
  29. getScriptSrc(cfg) {
  30. return `${this.protocol}//${cfg.hostAndPath}?v=${cfg.v}&key=${cfg.key}&callback=${cfg.callback}`
  31. }
  32. buildScriptTag(src) {
  33. const script = document.createElement('script')
  34. script.type = 'text/javascript'
  35. script.async = true
  36. script.defer = true
  37. script.src = src
  38. return script
  39. }
  40. getAmapuiPromise() {
  41. const script = this.buildScriptTag(`${this.protocol}//webapi.amap.com/ui/1.0/main-async.js`)
  42. const p = new Promise(resolve => {
  43. script.onload = () => {
  44. resolve()
  45. }
  46. })
  47. document.body.appendChild(script)
  48. return p
  49. }
  50. getMainPromise() {
  51. const script = this.buildScriptTag(this.getScriptSrc(this.config))
  52. const p = new Promise(resolve => {
  53. window[this.config.callback] = () => {
  54. resolve()
  55. delete window[this.config.callback]
  56. }
  57. })
  58. document.body.appendChild(script)
  59. return p
  60. }
  61. load() {
  62. if (typeof window === 'undefined') {
  63. return null
  64. }
  65. const { useAMapUI } = this.config
  66. mainPromise = mainPromise || this.getMainPromise()
  67. if (useAMapUI) {
  68. amapuiPromise = amapuiPromise || this.getAmapuiPromise()
  69. }
  70. return new Promise(resolve => {
  71. mainPromise.then(() => {
  72. if (useAMapUI && amapuiPromise) {
  73. amapuiPromise.then(() => {
  74. if (window.initAMapUI && !amapuiInited) {
  75. window.initAMapUI()
  76. if (typeof useAMapUI === 'function') {
  77. useAMapUI()
  78. }
  79. amapuiInited = true
  80. }
  81. resolve()
  82. })
  83. } else {
  84. resolve()
  85. }
  86. })
  87. })
  88. }
  89. }