vue+element项目使用百度地图 实现搜索定位功能

1,084 阅读1分钟
  1. 首先要在百度开发者工具注册

Snipaste_2022-11-29_10-05-51.png 3.新建vueBMap.js文件

/**
 * 动态加载百度地图api函数
 * @param {String} ak  百度地图AK,必传
 */
export default function loadBMap(ak) {
  return new Promise(function(resolve, reject) {
    if (typeof window.BMap !== 'undefined') {
      resolve(window.BMap)
      return true
    }
    window.onBMapCallback = function() {
      resolve(window.BMap)
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src =
      'http://api.map.baidu.com/api?v=3.0&ak=' + ak + '&callback=onBMapCallback'
    script.onerror = reject
    document.head.appendChild(script)
  })
}

4.详细代码 我这里做了dialog回显处理,所以大家应该按照自己需要适当删减

<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="90px">
      <el-form-item label="地图定位" prop="address">
        <el-autocomplete
          v-model="form.address"
          style="width:280px;margin-left:0px"
          popper-class="autoAddressClass"
          :fetch-suggestions="querySearchAsync"
          :trigger-on-focus="false"
          placeholder="请输入地址"
          clearable
          @change="handleChange"
          @select="handleSelect"
        >
          <template slot-scope="{ item }">
            <div style="display:flex;height: 30px;line-height: 30px;">
              <div><i class="el-icon-search fl mgr10" /></div>
              <div class="title" style="margin-left:10px">{{ item.title }}</div>
              <div>
              </div>
            </div>
          </template>
        </el-autocomplete>
      </el-form-item>
      <div id="map-container" style="width:100%;height:330px;" />
    </el-form>
  </div>
</template>

<script>
import loadBMap from '@/utils/vueBMap'
export default {
  props: {
    lngLat: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      form: {
        address: '', // 详细地址
        addrPoint: { // 详细地址经纬度
          lng: 0,
          lat: 0
        }
      },
      map: '', // 地图实例
      mk: '' // Marker实例
    }
  },
  watch: {
    lngLat: {
      handler: function(newValue) {
        if (+newValue.lng !== 0 && +newValue.lat !== 0) {
          this.form.addrPoint.lng = +newValue.lng
          this.form.addrPoint.lat = +newValue.lat
        }
      },
      deep: true,
      immediate: true
    }
  },
  async mounted() {
    await loadBMap('百度地图的密钥')
    setTimeout(() => {
      this.initMap()
    }, 800)
  },
  created() {

  },

  methods: {
    initMap() {
      var that = this
      // 挂载地图
      this.map = new BMap.Map('map-container', { enableMapClick: false })
      var point = new BMap.Point(this.form.addrPoint.lng, this.form.addrPoint.lat)
      this.map.setCenter(point)
      this.map.centerAndZoom(point, 15)
      // 设置图像标注并绑定拖拽标注结束后事件
      this.mk = new BMap.Marker(point, { enableDragging: true })
      this.map.addOverlay(this.mk)
      this.mk.addEventListener('dragend', function(e) {
        that.getAddrByPoint(e.point)
      })
      // 添加(右上角)平移缩放控件
      this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL }))
      // 添加(左下角)定位控件
      var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT })
      geolocationControl.addEventListener('locationSuccess', function(e) {
        that.getAddrByPoint(e.point)
      })
      geolocationControl.addEventListener('locationError', function(e) {
        alert(e.message)
      })
      this.map.addControl(geolocationControl)
      // 浏览器定位
      if (+this.lngLat.lng !== 0 && +this.lngLat.lat !== 0) {
        this.getAddrByPoint(point)
      }
      // 绑定点击地图任意点事件
      this.map.addEventListener('click', function(e) {
        that.getAddrByPoint(e.point)
      })
    },
    handleChange(value) {
      if (!value) {
        this.form.addrPoint.lng = ''
        this.form.addrPoint.lat = ''
        this.form.address = ''
        this.form.title = ''
        this.onSubmit()
      }
    },
    // 获取两点间的距离
    getDistancs(pointA, pointB) {
      return this.map.getDistance(pointA, pointB).toFixed(2)
    },
    // 浏览器定位函数
    geolocation() {
      var that = this
      var geolocation = new BMap.Geolocation()
      geolocation.getCurrentPosition(function(res) {
        if (this.getStatus() === BMAP_STATUS_SUCCESS) {
          that.getAddrByPoint(res.point)
          that.locationPoint = res.point
        } else {
          that.locationPoint = new BMap.Point(113.3324436, 23.1315381)
        }
      }, { enableHighAccuracy: true })
    },
    // 逆地址解析函数
    getAddrByPoint(point) {
      var that = this
      var geco = new BMap.Geocoder()
      geco.getLocation(point, function(res) {
        that.mk.setPosition(point)
        that.map.panTo(point)
        that.form.address = res.address
        that.form.title = res.title
        that.form.addrPoint = point
        that.onSubmit()
      })
    },
    // 地址搜索
    querySearchAsync(str, cb) {
      var options = {
        onSearchComplete: function(res) {
          var s = []
          if (local.getStatus() === BMAP_STATUS_SUCCESS) {
            for (var i = 0; i < res.getCurrentNumPois(); i++) {
              s.push(res.getPoi(i))
            }
            cb(s)
          } else {
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options)
      local.search(str)
    },
    // 选择地址
    handleSelect(item) {
      this.form.address = item.address + item.title
      this.form.title = item.title
      this.form.addrPoint = item.point
      this.map.clearOverlays()
      this.mk = new BMap.Marker(item.point)
      this.map.addOverlay(this.mk)
      this.map.panTo(item.point)
      this.form.addrPoint.lng = item.point.lng
      this.form.addrPoint.lat = item.point.lat
      this.onSubmit()
    },
    onSubmit() {
      const data = {
        name: this.form.title,
        // 地址名称
        address: this.form.address,
        // 纬度lat
        lat: this.form.addrPoint.lat,
        // 经度lng
        lng: this.form.addrPoint.lng
      }
      this.$emit('getPosition', data)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>


<style>
.count {
  color: red;
}
</style>