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 |