一、cordova-plugin-device-motion加速计
这个插件提供了对设备加速度计的访问。加速度计是一种运动传感器,它检测相对于当前设备方向的运动变化(增量),在x、y和z轴上的三维变化。
这个插件的API类似地理位置API,一个获取状态getCurrentAcceleration,一个监听状态watchAcceleration
1.安装命令:
cordova plugin add cordova-plugin-device-motion
2.获取加速状态,x/y/z和当前时间戳
获取acceleration对象属性
- x: Amount of acceleration on the x-axis. (in m/s^2) (Number)
- y: Amount of acceleration on the y-axis. (in m/s^2) (Number)
- z: Amount of acceleration on the z-axis. (in m/s^2) (Number)
- timestamp: Creation timestamp in milliseconds. (DOMTimeStamp)
//获取加速信息 navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); function onSuccess(acceleration) { console.info(acceleration); acceleration.x// app.curInfo = JSON.stringify(acceleration); } function onError() { alert('获取失败'); }3.监听加速计状态/清楚监听
//监听加速状态 watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, { frequency: 1000 //设置触发时间间隔 }); function onSuccess(acceleration) { app.watchInfo = JSON.stringify(acceleration); } function onError() { alert('获取失败'); }
//清楚监听 navigator.accelerometer.clearWatch(watchID);
一些Android设备如果平放在桌面上,加速计大致返回这样的值:X:0, Y:0, Z:10,翻转后它就位于现在位置的左边,值就调整为X:10,Y:0,Z:0,把设备从底边立起来,置变为X:0, Y:10, Z:0,从顶边立起来,置变为X:0, Y:-10, Z:0。应用就使用这样的值判断用户怎么拿设备,多用在游戏和交互性的应用上。
二、cordova-plugin-device-orientation设备方向(指南针Compass)
cordova plugin add cordova-plugin-device-orientation
1.Compass API可以让开发者读取移动设备的朝向。这个API的使用和Accelerometer API基本一样,既可以一次查找朝向值也可以定义个监视器定期测量朝向值。
和Compass API提供了也三个方法:
- compass.getCurrentHeading
- compass.watchHeading
- compass.clearWatch
heading对象(即例子中的res)返回给onSuccess函数,它的属性值如下表:
属性 | 描述 |
---|---|
magneticHeading | 以从0到359的度数表示compass的朝向值 |
trueHeading | compass相对于北极的朝向值,范围从0到259度。负值表示真实的朝向值不能确定 |
headingAccuracy | 用度数表示磁极朝向和真实朝向值的不同 |
timestamp | 朝向值测量的日期和时间(从1970年1月1日午夜开始的毫秒数) |
错误发生时,onFailure函数传入错误代码可以判断错误的原因。可能的值有CompassError.COMPASS_INTERNAL_ERR和CompassError.COMPASS_NOT_SUPPORTED。
2.获取方向信息:
//1.获取方向信息 navigator.compass.getCurrentHeading(onSuccess, onError); function onSuccess(res) { app2.orientation1 = JSON.stringify(res); } function onError(err) { alert('Error:' + err.code); }3.监听、取消监听方向
watchID2 = navigator.compass.watchHeading(onSuccess, onError, { frequency: 1000 }); function onSuccess(res) { app2.orientation2 = JSON.stringify(res); } function onError(err) { alert('Error:' + err.code); }
navigator.compass.clearWatch(watchID);两个插件测试显示:
更多:
cordova-plugin-globalization本地化