获取当前指南针的状态
方法
compass.getCurrentHeading---罗盘的当前朝向
compass.watchHeading---固定的时间间隔获取罗盘朝向的角度
compass.clearWatch---停止watch ID参数指向的罗盘监视
compass.watchHeadingFilter---当罗盘至少改变一定度数时获取罗盘的朝向度数
compass.clearWatchFilter---停止对通过watchID参数指定的罗盘的监听
参数
compassSuccess---成功调用函数
compassError---失败调用函数
compassOptions---可选参数,刷新频率,过滤
compassHeading---传递信息
截图:
方法
compass.getCurrentHeading---罗盘的当前朝向
compass.watchHeading---固定的时间间隔获取罗盘朝向的角度
compass.clearWatch---停止watch ID参数指向的罗盘监视
compass.watchHeadingFilter---当罗盘至少改变一定度数时获取罗盘的朝向度数
compass.clearWatchFilter---停止对通过watchID参数指定的罗盘的监听
参数
compassSuccess---成功调用函数
compassError---失败调用函数
compassOptions---可选参数,刷新频率,过滤
compassHeading---传递信息
代码:
<!DOCTYPE html>
<html>
<head>
<title>指南针</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8">
// watchID是当前 “watchHeading” 的引用
var watchID = null;
var watchid2=null;
// 等待加载PhoneGap
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap加载完毕
function onDeviceReady() {
initStart();
startFWatch();
startWatch();
}
function initStart(){
navigator.compass.getCurrentHeading(onInitSuccess, onInitError);
}
// onSuccess: 返回当前的朝向数据
function onInitSuccess(heading) {
alert('当前朝向: ' + heading.magneticHeading);
}
// onError: 返回朝向数据失败
function onInitError(compassError) {
alert('指南针错误: ' + compassError.code);
}
// 开始监视罗盘
function startFWatch() {
// 每隔1秒钟更新一次罗盘数据
var options = { frequency: 1000 };
watchID = navigator.compass.watchHeading(onFSuccess, onFError, options);
}
// 停止监视罗盘
function stopFWatch() {
if (watchID) {
navigator.compass.clearWatch(watchID);
watchID = null;
}
}
// onSuccess: 返回罗盘的当前朝向
function onFSuccess(heading) {
var element = document.getElementById('heading');
element.innerHTML = '朝向: ' + heading.magneticHeading;
}
// onError: 获取罗盘朝向失败
function onFError(compassError) {
alert('指南针错误: ' + compassError.code);
}
// 开始监视罗盘
function startWatch() {
// 当罗盘的方向改变大于或等于10度时获取通知
var options = {filter: 10 };
watchid2 = navigator.compass.watchHeadingFilter(onSuccess, onError, options);
}
// 停止监视罗盘
function stopWatch() {
if (watchid2) {
navigator.compass.clearWatchFilter(watchID);
watchID = null;
}
}
// onSuccess: 返回罗盘的当前朝向
function onSuccess(heading) {
var element = document.getElementById('heading2');
element.innerHTML = '朝向: ' + heading.magneticHeading;
}
// onError: 获取罗盘朝向失败
function onError(compassError) {
alert('指南针错误: ' + compassError.code);
}
</script>
</head>
<body>
<div id="heading">等待指南针定位…………</div>
<div id="heading2">变化大于10度才改变…………</div>
---固定频率监视指南针---
<button οnclick="startFWatch();">开始</button>
<button οnclick="stopFWatch();">停止</button>
---固定频率监视指南针并过滤后显示---<br>
<button οnclick="startWatch();">开始</button>
<button οnclick="stopWatch();">停止</button>
</body>
</html>
截图: