我目前正在开发的应用需要知道设备的方向,因此我使用以下代码来检测方向变化事件:
window.addEventListener('orientationchange', function(){
theApp.orientationChange();
});
同时,通过该属性获得实际方向值:
window.orientation
问题:在两种横屏模式之间切换时,不会触发任何事件,并且方向保持在现在错误的90度或-90度。
我正在测试2个Android设备,运行2.3.5和4.4.4,两者都显示相同的行为。
因此,问题是:
- 是否有解决方法? - 如何检测此事件?
- 此错误仅在Android上显示,还是其他平台也受到影响?
我希望我的应用程序显示从用户位置到目标地理位置的方向。
为此,我需要两个不同的方向信息:
- 指南针方向
- 屏幕方向
org.apache.cordova.device-orientation 0.3.10 "Device Orientation"
我使用
navigator.compass.watchHeading
获取方向更新 - 这一部分正常工作。
为了创建一个指向目标位置的箭头元素,应用程序不仅需要知道罗盘方向,还需要知道屏幕方向(从window.orientation属性中获取的0、90、-90和180度的值)。
但是,在从横向1直接旋转到横向2的情况下,Android设备上的window.orientation属性将是错误的,而没有经过纵向模式。此外,此情况下不会触发orientationchange事件。
KRIZTE引用的IOS示例代码(顺便说一句:示例中没有IOS特定的内容,该代码应在每个WebView中运行)依赖于正确的window.orientation值。提到的问题(延迟的初始更新)并不是我的代码的问题。
用于检查window.orientation的(测试)代码:
setInterval(function(){
console.log('WO ' + window.orientation);
}, 1000);
等待屏幕方向改变事件:
window.addEventListener('orientationchange', function(){
console.log('window.orientation : ' + window.orientation);
});
注释日志:
[starting app]
[check function returns correct value:]
"WO 0"
...
[change device orientation to landscape 1]
[got orientationchanged event, value is correct]
"window.orientation : 90"
[check function returns correct value:]
"WO 90"
...
[change device orientation back to portrait]
[got orientationchanged event, value is correct]
"window.orientation : 0"
[check function returns correct value:]
"WO 0"
...
[change device orientation to landscape 2]
[got orientationchanged event, value is correct]
"window.orientation : -90"
[check function returns correct value:]
"WO -90"
...
[change device orientation to landscape 1]
... < Problem 1: no orientationchanged event
"WO -90" < Problem 2: wrong window.orientation value, value should be +90 deg
...