I like to create a website which feature should be to read your current heading.
-
Hi, jonas! I've edited your answer to show the screenshot directly and to make it a bit tidier in general. Please do check that I haven't accidentally changed the meaning of your question in any way, and feel free to undo my edits and/or edit your question further if there's anything you feel needs fixing. Thanks, and welcome to Stack Overflow! – Ilmari Karonen Sep 04 '17 at 13:54
1 Answers
I'm assuming that you already know how to use the JavaScript geolocation API and how to render a rotating arrow in JavaScript, and just need help with calculating the angle by which the arrow should be rotated. This angle is simply the difference between the azimuth angle of the target point from your location and the compass heading of the device.
To approximately calculate the azimuth of the target, you can use the following formula (adapted from the Wikipedia article linked above):
var dx = Math.sin(lon2 - lon1);
var dy = Math.cos(lat1)*Math.tan(lat2) - Math.sin(lat1)*Math.cos(lon2 - lon1);
var azimuth = Math.atan2(dx, dy); // north = 0, increases clockwise
where lat1
and lon1
are our current latitude and longitude and lat2
and lon2
are the latitude and longitude of the target, and azimuth
is the azimuth angle of the target as seen from our current position, measured clockwise from due north.
(This formula is only approximate, since it assumes that the Earth is a sphere, but the error this introduces should be negligible compared to other sources of error such as inaccurate location and device orientation readings. If you really want to eliminate even this minor error, though, you can calculate the azimuth on the WGS84 spheroid using the more complicated formula also given in the Wikipedia article.)
Note that all the inputs to the formula above need to be given in radians, since that's what the JavaScript trigonometric functions expect. Normally, latitudes and longitudes are given in degrees, so you'll need to first convert them into radians by multiplying them with Math.PI / 180
. The result of the calculation above is also in radians; to convert it into degrees, you'll need to multiply the azimuth
value with 180 / Math.PI
.
Once you know the azimuth angle of the target and the compass heading of the device, you can simply subtract the latter from the former to get the angle by which you need to rotate the arrow to make it point at the target.

- 49,047
- 9
- 93
- 153
-
How is it "not working"? And can you post a snippet / fiddle demonstrating the problem? – Ilmari Karonen Sep 05 '17 at 17:31