1. 程式人生 > 實用技巧 >vue 初始化高德地圖

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端, 移動端還在測試中...........