为了更好地为移动设备服务,HTML5推出了一系列针对移动设备的API。javascript
Geolocation接口用于获取用户的地理位置。它使用的方法基于GPS或者其余机制(好比IP地址、WIFI热点等)。html
下面的方法,能够检查浏览器是否支持这个接口。html5
if (navigator.geolocation) { // 支持 } else { //不支持 }
getCurrentPosition方法,用来获取用户的地理位置。使用它须要获得用户的受权,浏览器会跳出一个对话框,询问用户是否许可当前页面获取他的地理位置。必须考虑两种状况的回调函数:一种是赞成受权,另外一种是拒绝受权。若是用户拒绝受权会抛出一个错误。java
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
上面代码指定了处理当前地址位置的两个回调函数。git
若是用户赞成受权,就会调用geoSuccess。web
function geoSuccess(event) { var coords = event.coords; console.log('latitude: ' + coords.latitude); //纬度 console.log('longitude: ' + coords.longitude); //经度 console.log('accuracy: ' + coords.accuracy); //精度 console.log('altitude: ' + coords.altitude); //海拔 console.log('altitudeAccuracy: ' + coords.altitudeAccuracy); //海拔精度(单位:米) console.log('heading: ' + coords.heading); //以360度表示的方向 console.log('speed: ' + coords.speed); //每秒的速度(单位:米) }
geoSuccess的参数是一个event对象。event.coords属性指向一个对象,包含了用户的位置信息,主要是如下几个值:api
若是用户拒绝受权,就会调用geoError。数组
function geoError(event) { console.log('Error code ' + event.code + '. ' + event.message); }
geoError的参数也是一个event对象。event.code属性表示错误类型,有四个值:浏览器
event.message为错误提示信息。缓存
getCurrentPosition方法还能够接受一个对象做为第三个参数,用来设置定位行为。
var option = { enableHighAccuracy: true, timeout: Infinity, maximumAge: 0 }; navigator.geolocation.getCurrentPosition(geoSuccess, geoError, option);
这个参数对象有三个成员:
watchPosition方法能够用来监听用户位置的持续改变,使用方法与getCurrentPosition方法同样。
var watchID = navigator.geolocation.watchPosition(geoSuccess, geoError);
一旦用户位置发生改变,就会调用回调函数。
若是要取消监听,则使用clearWatch方法。
navigator.geolocation.clearWatch(watchID);
Vibration接口用于在浏览器中发出命令,使得设备振动。因为该操做很耗电,在低电量时最好取消该操做。
使用下面的代码检查该接口是否可用。目前,只有Chrome和Firefox的Android平台最新版本支持它。
navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate; if (navigator.vibrate) { // 支持 }
vibrate方法可使得设备振动,它的参数就是振动持续的毫秒数。
navigator.vibrate(1000);
上面的代码使得设备振动1秒钟。
vibrate方法还能够接受一个数组做为参数,表示振动的模式。偶数位置的数组成员表示振动的毫秒数,奇数位置的数组成员表示等待的毫秒数。
navigator.vibrate([500, 300, 500]);
上面代码表示,设备先振动500毫秒,而后等待300毫秒,再接着振动500毫秒。
vibrate是一个非阻塞式的操做,即手机振动的同时,JavaScript代码继续向下运行。要中止振动,只有将0毫秒传入vibrate方法。
navigator.vibrate(0);
当移动设备的亮度传感器,感知外部亮度发生显著变化时,会触发devicelight事件。目前,只有Firefox布署了这个API。
window.addEventListener('devicelight', function(event) { console.log(event.value + 'lux'); })
下面代码表示,devicelight事件的回调函数,接受一个事件对象做为参数。该对象的value属性就是亮度值。
这种API的一种应用是,咱们能够针对亮度的强弱来改网页背景和文字颜色。
[1] Ryan Stewart, Using the Geolocation API
[2] Rathnakanya K. Srinivasan, HTML5 Geolocation
[3] Craig Buckler, How to Use the HTML5 Vibration API
[4] Tomomi Imura, Responsive UI with Luminosity Level
[5] Ruanyf, 移动设备API