Struggling with Device Orientation and Heading Calculation in JavaScript

0
5
Asked By TechieTraveler92 On

I'm really stuck trying to calculate the heading for my web app on iOS. I'm using the webkitCompassHeading to get the direction, but I can't seem to get it right. I know it references magnetic north and rotates clockwise, unlike the e.alpha that goes counterclockwise. I tried using the formula `heading = (360 + e.webkitCompassHeading - rotation) % 360;` but it's not giving me the expected result. My task involves using the user's current location and a target location to calculate the bearing and then adjust the arrow in my app to always point towards the target as the device rotates. I would appreciate any hints or guidance on how to resolve this issue, particularly for iOS.

2 Answers

Answered By MapMaster On

Make sure your `lastRotation` value is correctly updated after every orientation event. If it’s not set appropriately, it can throw off the calculations for subsequent device movements. Consider logging the different stages of your calculations to understand how those values change during operation.

TechieTraveler92 -

Thanks! I’ll add some console logs to track everything better. It’s been a bit confusing with all the rotations and headings involved.

Answered By DevGuru23 On

It looks like you're on the right track, but double-check how you're handling the rotation values. Instead of just subtracting rotation from the compass heading, try adding the rotation like this: `heading = (e.webkitCompassHeading + rotation) % 360;` This may align your arrow direction better. Also, ensure you’re updating the rotation correctly whenever the device orientation changes.

CodeWizard88 -

That makes sense! I’ll give it a shot. Just to clarify, if I'm using `screen.orientation.angle`, should that value be added or subtracted in this formula?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.