vue使用百度地图,添加覆盖物

282 阅读1分钟

首页index.html中引入

<script type="text/javascript" src="//api.map.baidu.com/api?v=3.0&ak=你的ak"></script> 当然你也可以 动态创建script引入

页面中选择一个容器,并添加id

 <div class="app-container" id="map" style="height: 90vh;width: 98%;margin: auto;">
  </div>

初始化地图 并添加覆盖物

createMap(longitude,latitude){
  // 百度地图API功能
  var map = new BMap.Map("map");    // 创建Map实例
  map.centerAndZoom(new BMap.Point(longitude,latitude), 15);  // 初始化地图,设置中心点坐标和地图级别
  const point = new BMap.Point(longitude,latitude);
    // 实例化自定义覆盖物,将坐标点和水波纹的尺寸传进构造函数中
  const radar = new RadarOverlay(point, 40,'');
  // 添加自定义覆盖物
  map.addOverlay(radar);
  //添加地图类型控件
  map.addControl(new BMap.MapTypeControl({
      mapTypes:[
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
      ]}));

  map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放
}

把覆盖物的方法 可以单独写个js

// eslint-disable-next-line no-undef
export class RadarOverlay extends BMap.Overlay {
  constructor(point, size,carNumber) {
    super();
    this.point = point;
    this.size = size;
    this.carNumber = carNumber;
  }

  initialize(map) {
    this._map = map;
    const template = `<div class="radar-box">
        <div>${this.carNumber}</div>
        <div class="radar">
          <div class="ripple"></div>
          <div class="ripple"></div>
          <div class="ripple"></div>
        </div>
      </div>`;
    const divFragment = document.createRange().createContextualFragment(template);
    const div = divFragment.querySelectorAll('.radar-box')[0];
    map.getPanes().markerPane.appendChild(div);
    this._div = div;
    return div;
  }

  draw() {
    // 根据地理坐标转换为像素坐标,并设置给容器
    const position = this._map.pointToOverlayPixel(this.point);
    this._div.style.left = `${position.x - this.size / 2}px`;
    this._div.style.top = `${position.y - this.size / 2}px`;
  }
}

如果要修饰覆盖物的样式可以 写css 下边是一个可以扩散的原点例子

<style lang="scss" rel="stylesheet/scss">
.BMap_cpyCtrl {
    display: none;
}
.anchorBL {
    display: none;
}
.radar-box {
  position: absolute;

.radar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: red;
  position: relative;
}

.radar .ripple {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid red;
  animation: ripple 2s linear infinite;
}

.radar :nth-child(1) {
  animation-delay: 0.666s;
}

.radar :nth-child(2) {
  animation-delay: 1.322s;
}

@keyframes ripple {
  to {
    width: 150px;
    height: 150px;
    opacity: 0;
  }
}


}
</style>