Vue 通过调用百度API获取地理位置-经度纬度省份城市

一、首先在百度api注册获得ak密钥

二、新建js文件,我命名为loadBMap.js,里面创建script,代码如下:

/**
 * 加载地图
 * @param {Function} callback 回调函数名称,回调函数将会挂载到window上,例如:window.initBaiduMapScript,在方法中就能拿到BMap对象
 */
export function loadBMap(callback) {
  var script = document.createElement('script')
  script.src = 'http://api.map.baidu.com/api?v=2.0&ak=你的AK&callback=' + callback
  document.body.appendChild(script)
}

三、在Vue页面中导入js

import { loadBMap } from './loadBMap'

四、在Vue页面中定义一些需要用到的数据

data () {
  return {
    BMap: null,
    geolocation: null, // Geolocation对象实例
    positioning: false, // 定位中
    positioningInterval: null, // 定位倒计时计时器
    countDown: 30, // 倒计时,单位秒
    location: null // 位置信息
  }
}

四、在mounted中调用创建回调函数,并调用loadMap方法,将回调函数名称传递到loadMap中

mounted() {
  const _this = this
  window.initBaiduMapScript = () => {
    _this.BMap = window.BMap
  }
  loadBMap('initBaiduMapScript')
}

五、在methods中定义获取地理位置的方法

// 获取地理定位
getLocation() {
  const _this = this
  _this.geolocation = new _this.BMap.Geolocation()
  if (_this.geolocation) {
    // 开启SDK辅助定位,仅当使用环境为移动web混合开发,且开启了定位sdk辅助定位功能后生效
    _this.geolocation.enableSDKLocation()
    // 开始定位
    this.positioning = true
    // 倒计时
    this.positioningInterval = setInterval(() => {
      if (this.countDown === 0) {
        this.countDown = 30
        clearInterval(this.positioningInterval)
      } else {
        this.countDown--
      }
    }, 1000)
    // 位置选项
    const positionOptions = {
      enableHighAccuracy: true, // 要求浏览器获取最佳结果
      timeout: 30, //    超时时间
      maximumAge: 0 // 允许返回指定时间内的缓存结果。如果此值为0,则浏览器将立即获取新定位结果
    }
    // 获取用户位置信息
    _this.geolocation.getCurrentPosition(position => {
      _this.resetPositioning()
      // 获取定位结果状态码
      const statusCode = _this.geolocation.getStatus()
      let msg = '由于未知错误而无法检索设备的位置' // 提示消息
      let msgType = 'error' // 消息类型
      // 判断结果状态码,为0代表获取成功,读取省市、经纬度
      switch (statusCode) {
        case 0:
          msgType = 'success'
          msg = '获取地理位置定位请求成功'
          if (position) {
            // 数据变量定义
            let lat = 0.0 // 经度
            let lng = 0.0 // 纬度
            let province = '未知' // 经度
            let city = '未知' // 纬度

            // 坐标
            if (position.point) {
              lat = position.point.lat
              lng = position.point.lng
            }
            // 位置
            if (position.address) {
              province = position.address.province
              city = position.address.city
            }
            _this.location = {
              省份: province,
              城市: city,
              经度: lat,
              纬度: lng
            }
          } else {
            msg = '由于未知错误而无法检索设备的位置'
          }
          break
        case 2:
          msg = '由于未知错误而无法检索设备的位置'
          break
        case 4:
        case 5:
          msg = '位置服务请求非法'
          break
        case 6:
          msg = '应用程序没有使用位置服务的权限'
          break
        case 7:
          msg = '网络不可用或者无法连接到获取位置信息的卫星'
          break
        case 8:
          msg = '无法在指定的最大超时间隔内检索位置信息'
          break
        default:
          msg = '由于未知错误而无法检索设备的位置'
          break
      }
      _this.$notification[msgType]({
        key: NotificationKey,
        message: '提示',
        description: msg
      })
    }, positionOptions)
  } else {
    _this.$notification.error({
      key: NotificationKey,
      message: '提示',
      description: '您的浏览器不支持地理位置服务'
    })
  }
},
// 重置定位相关数据
resetPositioning() {
  this.positioning = false
  this.location = null
  this.countDown = 30
  clearInterval(this.positioningInterval)
}

六、在需要的地方调用getLocation即可,例如:

<a-form-model-item label="地理位置" prop="location">
  <span>{{ location }}</span>
  <a v-show="!location && !positioning" @click="getLocation">点击获取位置</a>
  <a-spin :spinning="positioning" />
  <span v-show="positioning">
    &nbsp;还需等待
    <span class="red">{{ countDown }}</span></span>
</a-form-model-item>

效果:

【获取前】

【获取中】

【获取后】

嘴角上扬,记得微笑
原文地址:https://www.cnblogs.com/jardeng/p/13574247.html