1、安装
npm i @amap/amap-jsapi-loader --save
2、封装地图组件
<template><div id="map" ref="mapcontainer"></div>
</template><script>
import AMapLoader from "@amap/amap-jsapi-loader";
export default {beforeCreate() {AMapLoader.load({key: "aa3dac8335f8831b0bf80a66a28b57e4", // 申请好的Web端开发者Key,首次调用 load 时必填version: "1.4.15", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15plugins: [], // 需要使用的的插件列表,如比例尺'AMap.Scale'等AMapUI: {// 是否加载 AMapUI,缺省不加载version: "1.1", // AMapUI 缺省 1.1plugins: [], // 需要加载的 AMapUI ui插件},Loca: {// 是否加载 Loca, 缺省不加载version: "1.3.2", // Loca 版本,缺省 1.3.2},}).then((AMap) => {this.$nextTick(() => this.initMap(AMap));}).catch((e) => {console.error(e);});},mounted() {// console.log(window.AMap, "window.AMap");},methods: {initMap(AMap) {// 初始化map实例this.map = new AMap.Map(this.$refs.mapcontainer);var that = this;AMap.plugin(["AMap.Geolocation", "AMap.Driving"], function () {//异步同时加载多个插件var geolocation = new AMap.Geolocation();that.map.addControl(geolocation);// var driving = new AMap.Driving(); //驾车路线规划// driving.search(/*参数*/);});// 或者使用 $refs 获取节点// this.map = new AMap.Map(this.$refs.container);},},
};
</script><style scoped lang="scss">
#map {width: 800px;height: 500px;background-color: pink;margin: 0 auto;margin-top: 15px;
}
</style>
3、在需要的地方引入组件并使用
//使用组件
<templete><MyMap/>
</templete>//引入组件
import MyMap from './MyMap.vue'
components:{
MyMap //祖册组件
}