I would like to detect a live device rotation (not orientation, rotation in degrees) with Cordova. I used device motion but I get a bunch of acceleration x y and z 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 hit it so it swings).
Thanks!
You can use the 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 an event to detect 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 the plugin to be honest but would be would be safer to add the cordova plugin.
As you want to detect a 360 rotation, which isn't included, you need to count this yourself... Something along the lines of;
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;
}
}
maybe what you're looking for is the compass : cordova-plugin-device-orientation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With