Javatpoint Logo
Javatpoint Logo

Reading the Accelerometer

We know that PhoneGap is designed to make it easy to develop a cross-platform application. PhoneGap would not be much powerful if it will not have the ability to interact with device hardware. In this section, we will work with the accelerometer to determine the device's position in space. There will be the following steps used to work with the accelerometer in PhoneGap:

1) Create a new project

Firstly, we will create a new PhoneGap project with a blank template. If you don't know how to create an app with a blank template, go through the PhoneGap project link.

Reading the Accelerometer
Reading the Accelerometer

2) Create window.onload function

Now, we will change the title tag with our preferred title. We will create window.onload function in between the <script></script> tags. In this window.onload function, we will turn on our accelerometer. For this purpose, we will call the navigator and watch the acceleration consistently. When the acceleration change, it will return new values for the x, y, and z-axis.

The watchAcceleration function has three callback functions, i.e., success, fail, and frequency. This last function is the options which we send to the accelerometer. This will be coded as:

3) Create callback functions

Now, we will create success and fail callback function. The fail function will be called when any kind of failure occurs. This function contains only an alert function. After that, we will create a success function. In this function, we will get an object which contains the acceleration information. This function takes the acceleration information as an argument.

We will first deal with the actual X value. So, we will create an output field in the user interface and give an Id to id using id property in the following way:


Reading the Accelerometer

Now, in the success function, we will get the outX element using the document.getElementById() and set the X value from the acceleration information in the following way:

In the same way, we will do for Y and Z. We will create output fields for them and get both the element.

Creating output fields for Y and Z

Getting outY and outZ element

Complete code:

Output:

Reading the Accelerometer




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA