Sea*_* W. 12 javascript html5 android ios
我可以在跨平台的方式中使用Javascript来获取iOS和Android(使用Chrome)的指南针标题,而无需使用像PhoneGap这样的东西吗?我知道iOS有DeviceOrientationEvent,但我在Chrome for Android上找不到任何等价物.
ric*_*cht 19
作为入门读物,您应该查看之前相关的StackOverflow答案,并熟悉在Web应用程序中使用DeviceOrientation事件的一般实际注意事项.
我在之前的相关StackOverflow答案中提供的简单解决方案仅适用于实现absolutedeviceorientation事件的浏览器(即,deviceorientation alpha属性是面向罗盘的浏览器).这意味着目前提供的解决方案仅适用于Android浏览器,而不适用于基于iOS的浏览器或任何其他不提供absolute基于设备定向事件数据的浏览器.
为了可靠地获取当前Android和iOS浏览器的当前罗盘标题,您需要处理提供附加属性的absolute非absolute实现和非实现,webkitCompassHeading并确保考虑任何当前屏幕方向更改作为其中的一部分.AFAIK目前唯一的这个库是Full Tilt JS(免责声明:我是这个库的作者).
以下代码将为iOS和Android浏览器提供相同的正确罗盘标题,同时考虑到设备方向实现的差异以及应用任何必要的运行时屏幕方向变换:
<!-- Include the Full Tilt JS library from https://github.com/richtr/Full-Tilt-JS -->
<script src="fulltilt-min.js"></script>
<script>
// Obtain a new *world-oriented* Full Tilt JS DeviceOrientation Promise
var promise = FULLTILT.getDeviceOrientation({ 'type': 'world' });
// Wait for Promise result
promise.then(function(deviceOrientation) { // Device Orientation Events are supported
// Register a callback to run every time a new
// deviceorientation event is fired by the browser.
deviceOrientation.listen(function() {
// Get the current *screen-adjusted* device orientation angles
var currentOrientation = deviceOrientation.getScreenAdjustedEuler();
// Calculate the current compass heading that the user is 'looking at' (in degrees)
var compassHeading = 360 - currentOrientation.alpha;
// Do something with `compassHeading` here...
});
}).catch(function(errorMessage) { // Device Orientation Events are not supported
console.log(errorMessage);
// Implement some fallback controls here...
});
</script>
Run Code Online (Sandbox Code Playgroud)
这是一个演示,演示了这种技术,以获得用户正面临的罗盘方向.它应该适用于iOS和Android浏览器.
该演示中的代码实现如上所示,可以在Github上查看./scripts/compass.js:L268-L272.
是的你可以!不幸的是,alpha它不适用于iPhone/iPad.使用Mobile Safari时,alpha它基于设备首次请求设备方向时指向的方向.随附的webkit为您提供指南针标题.为了使所有其他浏览器(所有支持alpha的compassheading),可以使用下面的JavaScript代码:
if (window.DeviceOrientationEvent) {
// Listen for the deviceorientation event and handle the raw data
window.addEventListener('deviceorientation', function(eventData) {
var compassdir;
if(event.webkitCompassHeading) {
// Apple works only with this, alpha doesn't work
compassdir = event.webkitCompassHeading;
}
else compassdir = event.alpha;
});
}
Run Code Online (Sandbox Code Playgroud)
Android也支持Webkit,所以也会使用event.webkitCompassHeading,但没关系.
顺便说一句:oncompassneedscalibrationiPhone和iPad也不支持" ".
| 归档时间: |
|
| 查看次数: |
13430 次 |
| 最近记录: |