index.js 2.01 KB
const envObject = {
  1: 'develop',
  2: 'test',
  3: 'production',
  4: 'beta'
}
class GlMapSdk {
  constructor() {
    let mapConfig = {
      env: 3,
      version: 3
    },
      _callBack = arguments[0]
    if (arguments.length > 1) {
      mapConfig = typeof arguments[0] == 'object' ? arguments[0] : mapConfig
      _callBack = arguments[1]
      if (!mapConfig.env) mapConfig.env = 3
      if (!mapConfig.version) mapConfig.version = 3
    }
    if (typeof window !== 'undefined') {
      const fetchConfig = async () => {
        try {
          let url = 'https://config-center-backend.glsx.com.cn/glsxAdmin/config?moduleUrl=map-api-js'
          if(mapConfig.hasEnv) url += `&env=${envObject[mapConfig.env]}`;
          const response = await fetch(url);
          const res = await response.json(),
            scriptExists = Array.from(document.head.getElementsByTagName('script')).some(script => script.src === res.apiUrl);
          if (!scriptExists) {
            const script = document.createElement('script');
            script.setAttribute('ignore', '')
            script.src = res.apiUrl;
            document.head.appendChild(script)
            script.onload = () => {
              this.GLMap = new window.$GlMapApi(mapConfig, () => {
                if (_callBack && typeof _callBack == 'function') _callBack(this)
              })
            }
          } else if (_callBack && typeof _callBack == 'function') {
            this.GLMap = new window.$GlMapApi(mapConfig, () => {
              if (_callBack && typeof _callBack == 'function') _callBack(this)
            })
          }
        } catch (error) {
          console.error('Failed to fetch configuration:', error)
        }
      }
      fetchConfig()
    }
  }
  invoke (target) {
    let params = Array.prototype.slice.call(arguments, 1)
    return this.GLMap[target](...params)
  }
  get map () {
    return this.GLMap._BMAP
  }
  get mapGL () {
    return this.GLMap._BMapGL
  }
}
export default GlMapSdk