vue 初始化高德地图

时间:2022-07-24
本文章向大家介绍vue 初始化高德地图,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

由于项目中需要,但是vue-AMap 又满足不了项目需求。只能赶鸭子上架,看看怎么引入高德原生 地图 api 。( 三大步骤 )

  • 登录高德地图,申请个人 key。
  • 创建 单独的 .js 文件
  • 在 .vue 项目中,import 引入

1.首先在项目根目录创建一个 AMap.js 文件

export default async function MapLoader (key) {
    return new Promise((resolve, reject) => {
        if (window.AMap) {
            window.onload = function () {
                resolve(window.AMap)
            }
        } else {
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.axync = true;
            script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=' + key;  // 申请个人 key 
            script.onerror = reject;
            document.head.appendChild(script);
            window.onload = function () {
                resolve(window.AMap)
            }
        }
    })
}

如果直接在 HTML,通过script 的方式引入,即使添加 async,也不能获取到 AMap 构造函数。

所以,通过 promise 方式,引入 AMap.js 文件

2.在每个需要 AMap 的.vue 组件中,直接 import 引入。

<script>
import MapLoader from '../../AMap'   // AMap.js 文件(请核对 项目路径是否正确)
export default {
  name: 'Home',
  data() {
    return {
      map: null,
    }
  },
  mounted() {
    this.init_map();   // 页面加载,初始化 AMap。
  },
  methods: {
    init_map() {
      let that = this
      MapLoader('3d053e40e060b0fc8e39fff2023c95c6').then((AMap) => {       // MapLoader(key)  ---> 申请的个人  key
        that.map = new AMap.Map('container', {                            // html 放置 一个 id = container 的div
          mapStyle: 'amap://styles/7e8dadf307af8b4a5da5a98e53fd2657',     //   *** 地图的背景颜色   ( 可以自己在高德官网 查看如何配置 )
          zoom: 13,
          resizeEnable: true,
        })
        AMap.plugin('AMap.Geolocation', function () {                           //  返回当前的  个人所在的位置  (定位)
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位,默认:true
            timeout: 10000, //超过10秒后停止定位,默认:5s
            buttonPosition: 'RB', //定位按钮的停靠位置
            buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            zoomToAccuracy: true, //定位成功后是否自动调整地图视野到定位点
          })
          that.map.addControl(geolocation)
          geolocation.getCurrentPosition()
          AMap.event.addListener(geolocation, 'complete', onComplete)     
          AMap.event.addListener(geolocation, 'error', onError)

          function onComplete(data) {
            // data是具体的定位信息
            console.log(data)
          }

          function onError(data) {
            // 定位出错
          }
        })
      })
    }
  },
}
</script>

仅限于 pc端, 移动端还在测试中...........