- PhoneGap 4 Mobile Application Development Cookbook
- Zainul Setyo Pamungkas
- 812字
- 2021-07-09 21:26:47
Detecting device movement using the accelerometer
The accelerometer captures device motion in the x, y, and z axis direction. The accelerometer is a motion sensor that detects change (delta) in movement relative to the orientation of the current device.
How to do it…
We will use the accelerometer functionality from the plugins to monitor the feedback from the device:
- First, create a new PhoneGap project named
accelerometer
. Open Terminal or Command Prompt and run the following command:phonegap create accelerometer com.myapp.accelerometer accelerometer
- Add the device's platform. You can choose to use Android, iOS, or both:
cordova platform add ios cordova platform add android
- Add the
device-motion
plugin by running the following command:phonegap plugin add org.apache.cordova.device-motion
- Open
www/index.html
and clean up unnecessary elements; so you have the following:<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" /> <meta name="msapplication-tap-highlight" content="no" /> <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>Hello World</title> </head> <body> <h1>Accelerometer Data</h1> <div id="accelerometerData">Obtaining data…</div> <script type="text/javascript" src="cordova.js"></script> <script type="text/javascript"> </script> </body> </html>
- Below the Cordova JavaScript reference, write a new JavaScript tag block and define an event listener to ensure that the device is ready and the native code has loaded before continuing:
<script type="text/javascript"> // Set the event listener to run // when the device is ready document.addEventListener('deviceready', onDeviceReady, false); </script>
- Now add in the
onDeviceReady
function, which will run thegetCurrentAcceleration
method when the native code has fully loaded:// The device is ready so let's // obtain the current accelerometer data function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration( onSuccess, onError); }
- Include the
onSuccess
function to handle the returned information from the accelerometer. - Define the
accelerometer div
element to theaccElement
variable to hold the generated accelerometer results. - Next, assign the returned values from the
acceleration
object as the HTML within theaccelerometer div
element for display to the user; the available properties are accessed through theacceleration
object:// Run after successful transaction // Let's display the accelerometer data function onSuccess(acceleration) { var accElement = document.getElementById('accelerometerData'); accElement.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' + 'Acceleration Y: ' + acceleration.y + '<br />' + 'Acceleration Z: ' + acceleration.z + '<br />' + 'Timestamp: ' + acceleration.timestamp; }
- Finally, include the
onError
function to deal with any possible issues:// Run if we face an error // obtaining the accelerometer data function onError(error) { // Handle any errors we may face alert('error'); }
- Build and run the project:
cordova build android cordova run android
- When running the application on an emulator, the output will look something like this:
How it works…
By registering an event listener to the deviceready
event, we are ensuring that the JavaScript code does not run before the native PhoneGap code is executed. Once ready, the application will call the getCurrentAcceleration
method from the accelerometer API, providing two methods to handle successful transactions and errors respectively.
The onSuccess
function returns the obtained acceleration information in the form of the following four properties:
acceleration.x
: This is aNumber
registered in meters per second squared (m/s^2) that measures the device acceleration across the x axis. This is the movement from left to right when the device is placed with the screen in an upright position. Positive acceleration is obtained as the device is moved to the right, whereas a negative movement is obtained when the device is moved to the left.acceleration.y
: This is aNumber
registered in m/s^2 that measures the device acceleration across the y axis. This is the movement from bottom to top when the device is placed with the screen facing an upright position. Positive acceleration is obtained as the device is moved upwards, whereas a negative movement is obtained when the device is moved downwards.acceleration.z
: This is aNumber
registered in m/s^2 that measures the device acceleration across the z axis. This is perpendicular from the face of the device. Positive acceleration is obtained when the device is moved to face towards the sky, whereas a negative movement is obtained when the device is pointed towards the Earth.acceleration.timestamp
: This is aDOMTimeStamp
that measures the number of milliseconds from the point of the application's initialization. This could be used to store, update and track changes over a period of time since the last accelerometer update.
The following diagram shows the X, Y, and Z axis in relation to the device:

The acceleration.x
, acceleration.y
, and acceleration.z
values returned from the aforementioned acceleration object include the effect of gravity, which is defined as precisely 9.81 m/s^2.
There's more...
Accelerometer data obtained from devices has been used to great effect in mobile handset games that require balance control and detection of movement, including steering, control views, and tilting objects. You can check out the official Cordova documentation covering the getCurrentAcceleration
method and obtaining accelerometer data.
See also
- You can check out the official Cordova documentation covering the
getCurrentAcceleration
method and obtaining accelerometer data at http://plugins.cordova.io/#/package/org.apache.cordova.device-motion.