Geolocation: Watching the position for changes

In addition to getting the user position once, which you can do using getCurrentPosition(), you can use the watchPosition() method of navigator.geolocation to register a callback function that will be called upon each and every change that the device will communicate to us.

Usage:

navigator.geolocation.watchPosition(position => {
  console.log(position)
})

The browser will ask for the permission also with this method, if it was not already granted.

We can stop watching for a position by calling the navigator.geolocation.clearWatch() method, passing it the id returned by watchPosition():

const id = navigator.geolocation.watchPosition(position => {
  console.log(position)
})

//stop watching after 10 seconds
setTimeout(() => {
  navigator.geolocation.clearWatch(id)
}, 10 * 1000)

Lessons in this unit:

0: Introduction
1: Getting the user's position
2: ▶︎ Watching the position for changes
3: If the user denies the position
4: Adding more options
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!