vue使用百度地图vue-bmap-gl

需求;

为了使用百度地图的3D控件及旋转地图功能,特此研究了vue-bmap-gl

一.安装:

npm install vue-bmap-gl -D

二.main.js全局引入

import VueBMap from 'vue-bmap-gl'
import 'vue-bmap-gl/dist/style.css'

Vue.use(VueBMap)
VueBMap.initBMapApiLoader({
  // 百度的key
  ak: 'T9XgL5DpTmOQvL0SbN362KIzYpR52LYU', // 用自己的百度地图ak
  // 百度 sdk 版本,默认为 1.0
  v: '1.0'
})

 

三.组件代码如下:

<template>
  <div>
    <div id="container" />
    <div class="zlp-control">
      <el-button @click="big()">放大一级</el-button>
      <el-button @click="small()">缩小一级</el-button>
    </div>
  </div>
</template>
<script>
import { lazyBMapApiLoaderInstance } from 'vue-bmap-gl'

export default {
  data() {
    return {
      map: null,
      centerPoint: {
        lng: 116.404,
        lat: 39.915
      },
      zoom: 15,
      mapType: 'BMAP_EARTH_MAP'
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    small() {
      this.map.zoomOut()
    },
    big() {
      this.map.zoomIn()
    },
    NavigationControl3D() {
      // eslint-disable-next-line no-undef
      var navi3DCtrl = new BMapGL.NavigationControl3D() // 添加3D控件
      this.map.addControl(navi3DCtrl)
    },
    LocationControl() {
      // 创建定位控件
      // eslint-disable-next-line no-undef
      var locationControl = new BMapGL.LocationControl({
        // 控件的停靠位置(可选,默认左上角)
        // anchor: 'BMAP_ANCHOR_TOP_RIGHT',
        // 控件基于停靠位置的偏移量(可选)
        // eslint-disable-next-line no-undef
        // offset: new BMapGL.Size(20, 20)
      })
      // 将控件添加到地图上
      this.map.addControl(locationControl)

      // 添加定位事件
      locationControl.addEventListener('locationSuccess', function(e) {
        var address = ''
        address += e.addressComponent.province
        address += e.addressComponent.city
        address += e.addressComponent.district
        address += e.addressComponent.street
        address += e.addressComponent.streetNumber
        alert('当前定位地址为:' + address)
      })
      locationControl.addEventListener('locationError', function(e) {
        alert(e.message)
      })
    },
    init() {
      lazyBMapApiLoaderInstance.load().then(() => {
        // eslint-disable-next-line no-undef
        const GL = BMapGL
        this.map = new GL.Map('container', {
          minZoom: 5,
          maxZoom: 20
        }) // 创建Map实例
        this.map.centerAndZoom(new GL.Point(this.centerPoint.lng, this.centerPoint.lat), this.zoom)
        this.map.enableScrollWheelZoom(true)
        this.map.setMapType(this.mapType)

        this.NavigationControl3D()
        this.LocationControl()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
#container {
  width: 100%;
  height: 100vh;
}
.zlp-control {
  position: fixed;
  top: 50px;
  left: 50px;
  z-index: 100;
}
</style>

四.效果如下:

 

posted @ 2022-03-09 17:42  土豆哥  阅读(2627)  评论(0编辑  收藏  举报