检测cordova中的设备方向

时间:2017-04-08 19:42:14

标签: javascript android ios cordova phonegap-plugins

有没有办法通过访问加速度计,指南针或其他来检测Cordova中的物理设备方向?

我想检测设备是侧面(即横向)还是直立(即纵向)。除了cordova detecting orientation change之外,我无法通过window.orientation使用定位,因为如果用户锁定了他们的定位,它就会失败。

我不需要知道用户所处的模式。只需要知道设备是侧面还是直立。

1 个答案:

答案 0 :(得分:0)

我找到了一篇描述how device orientation can be read from accelerometer despite a locked device orientation的博客文章。

相关的代码段在Objective-C中提供,但自然适用于Phonegap,因为它可以通过Cordova's Device Motion Plugin进行翻译和使用。

这是原作:

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];
}

解释:对于任何不等于零的实参x和y,atan2(y,x)是平面的正x轴与点之间的弧度角由指定的坐标给出。对于逆时针角度,角度为正,对于顺时针角度,角度为负。