【学习记录】vue中引入百度地图

279 阅读1分钟

之前做了个仿京东到家的web项目,用vue写完了前端部分。

登陆/注册页面

image.png

首页

image.png

最近想把后端部分也做完,如图中所示,需要获取到当前位置信息。

image.png

找了下发现可以使用 Vue Baidu Map,简单做个记录。

简单示例:

1.npm

npm i vue-baidu-map --save

2.在全局中注册
import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'

Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: 'YOUR_APP_KEY'
})
3.模板
<template>
  <baidu-map class="bm-view">
  </baidu-map>
</template>

<style>
.bm-view {
  width: 100%;
  height: 300px;
}
</style>

这个时候页面上还不会显示出地图,原因:

  • BaiduMap 组件容器本身是一个空的块级元素,如果容器不定义高度,百度地图将渲染在一个高度为 0 不可见的容器内。
  • 没有设置 center 和 zoom 属性的地图组件是不进行地图渲染的。当center 属性为合法地名字符串时例外,因为百度地图会根据地名自动调整 zoom 的值。
  • 由于百度地图 JS API 只有 JSONP 一种加载方式,因此 BaiduMap 组件及其所有子组件的渲染只能是异步的。因此,请使用在组件的 ready 事件来执行地图 API 加载完毕后才能执行的代码,不要试图在 vue 自身的生命周期中调用 BMap 类,更不要在这些时机修改 model 层。
4.完整代码
<template>
  <baidu-map :center="center" :zoom="zoom" @ready="handler"></baidu-map>
</template>
<script>
export default {
  data () {
    return {
      center: {lng: 0, lat: 0},
      zoom: 3
    }
  },
  methods: {
    handler ({BMap, map}) {
      console.log(BMap, map)
      this.center.lng = 116.404
      this.center.lat = 39.915
      this.zoom = 15
    }
  }
}
</script>
5.显示出地图

image.png

获取所在位置的代码

<template>
  <div>
    <baidu-map
      class="bm-view"
      :center="center"
      :zoom="zoom"
      :scroll-wheel-zoom="true"
      @click="getClickInfo"
      @moving="syncCenterAndZoom"
      @moveend="syncCenterAndZoom"
      @ready="onBaiduMapReady"
      @zoomend="syncCenterAndZoom"
    ></baidu-map>
    <bm-view style="width: 100%; height: 100%" />
    <bm-geolocation
      anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
      show-address-bar
      auto-location
    />
    <!-- <bm-marker :position="{lng: center.lng, lat: center.lat}" :dragging="true" animation="BMAP_ANIMATION_BOUNCE" /> -->
     <h1>{{choosedLocation.addr}}</h1>
  </div>

 
</template>

<script>
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
export default {
  components: {
    BaiduMap,
  },

  data() {
    return {
      BMap: null,
      center: { lng: 0, lat: 0 },
      choosedLocation: { province: '', city: '', district: '', addr: '' },
      zoom: 15
    };
  },

  methods: {
    onBaiduMapReady(e) {
      console.log('返回BMap类和map实例', e)
      const that = this
      this.BMap = e.BMap
      if (this.BMap) {
        // 获取定位地址信息并赋值给声明变量
        // Geolocation 对象的 getCurrentPosition()、watchPosition()、clearWatch() 方法详解 :https://blog.csdn.net/zyz00000000/article/details/82774543
        const geolocation = new this.BMap.Geolocation()
        // 通过 getCurrentPosition() 方法:获取当前的位置信息
        geolocation.getCurrentPosition(res => {
          console.log('返回详细地址和经纬度', res)
          const { lng, lat } = res.point
          const { province, city, district, street, street_number } = res.address

          that.center = { lng, lat }
          that.choosedLocation = { province, city, district, addr: street + street_number, lng, lat }
        })
      }
    },

/** *
     * 地图点击事件。
     */
    getClickInfo(e) {
      // 调整地图中心位置
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat

      // 此时已经可以获取到BMap类
      if (this.BMap) {
        const that = this
        // Geocoder() 类进行地址解析
        // 创建地址解析器的实例
        const geoCoder = new this.BMap.Geocoder()
        // getLocation() 类--利用坐标获取地址的详细信息
        // getPoint() 类--获取位置对应的坐标
        geoCoder.getLocation(e.point, function(res) {
          console.log('获取经纬度', e.point, '获取详细地址', res)
          const addrComponent = res.addressComponents
          const surroundingPois = res.surroundingPois
          const province = addrComponent.province
          const city = addrComponent.city
          const district = addrComponent.district
          let addr = addrComponent.street
          if (surroundingPois.length > 0 && surroundingPois[0].title) {
            if (addr) {
              addr += `-${surroundingPois[0].title}`
            } else {
              addr += `${surroundingPois[0].title}`
            }
          } else {
            addr += addrComponent.streetNumber
          }
          that.choosedLocation = { province, city, district, addr, ...that.center }
        })
      }
    },

 syncCenterAndZoom(e) {
      // 返回地图当前的缩放级别
      this.zoom = e.target.getZoom()
    },


  },
};
</script>

<style>
.bm-view {
  width: 100%;
  height: 500px;
}
</style>

效果

image.png

缩放、点击地图就能获取到位置信息

image.png

参考

dafrok.github.io/vue-baidu-m…

www.jianshu.com/p/51e62c90d…