Geolocation是HTML5標準下的一個Web API,利用它可以獲取設備的當前位置信息(坐標),此API具有三個方法:getCurrentPosition、watchPosition和clearWatch,其中最常用的是getCurrentPosition方法,剩下兩個方法需要搭配使用!
使用方法:
瀏覽器兼容性檢測:
該api通過navigator.geolocation對象發布,只有在此對象存在的情況下,才可以使用它的地理定位服務,檢測方法如下:
if (navigator.geolocation) { // 定位代碼寫在這里} else { alert('Geolocation is not supported in your browser')}
獲取用戶的當前位置:
使用getCurrentLocation方法即可獲取用戶的位置信息,該方法有三個參數:
參數列表 | 類型 | 說明 |
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')}
下面是具有更多細節的代碼:
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')}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
|
新聞熱點
疑難解答