Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  67] [ 5]  / answers: 1 / hits: 20869  / 11 Years ago, tue, april 16, 2013, 12:00:00

Can I use Javascript in a cross-platform way to get the compass heading in iOS and Android (with Chrome), without using something like PhoneGap? I know iOS has DeviceOrientationEvent, but I can't find any equivalent on Chrome for Android.


More From » android

 Answers
58

Yes you can! Unfortunately the alpha doesn't work on iPhones/iPads. With Mobile Safari, alpha is based on the direction the device was pointing when device orientation was first requested. The included webkit offers you the compass heading. To make it work for all other browsers (which all supports alpha as compassheading) you can use the following Javascript code:



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


Android also supports Webkit, so would also use event.webkitCompassHeading, but that's OK.



BTW: oncompassneedscalibration is also not supported for iPhones and iPads.


[#78857] Tuesday, April 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zaynerogerb

Total Points: 454
Total Questions: 109
Total Answers: 97

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
zaynerogerb questions
;