Apache Cordova | Phonegap Accelerometer tutorial with example (Device Motion)

phonegap device motion example

What is accelerometer ?

Accelerometer is a feature where you can capture device motion in the x, y, and z direction.

About Sensor

An accelerometer is an electromechanical device used to measure acceleration forces. Such forces may be static, like the continuous force of gravity or, as is the case with many mobile devices, dynamic to sense movement or vibrations. Acceleration is the measurement of the change in velocity, or speed divided by time.

phonegap device motion example
phonegap device motion example

Accelerometer in phonegap

We can also capture device motion with phonegap-device-motion plugin

phonegap device motion plugin installation

cordova plugin add org.apache.cordova.device-motion

Methods:
There are three methods in device-motion (Accelerometer) plugin such as

  • getCurrentAcceleration – returns current acceleration
  • watchAcceleration – continuously watch acceleration
  • clearWatch – clear all

Objects:
Acceleration

phonegap accelerometer tutorial with example


function onSuccess(acceleration) {
    alert('Acceleration X: ' + acceleration.x + 'n' +
          'Acceleration Y: ' + acceleration.y + 'n' +
          'Acceleration Z: ' + acceleration.z + 'n' +
          'Timestamp: '      + acceleration.timestamp + 'n');
};
function onError() {
    alert('onError!');
};
var options = { frequency: 3000 };  // Update every 3 seconds
var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);

Full Example

<!DOCTYPE html>
<html>
<head>
<title>Acceleration Example</title>
<script type="text/javascript" charset="utf-8">
var watchID = null;
function onLoad(){
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
startWatch();
}
function startWatch() {
var options = { frequency: 1000 };
watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
}
function stopWatch() {
if (watchID) {
navigator.accelerometer.clearWatch(watchID);
watchID = null;
}
}
function onSuccess(acceleration) {
var element = document.getElementById('accelerometer');

element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' +
'Acceleration Y: ' + acceleration.y + '<br />' +
'Acceleration Z: ' + acceleration.z + '<br />' +
'Timestamp: ' + acceleration.timestamp + '<br />';
}
function onError() {
alert('onError!');
}
</script>
</head>
<body onload="onLoad()">
<div id="accelerometer">Waiting for accelerometer...</div>
<button onclick="startWatch();">Start Watching</button>
<button onclick="stopWatch();">Stop Watching</button>
<script type="text/javascript" src="cordova.js"></script>
</body>
</html>