vue结合高德地图api实现电子围栏

1,301 阅读1分钟

前言

相信大家或多或少地图,在后台管理中除了用到了echarts中的行政地图,点标记这些,今天主要来说一下在vue中调用高德地图实现电子围栏这个功能,如图所示,下面底部会有源码示例

image.png 我们来一步步开始吧,博主第一次写博客,文字功底表达能力较弱

第一步-申请高德地图的key

无论我们使用任何方式调用高德地图都需要在高德地图开放平台中申请key

注册账号

访问高德地图开发平台根据实际情况填写就可以🍜(实名认证的时候选择个人就可以,如果是企业级的项目,可能会涉及人员变动,建议使用公司邮箱进行注册)区别如下👇。

image.png

image.png 创建应用

新建应用时名称,与类型可以随意填写,尽量填写的与开发的应用一直,方便后期维护,如下所示

image.png

技术选型

开发一个地图组件目前常用的有 vue-amap 不过我们今天采用的时候高德地图官方提供的地图加载器amap-jsapi-loader

NPM 安装 Loader

npm i @amap/amap-jsapi-loader --save

安装完毕后就可以开始写代码了

完整代码

<template>
  <div>
    <a-button class="btn" @click="polyEditorStart" style="margin-bottom: 5px">开始编辑</a-button>
    <a-button class="btn" @click="createPolygon" style="margin-bottom: 5px" v-if="isCreateBtn">新建围栏</a-button>
    <a-button class="btn" @click="handleKeep" style="margin-bottom: 5px">保存</a-button>
    <a-button class="btn" @click="handleRemove" style="margin-bottom: 5px">删除围栏</a-button>
    <a-button class="btn" @click="polyEditorEnd">结束编辑</a-button>
    //设置地图容器
    <div id="map-container" style="height: 500px"></div>
  </div>
</template>

<script>
//引入我们前面安装的jsapi加载器
import AMapLoader from '@amap/amap-jsapi-loader'
export default {
   data(){
    return{
        map:null,//地图实例
        polygon: null,
        polyEditor: null,
        //经纬度构成的输出用于展示围栏 
        PolygonoArr: [],
    }
   },
   mounted() {
     this.initMap()
   },
   methods:{
     initMap() {
       AMapLoader.load({
         //我们申请的高德key
          key: 'xxxxxxxxxxxxxxxxxxxxxxx',
          version: '2.0',
          //加载插件
          plugins: ['AMap.Polygon', 'AMap.PolyEditor', 'AMap.PolygonEditor'],
       }).then((AMap) => {
           this.map = new AMap.Map('map-container', { zoom: 10, center: this.PolygonoArr[0] })
            //控制地图双击是否放大
            this.map.setStatus({ doubleClickZoom: false })
            
            //构造多边形对象
            this.polygon = new AMap.Polygon({
              path: this.PolygonoArr,
              strokeColor: '#1b38d3',
              strokeOpacity: 1,
              strokeWeight: 3,
              fillColor: '#1b38d3',
              fillOpacity: 0,
              zIndex: 50,
              // draggable: true,
              bubble: true,
            })
            // 创建多边形编辑器对象 指定地图容器和多边形对象
            this.polyEditor = new AMap.PolygonEditor(this.map, this.polygon)
            //绑定双击事件 双击打开编辑
            this.polygon.on('dblclick', () => {
              this.polyEditor.open()
            })
            //单击关闭
            this.polygon.on('click', () => {
              this.polyEditor.close()
            })
    
            this.map.add([this.polygon])
      })
     },
   }
}
</script>

最终效果 image.png