創建amap.js
/*
* 異步創建script標籤
*/
export default function MapLoader () {
return new Promise((resolve, reject) => {
if (window.AMap) {
resolve(window.AMap)
} else {
var url = 'https://webapi.amap.com/maps?v=1.4.15&key=2e91f494321a102c9f969df860b447dc&callback=onLoad'
var script = document.createElement('script')
script.charset = 'utf-8'
script.src = url
script.onerror = reject
document.head.appendChild(script)
}
window.onLoad = () => {
resolve(window.AMap)
}
})
}
在頁面中引用
<template>
<Row id="amap" style="width: 100%; height: 100%; margin-top: -40px;"></Row>
</template>
<script>
import MapLoader from '@/libs/amap'
let AMap
......
......
......
methods: {
createAmap () {
map = new AMap.Map('amap', {
resizeEnable: true,
zoom: 10, // 設置地圖顯示的縮放級別
center: this.center, // 設置地圖中心點座標
viewMode: '2D', // 設置地圖模式
// 地圖模式
lang: 'zh_cn' // 設置地圖語言類型
})
let scale = new AMap.Scale({ // 比例尺
visible: true
})
let toolBar = new AMap.ToolBar({ // 工具條
visible: true
})
map.addControl(scale)
map.addControl(toolBar)
// 瀏覽器精確定位
AMap.plugin('AMap.Geolocation', function () {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true, // 是否使用高精度定位,默認:true
timeout: 10000, // 超過10秒後停止定位,默認:無窮大
maximumAge: 0, // 定位結果緩存0毫秒,默認:0
convert: true, // 自動偏移座標,偏移後的座標爲高德座標,默認:true
showButton: true, // 顯示定位按鈕,默認:true
buttonPosition: 'RB', // 定位按鈕停靠位置,默認:'LB',左下角
buttonOffset: new AMap.Pixel(10, 20), // 定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
showMarker: true, // 定位成功後在定位到的位置顯示點標記,默認:true
showCircle: false, // 定位成功後用圓圈表示定位精度範圍,默認:true
panToLocation: true, // 定位成功後將定位到的位置作爲地圖中心點,默認:true
zoomToAccuracy: false // 定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,默認:false
})
map.addControl(geolocation)
geolocation.getCurrentPosition(function (status, result) {
let position = result.position
if (status === 'complete') {
console.log('定位成功:定位結果 = %o', [position.lng, position.lat])
} else {
console.log('定位失敗')
}
})
})
}
}
mounted () {
// 初始化地圖對象,加載地圖
MapLoader().then(aMap => {
console.log('%地圖異步加載成功%')
AMap = aMap
setTimeout(() => {
this.request()
this.createAmap()
}, 500)
})
}
</script>