1. 程式人生 > 實用技巧 >Vue 通過呼叫百度API獲取地理位置-經度緯度省份城市

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>

效果:

【獲取前】

【獲取中】

【獲取後】