项目场景:
由于公司业务涉及到地图,所以不得不自主学习。vue3项目中高德地图作为组件使用时,遇到了不少bug,而且都指向远程源码错误。头痛…真的很头痛…所以记录一下这个缠了我很多天的bug…
问题描述
项目中,高德地图作为组件,点击切换按钮触发“显示/隐藏”。初始化设置为“显示”,地图全部方法加载,正常显示且没有bug。切换后设置“隐藏”,再次点击设置为“显示”后,地图不显示,控制台报错AMap.xxx is not a constructor。
代码如下:
1.在 index.html 中同步引入
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode: '',
}
</script>
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=2.0&key=您申请的key值"></script>
2.在父组件中插入高德组件,并用 v-if 控制显示/隐藏
<Amap v-if="activeBtn !== 0" />
import Amap from './components/map.vue'
原因分析:
AMap实例对象定义结束后打印,发现对象上的确没有该方法/属性,判断是地图加载问题。所以改用异步加载。
官网异步加载方法
解决方案:
<template>
<div id="AMap" class="a-map"></div>
</template>
<script setup>
import { reactive, onMounted } from "vue";
let map = reactive(null)
let mass = reactive(null)
let marker = reactive(null)
onMounted(() => {
getMap()
});
const getMap = () => {
window.onApiLoaded = function () {
// onApiLoaded 报错可以使用onload
initMap()
}
// var url = 'https://webapi.amap.com/maps?v=2.0&key=您申请的key值&callback=onApiLoaded(或者onload)';
// 因为是内网项目,所以我把上面的url里面的代码复制下来放到本地了
var url = '../js/index.js';
var jsapi = document.createElement('script');
jsapi.charset = 'utf-8';
jsapi.src = url;
jsapi.type = "text/javascript" // url为本地要加,其他不用
document.head.appendChild(jsapi);
}
const initMap = () => {
map = new AMap.Map("AMap", {
center: [116.40,39.91],
zoom: 17,
pitch: 65, // 3d倾斜角度
resizeEnable: true, //是否监控地图容器尺寸变化
mapStyle: "amap://styles/darkblue",
viewMode: "3D"
});
mass = new AMap.MassMarks([], {
opacity: 0.8,
zIndex: 111,
cursor: "pointer",
style: {
url: require(`@/assets/img/1.png`),
anchor: new AMap.Pixel(6, 6),
size: new AMap.Size(29, 38),
}
})
marker= new AMap.Marker({
position: new AMap.LngLat(116.02,40.36),
anchor: new AMap.Pixel(6, 6),
icon: new AMap.Icon({
image: require(`@/assets/img/2.png`),
size: new AMap.Size(29, 38), //图标所处区域大小
imageSize: new AMap.Size(29, 38), //图标大小
}),
})
let pointInfoList = []
path.forEach((i) => {
pointInfoList.push({
lnglat: i
})
})
//地图加载完成后添加覆盖物
map.on("complete", () => {
mass.setData(pointInfoList)
map.add(marker)
mass.setMap(map)
})
}
<script>