這期內容當中小編將會給大家帶來有關如何在HTML5中使用Geolocation API,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
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')
}上述就是小編為大家分享的如何在HTML5中使用Geolocation API了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。