2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > HTML5 定位 —— Geolocation API的正确使用

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

时间:2018-11-01 06:24:48

相关推荐

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方法即可获取用户的位置信息:

该方法有三个参数:

// 初始化参数const options = {// 高精确度: true / falseenableHighAccuracy: 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 // 成功获取位置信息时的时间戳} = dataconst {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('位置服务请求被拒绝')breakcase 2:console.log('暂时获取不到位置信息')breakcase 3:console.log('获取信息超时')breakcase 4:console.log('未知错误')break}}const opt = {// 高精确度: true / falseenableHighAccuracy: true,// 等待响应的最长时间 单位:毫秒timeout: 5 * 1000,// 应用程序愿意接受的缓存位置的最大年限maximumAge: 0}if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(handleSuccess, handleError, opt)} else {alert('Geolocation is not supported in your browser')}复制代码

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。