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!
}
}
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.