vue-amap(高德地图vue插件)的使用

3,970 阅读2分钟
由于公司的项目需要地图,之前一直使用的百度地图,这次老板想用高德。于是就研究了一下。这里记录一下使用的方法以及遇到的坑(主要是覆盖物的使用)

安装

我使用的是cnpm

cnpm i vue-amap -S

引入

mian.js中引入(查了挺多资料,没有找到分模块引入的方法,所以也就放弃了,使用了官方的引入方式)

import VueAMap from "vue-amap";
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
    key: '在高德地图申请的key值',
    plugin: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.MapType', 'AMap.PolyEditor', 'AMap.CircleEditor','MarkerClusterer'], // 高德地图自带的插件,可以按需引入
    // 默认高德 sdk 版本为 1.4.4  
    v: '1.4.4'
});

使用

vue文件:

<template>
    <div class="index">
        <el-amap
        class="amap-box"
        :center="center"
        :zoom="zoom"
        ref="map"
        :events="events"
        >
            <el-amap-marker
            v-for="(item,index) in markers"
            :key="index"
            :position="item.position"
            :events="item.events"
            >
                <div class="userMarker">
                    <!-- 根据需求添加dom -->
                </div>
            </el-amap-marker>
        </el-amap>
    </div>
</template>

<script>
export default {
    data(){
        return {
            center: [lng,lat], // 默认中心点
            zoom: 12, // 默认缩放尺寸
            mapObj: null,
            // 地图的事件和方法
            events: {
                // 事件我都用的箭头函数,这样可以直接获取到当前的this
                // 初始化事件,地图在初始化完毕之后会调用这个事件,如果需要一开始对地图做出操作可以在这个事件里面执行
                init: (e) => {
                    // 将地图对象存储起来。由于高德地图的vue插件封装的并不完善,很多时候还是需要用到原始API,也可以自己定义一个函数,在这里面调用
                    this.mapObj = e; 
                },
                // 点击事件
                click: (e) => {
                    // 可以获取到当前点击的GPS信息等
                    console.log('点击了地图',e);
                },
                // https://lbs.amap.com/api/javascript-api/guide/events/map_overlay/?sug_index=0 可以根据官方文档使用所需的监听事件
            },
            markers: [],
        }
    },
    methods: {
        addMarkers(){ // 增加覆盖物
            this.markers = []; // 清除覆盖物数组、
            `// 高德地图的机制,在清除覆盖物之后要延迟才能添加,这是一个坑,当时坑死我了`
            setTimeout(() => {
                for(let i = 0; i < 10; i++){
                    this.markers.push({
                        position: [lng,lat],
                        events: {
                            // 覆盖物初始化函数
                            init: (o) => {
                                
                            },
                            //覆盖物点击函数
                            click: () => {
                                
                            }
                        },
                    });
                }
            },100);
        }
    }
}
</script>

<style lang="scss" scoped>
.index{
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    .amap-box{ // 地图的class或者地图父级的class必须要有高度
        width: 100%;
        height: 100%;
        /deep/.userMarker{
            
        }
    }
}
</style>

哪里写的有问题请大家指出,小白,第一次写教程