PhoneGap学习笔记(三) 加速计、罗盘、地理位置
加速计方法
var watchID=navigator.accelerometer.watchAcceleration(onSuccess,onError,{frequency:500});
第一个参数为成功回调,第二个为失败回调,第三个为参数,表示每隔多少毫秒获取一次数据,方法返回一个ID
该ID用户清除加速计监听:
navigator.accelerometer.clearWatch(watchID);
加速计获取加速数据成功后会调用onSuccess方法
var msg=document.getElementById("msg"); var x=document.getElementById("x"); var y=document.getElementById("y"); var z=document.getElementById("z"); function onSuccess(acceleration){
msg.innerHTML=acceleration.timestamp; x.innerHTML=acceleration.x; y.innerHTML=acceleration.y; z.innerHTML=acceleration.z; }
罗盘方法:
var watchID=navigator.compass.watchHeading(onSuccess,onError,{frequency:500});
清除监听
navigator.compass.clearWatch(watchID);
罗盘获取加速数据成功后会调用onSuccess方法
function onSuccess(heading){ x.innerHTML=heading.magneticHeading; }
地理位置:
function init(){ var watchID=navigator.geolocation.watchPosition(onSuccess,onError,{frequency:500}); //navigator.geolocation.clearWatch(watchID); } function onSuccess(position){ msg.innerHTML='纬度: ' + position.coords.latitude + '\n' + '经度: ' + position.coords.longitude + '\n' + '高度: ' + position.coords.altitude + '\n' + '经纬度读取经度(米):' + position.coords.accuracy + '\n' + '高度读取经度(米): ' + position.coords.altitudeAccuracy + '\n' + '方向: ' + position.coords.heading + '\n' + '速度: ' + position.coords.speed + '\n' + '时间戳: ' + position.timestamp + '\n'; } function onError(){ }