Demo
En la siguiente demostración se muestra el código del index.html con el código embebido para que se pueda utilizar directamente.
Nota: No mostramos el css
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Brújula</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
<div id="heading">Esperando a brújula...</div>
<button>STOP</button>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
var watchID = null;
//cargar las librerias de APIs
document.addEventListener("deviceready", onDeviceReady, false);
// Cuando esten cargadas las librerias
//
function onDeviceReady(){
onWatch();
}
// Cargar el ID del sensor
//
function onWatch(){
var options = { frequency: 1000 };
watchID = navigator.compass.watchHeading(onSuccess, onError, options);
}
// Si da exito
//
function onSuccess(heading){
$("#heading").html(heading.magneticHeading + "º");
}
// Si da error
//
function onError(compassError){
alert("Ocurrió un error: " + compassError.code);
}
// Detener la captura
//
$("button").click(function(){
navigator.compass.clearWatch(watchID);
watchID = null;
});
});
</script>
</body>
</html>
Vídeo de demostración de la aplicación