//單獨寫一個js文件 export default function MapLoader() { return new Promise((resolve, reject) => { if (window.AMap) { resolve(window.AMap); } else { window._AMapSecurityConfig = { securityJsCode: ' 高德地圖在 2021-12-12 更新之后,創建的key 會產生一個秘鑰 ', } 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); }; }); }
//高德地圖的應用地址 https://console.amap.com/dev/key/app
import AMap from "../../../utils/AMap.js" //這里引入上面那個JS的包
//放在 method 里的方法
async initAMap() { this.resAmap = await AMap(); this.$nextTick(function() { // this.getBroewerLatLng(); this.resAmap.plugin('AMap.Geolocation', () => { var geolocation = new this.resAmap.Geolocation({ enableHighAccuracy: true, //是否使用高精度定位,默認:true timeout: 10000, //超過10秒后停止定位,默認:5s noGeoLocation: 3, //是否禁止使用瀏覽器Geolocation定位,默認值為0,可選值0-3 0: 可以使用瀏覽器定位 1: 手機設備禁止使用瀏覽器定位 2: PC上禁止使用瀏覽器定位 3:有終端禁止使用瀏覽器定位 convert: false, //是否使用坐標偏移,取值true:為高德地圖坐標,取值false:為瀏覽器定位坐標默認值:true // GeoLocationFirst: true, //默認為false,設置為true的時候可以調整PC端為優先使用瀏覽器定位,失敗后使用IP定位 }); geolocation.getCurrentPosition(function(status, result) { if (status == 'complete') { // alert(result.position); result.position = result.position.toString() var positions = result.position.split(',') this.latitude = parseInt(positions[0]) this.longitude = parseInt(positions[1]) this.covers[0].latitude = parseInt(positions[1]) this.covers[0].longitude = parseInt(positions[0]) setTimeout(() => { this.getUserLocation(parseInt(positions[1]), parseInt( positions[0])); }, 1000) } else { this.initAMap() } }); }); }) },
//由於是同步鎖,所以放在哪里加載並沒有所謂。目前暫時沒有解決同步鎖的方法,后面如果有會同步更新