百度地图 创建 自定义控件(vue)

1.组件代码

Bmap.vue

<!-- 离线地图 组件 -->
<template>
  <div id="map" :style="style"></div>
</template>

<script>
export default{
  data(){
    return {
      style:{
        width:'100%',
        height:this.height + 'px'
      }
    }
  },
  props:{
    height:{
      type:Number,
      default:736  // 默认值
    },
    longitude:{
      type:Number,
      default:114.00100
    },  // 经度
    latitude:{
      type:Number,
      default:22.61067
    } // 维度
  },
  mounted(){
    let _this = this;
    /**
     * 百度地图API功能
     */
    let map = new BMap.Map("map",{minZoom:12,maxZoom:18});
    let point = new BMap.Point(this.longitude,this.latitude);
    map.centerAndZoom(point,13);

    // 定义一个控件类,即function
    function MessageControl(){
      // 默认停靠位置和偏移量
      this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
      this.defaultOffset = new BMap.Size(10, 10);
    }

    // 通过JavaScript的prototype属性继承于BMap.Control
    MessageControl.prototype = new BMap.Control();

    // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
    MessageControl.prototype.initialize = function(map){
      // 创建一个DOM元素
      let div = document.createElement("div");
      // 设置样式
      div.style.height = "50px";
      div.style.width = "50px";
      div.style.backgroundImage = "url('./static/img/message_map.png')";
      div.style.backgroundSize = "cover";
      // 绑定事件,点击一次放大两级
      div.onclick = function(e) {
        // 将输入值传递给父组件
        _this.$emit("showSideBar",true);
      }
      // 添加DOM元素到地图中
      map.getContainer().appendChild(div);
      // 将DOM元素返回
      return div;
    }

    // 创建控件
    let messageCtrl = new MessageControl();

    // 添加到地图当中
    map.addControl(messageCtrl);
  }
}
</script>

2.效果图

猜你喜欢

转载自www.cnblogs.com/crazycode2/p/9197435.html