vue cli3 + AMap

1. 项目引入AMap

vue.config.js

configureWebpack: {
    externals: {
      'AMap': 'AMap' 
    }
  },

configureWebpack配置中加入AMap项

2. 按需生成script

创建Map.js

export default function Map (key, plugins, v = '版本号') {
  return new Promise(function (resolve, reject) {
    if (typeof AMap !== 'undefined') {
      resolve(AMap)
      return true
    }
    window.onCallback = function () {
      resolve(AMap)
    }
    let script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://webapi.amap.com/maps?v=${v}&key=${key}&plugin=${plugins}&callback=onCallback`
    script.onerror = reject
    document.head.appendChild(script)
  })
}
3. 组件中使用

import Map from '@/XXXXX/Map.js'

data () {
    return {
      areaMap: null,
      plugins: [
        'AMap.MarkerClusterer',
        'AMap.MouseTool',
        'AMap.OverView',
        'AMap.PolyEditor',
        'AMap.RectangleEditor',
        'AMap.PlaceSearch',
        'AMap.DistrictLayer',
        'AMap.CustomLayer'
      ],
      key: '申请的key',
      v: '对应版本',
      loading: true
    }
  }

mounted()

loadMap(this.key, this.plugins, this.v)
    .then(AMap => {
      this.areaMap.on('complete', () => {
      successNotice(that, '温馨提示', '地图加载成功!')
        this.loading = false
      })
    }).catch(() => {
      this.loading = false
      warningNotice(that, '温馨提示', '地图加载失败!')
    })

你可能感兴趣的:(vue cli3 + AMap)