AI Workshop: learn to build apps with AI →
Geolocation: Watching the position for changes

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


In addition to getting the position once with getCurrentPosition(), you can use watchPosition() to register a callback that is called whenever the device reports a new position.

Usage:

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

The browser will prompt for permission with this method too if it was not already granted.

To stop watching, call navigator.geolocation.clearWatch() with 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