How to detect device rotation in Cordova?
I would like to detect realtime rotation (not orientation, rotation in degrees) from Cordova. I used device movement but I am getting a bunch of xy and z acceleration values, how can I calculate rotation from this?
I would like to detect a full 360 degree rotation (imagine putting the device on a stick [or pendulum] and then hitting it to swing it).
Thank!
source to share
You can use the screen orientation API by installing the plugin mentioned by Gandhi in the comment.
cordova plugin add cordova-plugin-screen-orientation
Then you can use the event to detect the orientation change after deviceReady
;
window.addEventListener('orientationchange', function(){
console.log(screen.orientation.type); // e.g. portrait
});
or
screen.orientation.onchange = function({
console.log(screen.orientation.type);
});
You should be able to do this without a plugin to be honest, but it would be safer to add the cordova plugin.
How do you want to detect a 360 degree rotation that is not included, you have to count it yourself ... Something along the lines:
var startingPoint = 0;
window.addEventListener('orientationchange', monitorOrientation);
function monitorOrientation(e) {
console.log('Device orientation is: ', e. orientation);
if(e. orientation == 180 || e.orientation == -180) {
// You can extend this or remove it completely and increment the variable as you wish i.e. 4x90 = 360
startingPoint += 180;
}
if(startingPoint == 360) {
// Do whatever you want and reset starting point back to 0
startingPoint = 0;
}
}
source to share
The device configuration plugin gives you information about device rotation in terms of degrees.
But if you're looking for device motion detection, device motion is the only plugin I could see that comes close to that requirement. But the rotation count of the device should be tracked using custom logic that needs to be built on top of the x, y, z coordinates. No out of the box solution available in plugins, but as far as I tested
source to share