vue2 结合iview和百度地图API实现电子围栏

vue2 结合iview和百度地图API实现电子围栏

实现在地图上绘制电子围栏并自定义电子围栏样式,还可以标记中心点

1.百度地图API相关JS引用

 <script src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=百度地图官网申请的ak"></script>
 //电子围栏相关的api
 <link href="//mapopen.cdn.bcebos.com/github/BMapGLLib/DrawingManager/src/DrawingManager.min.css" rel="stylesheet">
<script type="text/javascript"
  src="//mapopen.cdn.bcebos.com/github/BMapGLLib/DrawingManager/src/DrawingManager.min.js"></script>

2.页面代码

<template>
  <div style="position: relative;height:100%">
      <!--地图-->
     <div id="map" class="map" style="height:100%" />
     <div class="draw-btn" @click="drawMap()">开始绘制</div>
      <!--工具栏-->
    <div class="color-list" v-if="showDraw">
         <Button :type="isCenter?'info':'primary'"
                    size="small"
                    style="margin-right: 10px;"
                    @click="setCenter"> 
                 中心点
         </Button>
            <input type="color"
                   id="strokeColor"
                   v-model="strokeColor">
            <Select v-model="strokeWeight"
                    style="width:50px;margin:0 5px">
              <Option v-for="item in 9"
                      :value="item"
                      :key="item">{{ item }}</Option>
            </Select>
            <input type="color"
                   id="fillColor"
                   v-model="fillColor">
            <Select v-model="fillOpacity"
                    style="width:60px;margin:0 5px">
              <Option v-for="item in fillOpacityList"
                      :value="item"
                      :key="item">{{ item }}</Option>
            </Select>
          </div>
  </div>
</template>
<script>
export default {
  name: 'map',
   data() {
    return {
     strokeColor: '#DA4863',
      strokeWeight: 6,
      fillColor: '#DA4863',
      fillOpacity: 0.6,
      fillOpacityList: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1],
      polyLinePoints: [],
      markerPoints: [],
      polyLines: null,
      isCenter: false,
      showDraw:false
     }
    },
    computed:{
      changeData() {
      const { strokeColor, strokeWeight, fillColor, fillOpacity } = this
      return {
        strokeColor,
        strokeWeight,
        fillColor,
        fillOpacity
      }
    }
  },
  watch: {
    changeData: function (newV) {
      this.initSetMap()
    }
  },
  methods:{
  //开始绘制
  drawMap(){
    this.showDraw= true
    this.isCenter = false
    this.strokeColor = '#DA4863'
    this.strokeWeight = 6
    this.fillColor = '#DA4863'
    this.fillOpacity = 0.6
    this.initSetMap()
  },
   //获取坐标初始化地图
   init() {
      
       let data={blat: 29.516071,blng: 106.525681}
       this.initMap(data.blng, data.blat)
    },
    //清除坐标点
    clearMarkerOverlay() {
      const allOverlays = this.map.getOverlays()
      for (let i = 0; i < allOverlays.length; i++) {
        if (allOverlays[i].id && allOverlays[i].id === this.selectData.id) {
          this.map.removeOverlay(allOverlays[i])
        }
      }
    },
    //修改围栏样式时触发
    initSetMap() {
        this.polyLinePoints = []
       this.markerPoints = []
      var that = this
      const { strokeColor, strokeWeight, fillColor, fillOpacity } = this
      var overlaycomplete = function (e) {
        var mlnglat = []
        var path = e.overlay.getPath() // Array<Point> 返回多边型的点数组
        for (var i = 0; i < path.length; i++) {
          mlnglat.push({
            lng: path[i].lng,
            lat: path[i].lat
          })
        }
      console.log(mlnglat)
      }
      var styleOptions = {
        strokeColor: this.strokeColor, // 边线颜色。
        fillColor: this.fillColor, // 填充颜色。当参数为空时,圆形将没有填充效果。
        strokeWeight: this.strokeWeight, // 边线的宽度,以像素为单位。
        strokeOpacity: 1, // 边线透明度,取值范围0 - 1。
        fillOpacity: this.fillOpacity, // 填充的透明度,取值范围0 - 1。
        strokeStyle: 'solid' // 边线的样式,solid或dashed。
      }
      this.drawingManager = new BMapGLLib.DrawingManager(this.map, {
        isOpen: false, // 是否开启绘制模式
        enableDrawingTool: true, // 是否显示工具栏
        drawingToolOptions: {
          anchor: BMAP_ANCHOR_TOP_RIGHT, // 位置
          offset: new BMapGL.Size(5, 5) // 偏离值
        },
        polygonOptions: styleOptions // 多边形的样式
      })

      this.drawingManager.addEventListener('overlaycomplete', overlaycomplete)
    },
    //初始化地图
     initMap(lng, lat) {
      let that = this
      if (this.map) {
        this.map.clearOverlays()
      }
      this.map = new BMapGL.Map('map')
      var poi = new BMapGL.Point(lng, lat)
      this.map.centerAndZoom(poi, 18) // 设置中心点坐标和地图级别
      this.map.enableScrollWheelZoom() // 启用鼠标滚动对地图放大缩小
      this.map.addControl(new BMapGL.NavigationControl())

      if (this.polyLinePoints && this.polyLinePoints.length) {
        this.polyLinePoints.forEach((item) => {
          if (item.points && item.points.length) {
            let data = []
            item.points.forEach((col) => {
              var po = new BMapGL.Point(col.lng, col.lat)
              data.push(po)
            })
            this.polyLines = new BMapGL.Polygon(data, {
              strokeColor: item.strokeColor, // 边线颜色。
              fillColor: item.fillColor, // 填充颜色。当参数为空时,圆形将没有填充效果。
              strokeWeight: item.strokeWeight, // 边线的宽度,以像素为单位。
              strokeOpacity: 1, // 边线透明度,取值范围0 - 1。
              fillOpacity: item.fillOpacity // 填充的透明度,取值范围0 - 1。
            })
            this.map.addOverlay(this.polyLines)
          }
        })
      }
      if (this.markerPoints && this.markerPoints.length) {
        this.markerPoints.forEach((item) => {
          if (item.points && item.points.length) {
            let data = []
            item.points.forEach((col) => {
              var marker = new BMapGL.Marker(new BMapGL.Point(col.lng, col.lat))
              marker.id = item.id
              this.map.addOverlay(marker)
              const label = new BMapGL.Label('', {
                offset: new BMapGL.Size(0, 0)
              })
              label.setStyle({
                textAlign: 'center',
                // 设置label的样式
                color: 'white',
                fontSize: '14px',
                border: 'none',
                color: 'black',
                fontFamily: '黑体'
                // opacity: '0.5',
              })
              label.setContent(
                `<div style="background: rgba(255,255,255,1);border-radius: 12px;padding:3px 5px">${item.name}</div>`
              )
              marker.setLabel(label)
            })
          }
        })
      }
      //地图展示样式
      this.map.setMapStyleV2({
        styleJson: [
          // {
          //   featureType: 'poilabel',
          //   elementType: 'all',
          //   stylers: {
          //     visibility: 'off'
          //   }
          // },
          // {
          //   featureType: 'manmade',
          //   elementType: 'all',
          //   stylers: {
          //     visibility: 'off'
          //   }
          // },
          {
            featureType: 'building',
            elementType: 'all',
            stylers: {
              visibility: 'off'
            }
          }
        ]
      })
      this.map.addEventListener('click', function (e) {
      //点击地图设置中心点
        if (that.isCenter) {
          that.clearMarkerOverlay()
          var marker = new BMapGL.Marker(
            new BMapGL.Point(e.latlng.lng, e.latlng.lat)
          )
          marker.id = that.selectData.id
          that.map.addOverlay(marker)
          const label = new BMapGL.Label('', {
            offset: new BMapGL.Size(0, 0)
          })
          label.setStyle({
            textAlign: 'center',
            // 设置label的样式
            color: 'white',
            fontSize: '14px',
            border: 'none',
            color: 'black',
            fontFamily: '黑体'
            // opacity: '0.5',
          })
          label.setContent(
            `<div style="background: rgba(255,255,255,1);border-radius: 12px;padding:3px 5px">${that.selectData.name}</div>`
          )
          marker.setLabel(label)
        }
      })
    },
    setCenter() {
      this.isCenter = true
    },
  },
   mounted() {
   this.init()
   }
 }
</script>
<style scoped lang="less">
/deep/.BMapGLLib_Drawing {
  position: inherit !important;
}
/deep/ .BMapGLLib_Drawing .BMapGLLib_polyline {
  display: none !important;
}

/deep/ .BMapGLLib_Drawing_panel {
  position: absolute;
  right: 380px;
  top: 1%;
}
//隐藏除了多边形之外的按钮
/deep/ .BMapGLLib_Drawing .BMapGLLib_marker {
  display: none !important;
}
/deep/ .BMapGLLib_Drawing .BMapGLLib_circle {
  display: none !important;
}
/deep/ .BMapGLLib_Drawing .BMapGLLib_rectangle {
  display: none !important;
}
/deep/.BMap_stdMpZoom {
  width: 0 !important;
  height: 0 !important;
}
.draw-btn{
 position: absolute;
  left: 10px;
  top: 2%;
  z-index: 999;
}
.color-list {
  position: absolute;
  right: 10px;
  top: 2%;
  z-index: 999;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>

效果图

在这里插入图片描述
在这里插入图片描述

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现百度地图电子围栏,可以使用百度地图 JavaScript APIVue.js 框架来实现。以下是实现步骤: 1. 首先,在 HTML 中引入百度地图 JavaScript API 的库文件和 Vue.js 的库文件。 ```html <script src="http://api.map.baidu.com/api?v=2.0&ak=your_ak"></script> <script src="https://cdn.jsdelivr.net/npm/vue"></script> ``` 2. 创建一个地图容器,用于显示地图。 ```html <div id="map"></div> ``` 3. 在 Vue.js 中创建一个地图实例,并设置地图的中心点和缩放级别。 ```javascript new Vue({ el: '#map', data: { map: null, fence: null // 电子围栏对象 }, mounted() { this.map = new BMap.Map('map'); this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 15); } }); ``` 4. 实现电子围栏的绘制。可以使用百度地图提供的覆盖物来实现电子围栏的绘制,比如圆形、多边形等。这里以圆形为例。 ```javascript drawFence() { // 获取圆形的中心点和半径 const center = new BMap.Point(116.404, 39.915); const radius = 1000; // 创建圆形覆盖物 const circle = new BMap.Circle(center, radius, { strokeColor: '#f00', strokeWeight: 2, strokeOpacity: 0.5, fillColor: '#f00', fillOpacity: 0.1 }); // 添加圆形覆盖物到地图上 this.fence = circle; this.map.addOverlay(circle); } ``` 5. 给电子围栏添加事件监听器。可以使用覆盖物的事件监听器来实现电子围栏的事件处理,比如进入、离开等。 ```javascript addFenceListener() { this.fence.addEventListener('mouseover', () => { console.log('进入电子围栏'); }); this.fence.addEventListener('mouseout', () => { console.log('离开电子围栏'); }); } ``` 6. 最后,在 Vue.js 的生命周期函数中调用以上方法,实现电子围栏的创建和事件监听。 ```javascript mounted() { this.map = new BMap.Map('map'); this.map.centerAndZoom(new BMap.Point(116.404, 39.915), 15); // 绘制电子围栏 this.drawFence(); // 添加电子围栏事件监听器 this.addFenceListener(); } ``` 以上是使用百度地图 JavaScript APIVue.js 框架实现百度地图电子围栏的基本步骤。具体实现还需根据实际需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值