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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM