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

About Author

Author Image
Avilash Choudhary

Avilash has excellent experience in developing mobile and web applications using jQuery , Javascript and PhoneGap. His hobbies are watching and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..