vue & 百度地图:在地图上绘制多边形

<template>
  <div class="hello">
    <div style="margin-bottom:10px">
      <button @click="clickStart('jinting')">设定坐标</button>
      <button @click="clickEnd">退出设定</button>
      <button @click="re" style="color:#ff0000">重置</button>
      <button @click="getBoundary">生成区域</button>
      <button @click="clickCenter">设定中心点</button>
      <button @click="boo2 = !boo2">显示点集</button>
      <input type="text" placeholder="请输入城市名称" width="200" v-model="cityName"></input>
    </div>
    <!-- map start -->
    <div style="" id="dituContent" class="ditu-content"></div>
    <!-- map end -->
    <div style="text-align:center" class="ditu-point" v-if="savePointsArray.length > 0" v-show="boo2">
      <p v-for="todo in savePointsArray">
        <span style="padding-right:20px;">{{ todo.name }}</span><span>{{ todo.point }}</span>
      </p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'mymap',
  data () {
    return {
      polygons: [],
      clickCity: '',
      polyline: null,
      marker: null,
      cityName: '',
      status: 'none',
      centerPoint: [],
      savePointsArray: [],
      savePointsString: '',
      jinting: '',
      todos: [
        { text: '学习 JavaScript' },
        { text: '学习 Vue' },
        { text: '整个牛项目' }
      ],

      mapObj:null,    
      boo2: false     // 当点了显示点集的按钮之后变为true
    }
  },
  mounted () {
    this.initMap()    
  },
  methods:{
    re(){
      this.polygons = []
      this.clickCity = ''
      this.polyline = null
      this.marker = null
      this.cityName = ''
      this.status = 'none'
      this.centerPoint = []
      this.savePointsArray = []
      this.savePointsString = ''
      this.jinting = ''
      this.mapObj = null
      this.boo2 = false

      this.initMap()
    },
    initMap () {
      this.createMap() //创建地图      
    },
    createMap(){
      let self = this
      let m = new BMap.Map("dituContent")
      let point = new BMap.Point(120.49,31.15)
      m.centerAndZoom(point,12)
      m.setCurrentCity("苏州")
      m.addEventListener("click",function(e){
          let ln = e.point.lng
          let la = e.point.lat
          self.clickFun(ln,la)
      });

      this.setMapEvent(m)
    },
    setMapEvent(m){
      m.enableDragging();//启用地图拖拽事件,默认启用(可不写)
      m.enableScrollWheelZoom();//启用地图滚轮放大缩小
      m.enableDoubleClickZoom();//启用鼠标双击放大,默认启用(可不写)
      m.enableKeyboard();//启用键盘上下左右键移动地图

      this.addMapControl(m);//向地图添加控件
    },
    addMapControl(m){
      //向地图中添加缩放控件
      let ctrl_nav = new BMap.NavigationControl({anchor:BMAP_ANCHOR_TOP_LEFT,type:BMAP_NAVIGATION_CONTROL_LARGE});
      m.addControl(ctrl_nav);
      //向地图中添加缩略图控件
      let ctrl_ove = new BMap.OverviewMapControl({anchor:BMAP_ANCHOR_BOTTOM_RIGHT,isOpen:1});
      m.addControl(ctrl_ove);
      //向地图中添加比例尺控件
      let ctrl_sca = new BMap.ScaleControl({anchor:BMAP_ANCHOR_BOTTOM_LEFT});
      m.addControl(ctrl_sca);
      
      this.mapObj = m
    },
    clickFun(ln,la){
      
      if (this.status === 'inner') {
        this.centerPoint[0] = ln
        this.centerPoint[1] = la
        
        this.marker = new BMap.Marker(new BMap.Point(ln, la)); // 创建点
        this.mapObj.addOverlay(this.marker);
      } else if (this.clickCity === '') {
        console.log('当前没有选择镇');
        return
      } else {
        switch(this.clickCity)
        {
        case 'jinting':          
          this.jinting += (ln + ',' + la + ';')          
          this.pline(this.jinting)
          // console.log('this.jinting', this.jinting)
          break;    
        default:
          return
        }
      }
    },
    clickStart(n){
      $('#dituContent div').css({
        'cursor':'crosshair'
      })
      this.polygons = []
      this.clickCity = n
      this.status = 'outside'
    },
    clickEnd(){
      console.log('======================== CLICK END ======================')
      this.clickCity = ''
      this.status = 'none'
      $('#dituContent div').css({
        'cursor':'url("http://api0.map.bdimg.com/images/openhand.cur") 8 8, default'
      })
    },
    clickCenter(){
      this.status = 'inner'
      $('#dituContent div').css({
        'cursor':'crosshair'
      })
    },
    pline(city){
      
      this.mapObj.removeOverlay(this.polyline)
      let pois = city.split(';')
      let poisarray = []
      pois.pop()
      
      for (let i = 0; i < pois.length; i++) {
        poisarray.push(new BMap.Point(parseFloat(pois[i].split(',')[0]),parseFloat(pois[i].split(',')[1])))
        
      }
      
      this.polyline = new BMap.Polyline(poisarray, {
         enableEditing: false,//是否启用线编辑,默认为false
         enableClicking: false,//是否响应点击事件,默认为true
         strokeWeight:'5',//折线的宽度,以像素为单位
         strokeOpacity: 0.5,//折线的透明度,取值范围0 - 1
         strokeColor:"#18a45b" //折线颜色
      });
      this.mapObj.addOverlay(this.polyline);          //增加折线
    },
    getBoundary(){      
      this.mapObj.removeOverlay(this.polyline)
      let areas = []
      let contentArray = []
      areas.push(this.jinting)
      let colors = "#fff492"
      let pointArray = []
      for (var i = 0; i < areas.length; i++) {
        let ply = new BMap.Polygon(areas[i], { strokeWeight: 2, strokeColor: "#ff0000" }); //建立多边形覆盖物
        ply.setFillColor(colors)   //设置多边形的填充颜色
        ply.setFillOpacity(0.35);
        this.polygons.push(ply);  //加入多边形数组,以之后获取多边形边界点集
       
        // ply.enableEditing();  //范围可编辑 【编辑的时候开启】        

        this.mapObj.addOverlay(ply);  //添加覆盖物
        pointArray = pointArray.concat(ply.getPath());
      }
      
      this.addlabel2()
      this.savePoints()
      this.reload2()
    },
    reload2(){
      this.polygons = []
      this.clickCity = ''
      this.polyline = null
      this.cityName = ''
      this.jinting = ""
      this.status = 'none'
      this.mapObj.removeOverlay(this.marker)
      this.centerPoint = []
    },
    addlabel2(){
      let pointArray = [
        new BMap.Point(this.centerPoint[0], this.centerPoint[1]),
      ]
      let optsArray = [{}]
      let labelArray = []
      this.contentArray = [this.cityName]
      for (let i = 0; i < pointArray.length; i++) {
          optsArray[i].position = pointArray[i]
          labelArray[i] = new BMap.Label(this.contentArray[i], optsArray[i])
          labelArray[i].setStyle({
              color: "red",
              fontSize: "12px",
              height: "20px",
              lineHeight: "20px",
              fontFamily: "微软雅黑"
          });
          this.mapObj.addOverlay(labelArray[i])
      }
    },
    savePoints(){
      console.log('=======================存储点集')
      console.log(this.cityName)
      if (this.cityName === ''){
        alert('城市名称必填!')
        return 
      }
      if (this.savePointsCheck(this.cityName)){
        alert('这个点已经存过了!')
        return 
      }
      let obj = {}
      obj.name = this.cityName
      obj.point = this.jinting.slice(0,-1)
      obj.centerpoint = this.centerPoint[0] + ',' + this.centerPoint[1]
      this.savePointsArray.push(obj)
      console.log(this.savePointsArray)
      
    },
    savePointsCheck(c) {
      console.log(c)
      let f = this.savePointsArray.find((v) => {
          console.log(c)
          console.log(v.name + '===' + c)
          return v.name === c
      })
      
      return f
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .ditu-content{
    width:70%;
    height:600px;
    border:#ccc solid 1px;
    margin:0 auto 20px;
  }
  .pointwords{
    word-wrap: break-word;
    text-align: center;
    padding: 0 20px;
  }
  .button{
    height: 100px;
  }
</style>

最后效果如下:

参考:

https://blog.csdn.net/qq_38903950/article/details/78022174?locationNum=7&fps=1

https://www.cnblogs.com/RiseSoft/p/7979637.html

猜你喜欢

转载自www.cnblogs.com/foxcharon/p/8940946.html