Skip to Main Content
20 Recipes for Programming PhoneGap
book

20 Recipes for Programming PhoneGap

by Jamie Munro
March 2012
Intermediate to advanced content levelIntermediate to advanced
78 pages
1h 35m
English
O'Reilly Media, Inc.
Content preview from 20 Recipes for Programming PhoneGap

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" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

HTML5 Mobile Websites

HTML5 Mobile Websites

Matthew David
PhoneGap Build

PhoneGap Build

Bintu Harwani

Publisher Resources

ISBN: 9781449334383Supplemental ContentErrata