vue项目中使用百度地图

安装

首先在vue项目中,我们可以使用 vue-baidu-map 插件来替代直接引入百度地图js sdk。
官方文档

JavaScript API v2.0类参考

npm install --save vue-baidu-map 

全局注册

import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'

Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: 'YOUR_APP_KEY'
})

局部注册

如果有按需引入组件的需要,可以选择局部注册百度地图组件,这将减少工程打包后的容量尺寸。局部注册的 BaiduMap 组件必须声明 ak 属性。 所有的独立组件均存放在 vue-baidu-map/components 文件夹下,按需引用即可。 由于未编译的 ES 模块不能在大多数浏览器中直接运行,如果引入组件时发生运行时错误,请检查 webpackloader 配置,确认 includeexclude 选项命中了组件库。

<template>
  <baidu-map class="bm-view" ak="YOUR_APP_KEY">
  </baidu-map>
</template>

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

实例组件

在这里插入图片描述

<template>
  <div class='map-wrap'>
    <baidu-map class="bm-view" :center="center" :zoom="zoom" :scroll-wheel-zoom="true" :point="true" @ready="handler">
      <bm-marker :position="center" :dragging="true" />
      <bm-view class="map" />
      <!-- 官网搜索api -->
      <!-- <bm-control :offset="{width: '10px', height: '10px'}">
            <bm-auto-complete v-model="address" :sugStyle="{zIndex: 3000}">
            <input placeholder="请输入地名关键字" />
            </bm-auto-complete>
        </bm-control> -->
      <!-- <bm-local-search :keyword="address" :auto-viewport="true" @searchcomplete="onSearchComplete" :panel="false" /> -->
    </baidu-map>
    <div class="search-wrap">
      <!-- 搜索框 -->
      <div class="search">
        <el-input placeholder="请输入内容" v-model="address" class="input-with-select">
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
      <!-- 检索结果 -->
      <div v-show="showResultFlag" class="search-result">
        <div v-for="(item, index) in searchResult" class="item" :key="index" @click="handleSelect(item)">
          <p class="title">{{ item.title }}</p>
          <p class="address">{{ item.address }}</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
const defaultInfo = {
  lng: 0,
  lat: 0,
  addressStr: '',
  title: '',
  province: '', // 省
  city: '', // 市
  district: '' // 区
}
export default {
  name: 'Map',
  data() {
    return {
      BMap: null,
      map: null,
      zoom: 15,//地图放大缩小的值
      center: { lng: 116.404, lat: 39.915 },//地图坐标
      address: '',//搜索地址
      searchResult: [],//自动匹配地址结果
      showResultFlag: false,
      selectInfo: Object.assign({}, defaultInfo)
    }
  },
  mounted(){
    this.address = ""
  },
  methods: {
    handler({ BMap, map }) {
      this.BMap = BMap
      this.map = map
      const geolocation = new BMap.Geolocation()
      const that = this
      geolocation.getCurrentPosition(function (r) {
        const position = {
          lng: r.point.lng,
          lat: r.point.lat
        }
        that.center = position
      }, { enableHighAccuracy: true })
      this.zoom = 15
    },
    handleSelect(item) {
      let self = this
      console.log('item', item)
      let title = item.title
      let { lng, lat } = item.marker.point
      // 以下代码是为了根据经纬度去转换出 省、市、区的信息出来。如果,不需要,可以自行修改。
      let point = new this.BMap.Point(lng, lat)
      let geoc = new this.BMap.Geocoder()
      geoc.getLocation(point, function (res) {
        let addString =
          res.addressComponents.province + res.addressComponents.city + res.addressComponents.district + title
        self.showResultFlag = false
        self.address = addString
        self.map.clearOverlays() //清除地图上所有覆盖物point
        self.map.addOverlay(new self.BMap.Marker({ lng, lat }))
        self.center.lng = lng
        self.center.lat = lat
        self.zoom = 20,
        self.selectInfo = {
          lng,
          lat,
          addressStr: addString,
          title: title,
          province: res.addressComponents.province,
          city: res.addressComponents.city,
          district: res.addressComponents.district
        }
      })
    },
    onSearchComplete(res) {
      if (res && res.Xr) {
        this.searchResult = [...res.Xr]
        if (this.searchResult.length > 0) {
          this.showResultFlag = true
        } else {
          this.showResultFlag = false
        }
      }
    },
    handleSearch() {
      let self = this
      // self.showResultFlag = true
      self.selectInfo = Object.assign({}, defaultInfo)
      let local = new this.BMap.LocalSearch(this.map, {
        renderOptions: {
          map: this.map,
          selectFirstResult: false
        },
        onSearchComplete: function (res) {
          console.log(res);
          if (res && res.Xr) {
            self.searchResult = [...res.Xr]
            if (self.searchResult.length > 0) {
              self.showResultFlag = true
            } else {
              self.showResultFlag = false
            }
          } else {
            self.showResultFlag = false
          }
        }
      })
      local.search(this.address)
    }
  }
}
</script>
<style lang="scss" scoped>
.map-wrap {
  position: relative;
  .search{
    width: 300px;
    margin: 5px;
  }
  .search-result{
    width: 300px;
    margin-left: 5px;
    padding: 10px;
    background: #fff;
    max-height: 300px;
    overflow-y: auto;
  }
  .bm-view {
    height: 500px;

    .map {
      width: 100%;
      height: 100%;
    }
  }
  .search-wrap{
    position: absolute;
    top: 0;
    left: 0;
  }
}
</style>


在这里插入图片描述

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哚啦A孟

谢谢鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值