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
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:
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