Geolocation: Adding more options

When we talked about errors previously, I mentioned the timeout error. Looking up the position can take some time and we can set a maximum time allowed to perform the operation, as an option.

You can add a timeout by adding a third parameter to the methods getCurrentPosition() and watchPosition(), an object.

navigator.geolocation.getCurrentPosition(position => {
  console.log(position)
}, error => {
	console.error(error)
}, {

})

Inside this object we can pass the properties

  • timeout to set the number of milliseconds before the request errors out
  • maximumAge to set the maximum “age” of the position cached by the browser. We don’t accept one older than the set amount of milliseconds
  • enableHighAccuracy a boolean by default false, requires a position with the highest level of accuracy possible (which might take more time and more power)

Example usage:

navigator.geolocation.getCurrentPosition(position => {
  console.log(position)
}, error => {
	console.error(error)
}, {
  timeout: 1000,
  maximumAge: 10000,
  enableHighAccuracy: true
})

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