1.10. Using the Accelerometer to Detect Motion
Problem
You want to detect the motion of the device as it moves.
Solution
Similar to the compass, devices running iOS, Android, and BlackBerry 5.0 and above are able to detect the device’s current x, y, and z axis movements.
Three functions exist that work in the same way as the compass and
GPS location, which allow you to retrieve the current x, y, and z
coordinates through the use of the accelerometer.getCurrentAcceleration
function.
The accelerometer.watchAcceleration
function allows you to receive updates on the device’s position, while
the accelerometer.clearWatch
function
allows you to turn off receiving the updates.
Discussion
To demonstrate the accelerometer, I am going to use the new HTML5
canvas
tag and make an image of a
ball move around with the movement of the device. To start, a new HTML
page must be created inside of the assets/www directory: accelerometer.html.
<!DOCTYPE HTML> <html> <head> <title>PhoneGap</title> </head> <body> <div data-role="page" id="accelerometer-page"> <div data-role="header" data-position="inline"> <h1>Bouncing Ball</h1> </div> <canvas id="canvas" width="350" height="350" style="border: 2px solid #000"></canvas> <img id="ball" style="display: none" /> <div data-role="footer" data-position="fixed"> <div data-role="navbar"> <ul> <li><a href="index.html">Home</a></li> <li><a href="map.html">Map</a></li> <li><a href="compass.html">Compass</a></li> <li><a href="list.html">List</a></li> <li><a href="accelerometer.html" ...
Get 20 Recipes for Programming PhoneGap now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.