vue-cli使用高德地图api
1、再src文件下新建util文件夹,在其下边建公用函数类
export default {
loadMap(v = '2.0', key = '写自己申请的高德可以') {
return new Promise(function (resolve, reject) {
let hasLoaded = document.getElementById("amap");
if (hasLoaded) {//只加载一次
if (hasLoaded._version === v && hasLoaded._key === key) {
resolve(window.AMap);
return;
}
document.head.removeChild(hasLoaded);
}
let script = document.createElement('script');
script.type = 'text/javascript';
script.id = "amap";
script.src = `https://webapi.amap.com/maps?v=${v}&key=${key}&callback=initAMap&plugin=AMap.PolygonEditor`;
//此处若缺失callback,则页面在刷新后地图会变为空白不显示
script.onerror = reject;
script._version = v;
script._key = key;
document.head.appendChild(script)
window.initAMap = () => {
resolve(window.AMap)
}
})
}
}
2、在main.js下引入
import mapUtil from "../utils/index";
//url
Vue.prototype.$mapUtil = mapUtil;
3、map.vue使用
<template>
<div class="main">
<div class="container">
<div id="map" ref="map" style="width: 100%; height: 100%">
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
polygon:[],
};
},
components: {},
computed: {},
mounted() {
let self = this;
setTimeout(function () {
self.initMap();
}, 400); //延时加载地图,保证数据获取成功
// this.polyEditor.open()
},
methods: {
initMap() {
let _this=this;
this.$mapUtil
.loadMap('2.0')
.then((AMap) => {
_this.map = new AMap.Map('map', {
zoom: 12,
center: [116.471354, 39.994257], //初始化地图中心点
resizeEnable: true
});
})
.catch(() => {
console.log('地图加载失败!');
});
}
}
};
</script>
<style scoped>
.main {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.container {
display: flex;
height: 100%;
flex-direction: column;
}
</style>