这期内容当中小编将会给大家带来有关如何在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了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://www.jb51.net/html5/649066.html