>>I'm trying to get accurate heading information from the deviceorientation event.
>>
>>Till now I've just been using the alpha value and generally this is good but occasionally the heading will 'flick' a random number of degrees. I'm assuming this is because it needs to be corrected with the y and z axis values (beta,gamma). I've tried using the following code (from
http://w3c.github.io/deviceorientation/spec-source-orientation.html ) :
var degtorad = Math.PI / 180; // Degree-to-Radian conversion
>>
>>function compassHeading2(alpha, beta, gamma , absolute) {
>>
>> var _x = beta ? beta * degtorad : 0; // beta value
>> var _y = gamma ? gamma * degtorad : 0; // gamma value
>> var _z = alpha ? alpha * degtorad : 0; // alpha value
>>
>> var cX = Math.cos(_x);
>> var cY = Math.cos(_y);
>> var cZ = Math.cos(_z);
>> var sX = Math.sin(_x);
>> var sY = Math.sin(_y);
>> var sZ = Math.sin(_z);
>>
>> // Calculate Vx and Vy components
>> var Vx = -cZ * sY - sZ * sX * cY;
>> var Vy = -sZ * sY + cZ * sX * cY;
>>
>> // Calculate compass heading
>> var compassHeading = Math.atan(Vx / Vy);
>>
>> // Convert compass heading to use whole unit circle
>> if (Vy < 0) {
>> compassHeading += Math.PI;
>> } else if (Vx < 0) {
>> compassHeading += 2 * Math.PI;
>> }
>>
>> return compassHeading * (180 / Math.PI); // Compass Heading (in degrees)
>>}
but, instead of improving matters, this results in even more wildly erratic behaviour.
>>
>>I'm testing on a Nexus 7 with Chrome browser. The hardware seems OK (Nexus apps showing a compass are smooth and accurate).
>>Anyone know what the problem may be (or of an existing html page that demonstrates good results) ?
>
>
>(1) Is the output of compassHeading2() correct ?
>(2) How terrible is 'erratic'
>(3) assuming (1) is ok, what is your update frequency ?
>(4) Didn't you have a similar question in the past ( also with a Nexus) ?
Hi,
(1) No, it varies greatly depending on the y and z axis of the device even when the x axis is unchanged.
(2) Terrible. Difficult to quantify but bad enough to render it useless :-{ Just relying on the basic alpha value is much better.
(3) For testing I'm updating on every orientation change event - they come in pretty fast when the device is in motion
In my working code I only update if the change is more than one degree (and also smooth the last 5 results)
(4) Yes. I think that was about the smoothing mentioned above (which works OK)