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 |
|---|---|---|
|
| An enumerated value |
|
| 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!
}
}Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access