| 參數(shù)列表 | 類型 | 說明 |
| handleSuccess | Function | 成功時(shí)調(diào)用函數(shù)handleSuccess |
| handleError | Function | 失敗時(shí)調(diào)用函數(shù)handleError |
| options | Object | 初始化參數(shù) |
// 初始化參數(shù)
const options = {
// 高精確度: true / false
enableHighAccuracy: true,
// 等待響應(yīng)的最長(zhǎng)時(shí)間 單位:毫秒
timeout: 5 * 1000,
// 應(yīng)用程序愿意接受的緩存位置的最長(zhǎng)時(shí)間
maximumAge: 0
}
// 成功回調(diào)函數(shù) : data包含位置信息
const handleSuccess = data => console.log(data)
// 失敗回調(diào)函數(shù) : error包含錯(cuò)誤信息
const handleError = error => console.log(error)
if (navigator.geolocation) {
// 定位代碼寫在這里
navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options)
} else {
alert('Geolocation is not supported in your browser')
}
下面是具有更多細(xì)節(jié)的代碼:
const handleSuccess = data => {
const {
coords, // 位置信息
timestamp // 成功獲取位置信息時(shí)的時(shí)間戳
} = data
const {
accuracy, // 返回結(jié)果的精度(米)
altitude, // 相對(duì)于水平面的高度
altitudeAccuracy, // 返回高度的精度(米)
heading, // 主機(jī)設(shè)備的行進(jìn)方向,從正北方向順時(shí)針方向
latitude, // 緯度
longitude, // 經(jīng)度
speed // 設(shè)備的行進(jìn)速度
} = 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('位置服務(wù)請(qǐng)求被拒絕')
break
case 2:
console.log('暫時(shí)獲取不到位置信息')
break
case 3:
console.log('獲取信息超時(shí)')
break
case 4:
console.log('未知錯(cuò)誤')
break
}
}
const opt = {
// 高精確度: true / false
enableHighAccuracy: true,
// 等待響應(yīng)的最長(zhǎng)時(shí)間 單位:毫秒
timeout: 5 * 1000,
// 應(yīng)用程序愿意接受的緩存位置的最大年限
maximumAge: 0
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(handleSuccess, handleError, opt)
} else {
alert('Geolocation is not supported in your browser')
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
標(biāo)簽:紅河 咸陽 甘南 文山 惠州 萍鄉(xiāng) 蘇州 營(yíng)口
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《HTML5 Geolocation API的正確使用方法》,本文關(guān)鍵詞 HTML5,Geolocation,API,的,正確,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。