Detecting device motion in phonegap
Posted By : Avilash Choudhary | 31-Dec-2015
This plugin provide access to device’s accelerometer. Accelerometer is motion sensor that detects change in movement relative to current device orientation, it calculates the dimensions in x,y and z axis.
You can access the dimensions using the global navigator.accelerometer object.
Install the plugin using below command
cordova plugin add cordova-plugin-device-motion
There are methods available to get the acceleration
navigator.accelerometer.getCurrentAcceleration
this method returns the current acceleration with x,y and z axes
navigator.accelerometer.getCurrentAcceleration(function(acceleration){
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
}, function(){
alert('onError!');
});
navigator.accelerometer.watchAcceleration
Retrieves device current Acceleration at regular interval, executing accelerometerSuccess callback function each time. Specify interval in milliseconds via acceleratorOptions object’s frequency parameter.
Returned watch ID references accelerometer’s watch interval and can be used with navigator.accelerometer.clearWatch to stop watching accelerometer.
var watchID = navigator.accelerometer.watchAcceleration(function(acceleration
){
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
}, function(){
alert('onError!');
}, { frequency: 3000 }
);
navigator.accelerometer.clear.Watch
Stop watching Acceleration referenced by watchID parameter.
navigator.accelerometer.clearWatch(watchID); // this will clear the above created watch using navigator.accelerometer.watchAcceleration
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Avilash Choudhary
Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.