在 Vue3 项目中使用高德地图 JSAPI 2.0,官方推荐通过 @amap/amap-jsapi-loader 按需加载地图脚本。本文介绍从申请 Key 到封装组件的完整流程。
官方文档
申请高德 Key
- 打开 高德开放平台 并登录
- 创建应用,服务平台选择「Web端(JS API)」
- 获取 Key 与安全密钥(新版需要配置代理服务或安全密钥,用于 JSAPI 2.0 鉴权)
安装 Loader
1
| npm i @amap/amap-jsapi-loader
|
使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| <!-- MyMap.vue --> <template> <div :id="state.id"></div> </template> <script setup lang="ts"> import { onMounted, reactive } from "vue"; import AMapLoader from "@amap/amap-jsapi-loader"; const props = defineProps({ modelValue: null, }); const state = reactive({ id: "", map: null as any, }); const initMap = () => { state.id = Math.random().toString(36).substring(7) + Math.floor(Math.random() * 100); AMapLoader.load({ key: "", version: "2.0", plugins: ["AMap.Scale", "AMap.Marker"], }) .then((AMap) => { state.map = new AMap.Map(state.id, { viewMode: "3D", zoom: 18, center: props.modelValue, doubleClickZoom: false, layers: [], }); if (state.map) { const scale = new AMap.Scale({ visible: true, }); state.map.addControl(scale); const marker = new AMap.Marker({ position: props.modelValue, }); state.map.add(marker); } }) .catch((e) => { console.log(e); }); }; onMounted(() => { initMap(); }); </script> <style lang="less" scoped> #container { padding: 0px; margin: 0px; width: 100%; height: 800px; } </style>
|
代码说明
- 随机容器 id:每次初始化生成随机 id 并作为容器,避免多实例(如列表循环)时 id 冲突导致地图渲染异常
AMapLoader.load:按需加载 JSAPI 脚本,key 填入申请到的 Web 端 Key,version 指定版本,plugins 声明需要使用的插件
new AMap.Map:创建地图实例,center 传入经纬度数组(如 [116.39, 39.9]),viewMode: "3D" 开启 3D 视角
AMap.Scale / AMap.Marker:通过 addControl 添加比例尺,通过 add 在地图上添加标记点
页面中使用
1 2 3
| <template> <MyMap v-model="[116.397428, 39.90923]" /> </template>
|
注意:AMap.Map 必须在容器已挂载且有宽高后创建,因此初始化逻辑放在 onMounted 中执行;如果容器是异步渲染(如弹窗),需要等 DOM 渲染完成后(nextTick)再调用。