问题
Is it possible to access the compass with Javascript on an iphone/ android device from a web app? Have been looking all over the net for hours I know you can access the accelerometer with
window.ondevicemotion = function(event)
Does anyone know if you can access the information from the compass??
回答1:
On iPhone, you can get the compass value like this.
window.addEventListener('deviceorientation', function(e) {
console.log(e.webkitCompassHeading);
}, false);
Hope this help.
回答2:
It looks to be cross platform now, check this excellent article by Ruadhán O'Donoghue.
For Android, it still uses window.addEventListener('deviceorientation', ...)
but check for other event properties (event.alpha
which is compass orientation ; beta
and gamma
are also available, which represent the tilting).
Here are the relevant parts (adapted) if the link becomes unavailable:
if(window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', function(event) {
var alpha;
// Check for iOS property
if(event.webkitCompassHeading) {
alpha = event.webkitCompassHeading;
}
// non iOS
else {
alpha = event.alpha;
if(!window.chrome) {
// Assume Android stock
alpha = alpha-270;
}
}
}
}
Another usage example is available on CodePen.
来源:https://stackoverflow.com/questions/5918982/access-device-compass-from-webb-app-with-javascript