In this lesson I am accessing the users' geolocation and displaying their current speed and direction.
First I grab the elements I will be manipulating, 'arrow' and 'speed'.
Next I request to watch the geolocation data (navigator.geolocation.watchPosition((data) => {}). If the user accepts the request, I change 'speed.textContent' to match the speed value provided by the response (speed.textContent = data.coords.speed). For 'arrow' I rotate the image using the 'heading' in the response (arrow.style.transform = `rotate(${data.coords.heading}deg)`).
If the user denies the request, I log an error to the console and alert the user that the application requires geolocation permission to function.
See the Pen
JavaScript30 - 21 - Geolocation by Corey Noble (@CoreyNoble)
on CodePen.