封装:
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 = 'http://webapi.amap.com/maps?v=1.4.14&callback=initAMap&key=ee80c1540f06a00d5a574ca6b4974422'
script.onerror = reject
document.head.appendChild(script)
}
window.initAMap = () => {
resolve(window.AMap)
}
})
}
使用方法:
let that = this;
MapLoader().then(
AMap => {
let map = new AMap.Map("container", {
resizeEnable: true
});
map.plugin("AMap.Geolocation", function() {
let geolocation = new AMap.Geolocation({
enableHighAccuracy: true, //是否使用高精度定位,默认:true
timeout: 10000, //超过10秒后停止定位,默认:5s
buttonPosition: "RB", //定位按钮的停靠位置
buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
});
map.addControl(geolocation);
geolocation.getCurrentPosition(function(status, result) {
if (status == "complete") {
//that.address = result.formattedAddress;
that.latitude = result.position.lat;
that.longitude = result.position.lng;
that.load(that.latitude, that.longitude);
} else {
}
});
});
},
e => {}
);