Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect device rotation in Cordova?

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!

like image 327
trueicecold Avatar asked Oct 30 '22 05:10

trueicecold


2 Answers

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;
    } 
}
like image 138
Abdul Sadik Yalcin Avatar answered Jan 02 '23 19:01

Abdul Sadik Yalcin


maybe what you're looking for is the compass : cordova-plugin-device-orientation

like image 20
Djames Avatar answered Jan 02 '23 21:01

Djames