HTML5 定位 —— Geolocation API的正確使用

Geolocation是HTML5標準下的一個Web API,利用它能夠獲取設備的當前位置信息(座標),此API具備三個方法:getCurrentPosition、watchPosition和clearWatch,其中最經常使用的是getCurrentPosition方法,剩下兩個方法須要搭配使用!javascript

使用方法:

  1. 瀏覽器兼容性檢測:

該api經過navigator.geolocation對象發佈,只有在此對象存在的狀況下,才能夠使用它的地理定位服務,檢測方法以下:java

if (navigator.geolocation) {
	// 定位代碼寫在這裏
} else {
	alert('Geolocation is not supported in your browser')
}
複製代碼
  1. 獲取用戶的當前位置:

使用getCurrentLocation方法便可獲取用戶的位置信息:git

該方法有三個參數:api

參數列表 類型 說明
handleSuccess Function 成功時調用函數handleSuccess
handleError Function 失敗時調用函數handleError
options Object 初始化參數
// 初始化參數
const options = {
  // 高精確度: true / false
  enableHighAccuracy: true,
  // 等待響應的最長時間 單位:毫秒
  timeout: 5 * 1000,
  // 應用程序願意接受的緩存位置的最長時間
  maximumAge: 0
}

// 成功回調函數 : data包含位置信息
const handleSuccess = data => console.log(data)

// 失敗回調函數 : error包含錯誤信息
const handleError = error => console.log(error)

if (navigator.geolocation) {
	// 定位代碼寫在這裏
	navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options)
} else {
	alert('Geolocation is not supported in your browser')
}

複製代碼
  1. 更多細節的代碼
const handleSuccess = data => {
  const { 
    coords, // 位置信息
    timestamp // 成功獲取位置信息時的時間戳
  } = data

  const {
    accuracy, // 返回結果的精度(米)
    altitude, // 相對於水平面的高度
    altitudeAccuracy, // 返回高度的精度(米)
    heading, // 主機設備的行進方向,從正北方向順時針方向
    latitude, // 緯度
    longitude, // 經度
    speed // 設備的行進速度
  } = coords

  // 打印出來看看
  console.log('timestamp =', timestamp)
  console.log('accuracy =', accuracy)
  console.log('altitude =', altitude)
  console.log('altitudeAccuracy =', altitudeAccuracy)
  console.log('heading =', heading)
  console.log('latitude =', latitude)
  console.log('longitude =', longitude)
  console.log('speed =', speed)
}

const handleError = error => {
  switch (error.code) {
    case 1:
      console.log('位置服務請求被拒絕')
      break
    case 2:
      console.log('暫時獲取不到位置信息')
      break
    case 3:
      console.log('獲取信息超時')
      break
    case 4:
      console.log('未知錯誤')
      break
  }
}

const opt = {
  // 高精確度: true / false
  enableHighAccuracy: true,
  // 等待響應的最長時間 單位:毫秒
  timeout: 5 * 1000,
  // 應用程序願意接受的緩存位置的最大年限
  maximumAge: 0
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(handleSuccess, handleError, opt)
} else {
  alert('Geolocation is not supported in your browser')
}

複製代碼
相關文章
相關標籤/搜索