uniappH5中使用高德API

高德的API有現成的SDK支撐安卓/IOS  但是沒有專門的API支撐H5(或者說不用專門支撐)

當uniapp中調用高德API的時候就會遇到問題:

因爲直接用<sctipt>引入外部js肯定不行了

所以爲了解決這個問題就必須引入在線jsAPI

下面就介紹步驟

1.引入在線jsAPI   專門新建個工具類,這樣當需要調用地圖的時候直接引用該方法就行

a.直接引用js肯定不行,所以採用回調函數的方式引入

b.因爲高德的API是異步的,所以我們把他封裝成Promise函數

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

注意:key值換成自己的哈

2.引入工具類

import AMap from "../util/AMap.js"

3.加載API

return {
				 map: null,
				 resAmap:null,
				 scrollH:500,
				 scrollW:500,
				 initLat:39.913423,//初始維度
				 initLng:116.368904,//初始經度
				 LlayAroundGroupOpen:true,  //l網周邊
			}
onLoad() {
			 this.initAMap();
		},
async initAMap() {
					  try {
						  this.resAmap=await AMap();
						  this.$nextTick(function(){
						  	this.getBroewerLatLng();
						  	var map = new this.resAmap.Map('map', {
						  		   center:[this.initLng,this.initLat],
						  		   zoom:13
						  		});
						   this.map=map;
						  	this.drawAround();
						  })
						}catch(e){
							console.log(e)
						}
					},

最重要的事情是一定要將調用方法放到$nextTick中,因爲這樣才能保證完全請求完成才調用(具體原因參見Vue)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章