glsk-mapapi-sdk.js 5.37 KB
/**
 * 地图 API 封装:从配置中心拉取脚本地址并加载,与历史 UMD 导出保持一致。
 * - 修复:head 中已存在地图 script 时也必须实例化 GLMap(不再依赖构造函数是否传入回调)。
 * - 新增:ready() 返回 Promise,在底层 Map 可用时 resolve(失败则 reject)。
 */
;(function (global, factory) {
  typeof exports === 'object' && typeof module !== 'undefined'
    ? (module.exports = factory())
    : typeof define === 'function' && define.amd
      ? define(factory)
      : ((global =
          typeof globalThis !== 'undefined' ? globalThis : global || self),
        (global.GlMap = factory()))
})(this, function () {
  'use strict'

  var envNameByCode = {
    1: 'develop',
    2: 'test',
    3: 'production',
    4: 'beta'
  }

  function typeOf(v) {
    return typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol'
      ? function (t) {
          return typeof t
        }
      : function (t) {
          return t &&
            typeof Symbol === 'function' &&
            t.constructor === Symbol &&
            t !== Symbol.prototype
            ? 'symbol'
            : typeof t
        }
  }

  function GLMapVendorSdk() {
    var self = this
    this.GLMap = undefined

    var _resolveReady
    var _rejectReady
    var settled = false
    function settleResolve() {
      if (settled) return
      settled = true
      _resolveReady(self)
    }
    function settleReject(err) {
      if (settled) return
      settled = true
      _rejectReady(err)
    }
    this._readyPromise = new Promise(function (resolve, reject) {
      _resolveReady = resolve
      _rejectReady = reject
    })

    var o = { env: 3, version: 3 }
    var i
    if (arguments.length === 0) {
      i = undefined
    } else if (arguments.length === 1) {
      var a0 = arguments[0]
      if (typeOf(a0) === 'object' && a0 !== null) {
        o = a0
        if (!o.env) o.env = 3
        if (!o.version) o.version = 3
        i = undefined
      } else {
        i = a0
      }
    } else {
      o = typeOf(arguments[0]) === 'object' && arguments[0] !== null ? arguments[0] : o
      i = arguments[1]
      if (!o.env) o.env = 3
      if (!o.version) o.version = 3
    }

    if (typeof window === 'undefined') {
      settleReject(new Error('GLMapSdk requires window'))
      return
    }

    function attachGlMapInstance() {
      if (typeof window.$GlMapApi !== 'function') {
        var err = new Error('$GlMapApi is not available after script load')
        console.error(err)
        settleReject(err)
        return
      }
      try {
        self.GLMap = new window.$GlMapApi(o, function () {
          if (i && typeof i === 'function') i(self)
          settleResolve()
        })
      } catch (e) {
        settleReject(e)
      }
    }

    ;(async function () {
      try {
        // map-api-js:不配 env 时接口返回 code 与非对象 data,无 apiUrl(见配置中心「不存在该环境配置」)
        var envCode = o.env != null ? o.env : 3
        var envName = envNameByCode[envCode] || 'production'
        var url =
          'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=map-api-js&env=' +
          envName
        var resp = await fetch(url)
        var raw = await resp.json()
        var payload = raw && typeof raw === 'object' ? raw : {}
        var cfg = payload
        if (
          payload.data != null &&
          typeof payload.data === 'object' &&
          !Array.isArray(payload.data)
        ) {
          cfg = payload.data
        } else if (typeof payload.data === 'string' && payload.data.trim()) {
          try {
            var parsed = JSON.parse(payload.data)
            if (parsed && typeof parsed === 'object') cfg = parsed
          } catch (err) {
            /* ignore */
          }
        }
        var apiUrl = cfg.apiUrl || cfg.apiURL || cfg.scriptUrl
        if (!apiUrl) {
          var hint =
            (payload && payload.message) ||
            (cfg && cfg.message) ||
            'map config missing apiUrl'
          console.error('Map config response (no apiUrl):', raw)
          throw new Error(hint)
        }

        var scriptAlreadyLoaded = Array.from(
          document.head.getElementsByTagName('script')
        ).some(function (s) {
          return s.src === apiUrl
        })

        if (scriptAlreadyLoaded) {
          attachGlMapInstance()
        } else {
          var sc = document.createElement('script')
          sc.setAttribute('ignore', '')
          sc.src = apiUrl
          sc.onload = function () {
            attachGlMapInstance()
          }
          sc.onerror = function () {
            settleReject(new Error('Failed to load map script: ' + apiUrl))
          }
          document.head.appendChild(sc)
        }
      } catch (e) {
        console.error('Failed to fetch map configuration:', e)
        settleReject(e)
      }
    })()
  }

  GLMapVendorSdk.prototype.ready = function () {
    return this._readyPromise
  }

  GLMapVendorSdk.prototype.invoke = function (method) {
    var args = Array.prototype.slice.call(arguments, 1)
    var g = this.GLMap
    return g[method].apply(g, args)
  }

  Object.defineProperty(GLMapVendorSdk.prototype, 'map', {
    get: function () {
      return this.GLMap._BMAP
    }
  })

  Object.defineProperty(GLMapVendorSdk.prototype, 'mapGL', {
    get: function () {
      return this.GLMap._BMapGL
    }
  })

  return GLMapVendorSdk
})