Handling Errors

Geolocation is complicated. So many things can go wrong. I’ve mentioned the “user consent” angle already. If your web application wants the user’s location but the user doesn’t want to give it to you, you’re screwed. The user always wins. But what does that look like in code? It looks like the second argument to the getCurrentPosition() function—an error handling callback function:

navigator.geolocation.getCurrentPosition(
  show_map, handle_error)

If anything goes wrong, your error callback function will be called with a PositionError object. It has the properties listed in Table 6-3.

Table 6-3. Properties of the PositionError object

Property

Type

Notes

code

short

An enumerated value

message

DOMString

Not intended for end users

The code property will be one of the following:

  • PERMISSION_DENIED (1) if the user clicks the “Don’t Share” button or otherwise denies you access to his location.

  • POSITION_UNAVAILABLE (2) if the network is down or the positioning satellites can’t be contacted.

  • TIMEOUT (3) if the network is up but it takes too long to calculate the user’s position. How long is “too long”? I’ll show you how to define that in the next section.

  • UNKNOWN_ERROR (0) if anything else goes wrong.

For example:

function handle_error(err) {
  if (err.code == 1) {
    // user said no!
  }
}

Get HTML5: Up and Running now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.