vue 高德地图地图新建、保存、编辑、清除绘制多边形

请添加图片描述
请添加图片描述

请添加图片描述
index页面

<template>
  <div>
    <el-button @click="openEnclosure">绘制围栏</el-button>
    <draw-enclosure :show.sync="showDialog" :coordinate-string="temp.electronicFencePosition" @coordinate="enclosure" />

  </div>
</template>

<script>
import drawEnclosure from './MapDialog/draw-enclosure.vue'

export default {
  name: '',
  components: { drawEnclosure },
  props: {},
  data() {
    return {
      // 地图弹窗
      temp: {
        electronicFencePosition:  '[[113.345258, 23.121325], [113.391264, 23.121641], [113.371694, 23.105221]]'
        // electronicFencePosition:  ''
      },

      showDialog: false,
    }
  },
  filters: {},
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  beforeDestroy() {},
  methods: {
    // 绘制围栏
    openEnclosure() {
      this.showDialog = true
    },
    enclosure(data) {
      console.log(data, '坐标')
    },
  }
}
</script>

<style scoped lang="less">
</style>

绘制弹窗draw-enclosure.vue

<template>
  <el-dialog class="coordinate" title="选择坐标" :visible.sync="show" :before-close="closeAddressDialog">
    <el-row :gutter="10">
      <el-col :span="12">
        <div class="tips">注:通过左键点击来进行绘制,右键点击结束</div>
      </el-col>
      <el-col :span="12" style="text-align: right;margin-bottom: 10px;">
        <el-button type="warning" :disabled="disabled" @click="compile">编辑</el-button>
        <el-button type="primary" :disabled="disabled" @click="compileclose">结束编辑</el-button>
        <el-button type="success" @click="preservation">保存</el-button>
        <el-button type="danger" @click="clear">清除</el-button>
      </el-col>
    </el-row>
    <div id="enclosureMap" class="enclosureMap" />
  </el-dialog>
</template>

<script>
import _ from 'lodash'

export default {
  name: 'MapDialog',
  components: {},
  props: {
    show: {
      type: Boolean
    },
    coordinateString: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      iscompile: false,
      polygon: null,
      map: null,
      mouseTool: null,
      PolygonEditor: null,
      overlays: [],
      disabled: false,
      compileArr: []
    }
  },
  computed: {},
  watch: {
    show: {
      handler(newVal, oldVal) {
        var that = this
        if (newVal === true) {
          that.$nextTick(function() {
            that.MapInit()
            that.clear()
            if (that.coordinateString) {
              const arr = that.coordinateString.split(']').join('').split('[')
              var path = []
              arr.forEach(item => {
                if (item !== '') {
                  var pathArr = []
                  item.split(',').forEach(items => {
                    if (items !== '') {
                      pathArr[pathArr.length] = items * 1
                    }
                  })
                  path.push(pathArr)
                }
              })
              that.compileArr = path
              that.echo()
              that.disabled = false
            } else {
              that.compileArr = []
              that.mapping()
              that.disabled = true
            }
          })
        }
      },
      deep: true
    }
  },
  created() {},
  methods: {
    MapInit() {
      const that = this
      that.map = new AMap.Map('enclosureMap', {
        center: [113.364965, 23.107179], // [纬度,经度]
        mapStyle: 'amap://styles/7dc7bfff3444123cfbec260c6a0a8c71',
        resizeEnable: true,
        expandZoomRange: true,
        zoom: 13,
        zooms: [3, 21]
      })
      that.drawBounds(that.map)
      AMap.plugin(['AMap.ToolBar', 'AMap.Scale'], function() { // 异步同时加载多个插件
        that.toolbar = new AMap.ToolBar({
          // offset: AMap.Pixel(0, 10),
          ruler: false,
          liteStyle: true,
          position: 'RB'
        })
        that.map.addControl(that.toolbar)
        that.scale = new AMap.Scale()
        that.map.addControl(that.scale)
      })
      that.mouseTool = new AMap.MouseTool(that.map)
      // 监听draw事件可获取画好的覆盖物
      that.mouseTool.on('draw', function(e) {
        that.disabled = false
        that.overlays = []
        that.overlays.push(e.obj)
        that.mouseTool.close()
      })
    },

    // 编辑
    compile() {
      const that = this
      if (that.iscompile) {
        return
      }
      that.iscompile = true
      if (that.coordinateString === '') {
        that.PolygonEditor = new AMap.PolygonEditor(that.map, that.map.getAllOverlays('polygon')[1])
      } else {
        that.PolygonEditor = new AMap.PolygonEditor(that.map, that.polygon)
      }
      that.PolygonEditor.open()
      this.PolygonEditor.on('end', function(event) {
        that.iscompile = false
        that.overlays = []
        that.overlays.push(event.target)
      })
    },
    // 编辑回显
    echo() {
      const that = this
      const path = _.cloneDeep(that.compileArr)
      that.polygon = new AMap.Polygon({
        map: that.map,
        path: path,
        fillColor: '#00b0ff',
        strokeColor: '#80d8ff',
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        zIndex: 50
      })
    },
    // 结束编辑
    compileclose() {
      if (this.PolygonEditor) {
        this.PolygonEditor.close()
      }
    },
    // 新建
    mapping() {
      this.mouseTool.polygon({
        fillColor: '#00b0ff',
        strokeColor: '#80d8ff',
        zIndex: 50
        // 同Polygon的Option设置
      })
    },
    // 限制地图区域
    drawBounds(map) {
      const opts = {
        subdistrict: 0,
        extensions: 'all',
        level: 'city'
      }
      const district = new AMap.DistrictSearch(opts)
      district.setLevel('广州市')
      district.search('广州市', (status, result) => {
        const outer = [
          new AMap.LngLat(-360, 90, true),
          new AMap.LngLat(-360, -90, true),
          new AMap.LngLat(360, -90, true),
          new AMap.LngLat(360, 90, true)
        ]
        const holes = result.districtList[0].boundaries

        const pathArray = [outer]
        pathArray.push.apply(pathArray, holes)
        const polygon = new AMap.Polygon({
          pathL: pathArray,
          strokeColor: '#001826',
          strokeWeight: 1,
          strokeOpacity: 0.5,
          fillColor: '#ffffff',
          fillOpacity: 1,
          strokeStyle: 'dashed',
          strokeDasharray: [10, 2, 10]
        })
        polygon.setPath(pathArray)
        map.add(polygon)
      })
    },
    // 限制地图区域END

    // 清除
    clear() {
      if (this.iscompile) {
        this.PolygonEditor.close()
      }
      if (this.PolygonEditor) {
        this.map.remove(this.PolygonEditor)
      }
      if (this.mouseTool) {
        this.map.remove(this.mouseTool)
      }
      this.map.remove(this.overlays)
      if (this.polygon) {
        this.map.remove(this.polygon)
      }
      this.mapping()
      this.overlays = []
      this.compileArr = []
      this.disabled = true
    },

    // 保存
    preservation() {
      // if (this.PolygonEditor) {
      //   this.PolygonEditor.close()
      // }
      const coordinate = []
      this.overlays.forEach(item => {
        item._opts.path.forEach(items => {
          coordinate.push([items[0], items[1]])
        })
      })
      if (this.overlays.length > 0) {
        this.$emit('coordinate', coordinate)
      } else {
        this.$emit('coordinate', this.compileArr)
      }
      this.closeAddressDialog()
    },

    // 关闭弹窗
    closeAddressDialog() {
      this.$emit('update:show', false)
      this.clear()
    },
  }
}
</script>

<style lang="scss" scoped>
.coordinate {
  width: 100%;
  height: 100%;
  .enclosureMap {
    width: 100%;
    height: 300px;
  }
}
</style>

好的,您提到的问题是关于在 Vue 绘制多边形并进行编辑的问题,对吗?那么,您可以使用高德地图 JavaScript API 提供的绘制工具类来实现这一功能。具体步骤如下: 1. 引入高德地图 JavaScript API 和绘制工具类库: ```javascript <script src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script> <script src="https://webapi.amap.com/ui/1.0/main.js"></script> ``` 2. 在 Vue 组件创建地图容器,生成地图实例,并加载绘制工具类库: ```javascript <template> <div id="mapContainer"></div> </template> <script> export default { name: 'Map', mounted() { this.initMap(); }, methods: { initMap() { const map = new AMap.Map('mapContainer', { zoom: 10, center: [116.397428, 39.90923], }); AMap.plugin(['AMap.MouseTool'], () => { // 初始化鼠标绘制工具 const mouseTool = new AMap.MouseTool(map); // 监听draw事件,获取绘制的图形对象 AMap.event.addListener(mouseTool, 'draw', (e) => { console.log(e.obj); // e.obj为绘制出来的图形对象 // TODO: 将图形对象保存到state,用于后续编辑 }); }); }, }, }; </script> ``` 3. 在绘制完成后,将绘制的图形对象保存到 state ,以便进行后续编辑: ```javascript // 将绘制的图形对象保存到state // state.polygons为一个数组,保存所有已绘制多边形对象 state.polygons.push(e.obj); ``` 4. 对已绘制多边形对象进行编辑: ```javascript // 对已绘制多边形对象进行编辑 const drawPolygon = (polygon) => { // 使用多边形编辑插件 const polygonEditor = new AMap.PolyEditor(map, polygon); // 开启编辑模式 polygonEditor.open(); // 监听编辑完成事件,保存编辑后的多边形对象到state AMap.event.addListener(polygonEditor, 'end', (e) => { console.log(e.target); // e.target为当前编辑多边形对象 // TODO: 保存编辑后的多边形对象到state }); }; ``` 希望这个回答能够帮助您解决问题。如果您还有其他问题,可以继续向我提出。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值