zaph0t
zaph0t

Reputation: 101

Detecting device orientation in cordova

Is there a way to detect physical device orientation in Cordova by accessing accelerometer, compass, or others?

I'd like to detect if a device is either sideways (ie landscape) or upright (ie portrait). Other than: cordova detecting orientation change I won't be able to utilise orientation via window.orientation because it fails in case a user has locked their orientation.

I don't need to know the mode that user is in. Just need to know if the device is sideways or upright.

Upvotes: 0

Views: 344

Answers (1)

zaph0t
zaph0t

Reputation: 101

I found a blog entry that describes how device orientation can be read from accelerometer despite a locked device orientation.

The relevant code snippet is provided in Objective-C, but naturally applies to Phonegap since it can be translated and used via Cordova's Device Motion Plugin.

Here's the original:

float x = -[acceleration x];
float y = [acceleration y];
float angle = atan2(y, x);

if(angle >= −2.25 && angle <= −0.75) {
   //OrientationPortrait
} else if(angle >= −0.75 && angle <= 0.75){
   //OrientationLandscapeRight
} else if(angle >= 0.75 && angle <= 2.25) {
   //OrientationPortraitUpsideDown
} else if(angle <= −2.25 || angle >= 2.25) {
   //OrientationLandscapeLeft];
}

Explanation: For any real arguments x and y that are not both equal to zero, atan2(y, x) is the angle in radians between the positive x-axis of a plane and the point given by the specified coordinates on it. The angle is positive for counter-clockwise angles, and negative for clockwise angles.

Upvotes: 0

Related Questions