Geolocation in the browser
This is the 21st project of WesBos's JS30 series. To see the whole 30 part series, click here We make a really simple compass and speedometer with just JavaScript.
Video -
Starter file -
The compass logo is got from an SVG, we'll be applying a transform on it based on the data from the Position
object.
Get the handles to the html elements -
const arrow = document.querySelector('.arrow');
const speed = document.querySelector('.speed-value');
We use watchPosition
to get the data. If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the watchPosition()
function. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional, can be called repeatedly.
navigator.geolocation.watchPosition((data) => {
console.log(data);
}, (err) => {
console.error(err);
});
Manipulating the DOM elements with the position data -
// inside watchPosition
speed.textContent = data.coords.speed;
arrow.style.transform = `rotate(${data.coords.heading}deg)`;
This completes this exercise. The codepen (though I doubt this will work unless you're on a phone/tablet)