How to handle Geolocation errors in HTML5?


HTML5 Geolocation API lets you share your location with your favorite websites. A JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.

Geolocation is complicated, and it is very much required to catch any error and handle it gracefully.

The geolocations methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties −

Property
Type
Description
Code
Number
Contains a numeric code for the error.
message
String
Contains a numeric code for the error.

The following table describes the possible error codes returned in the PositionError object.

Code
Constant
Description
0
UNKNOWN_ERROR
The method failed to retrieve the location of the device due to an unknown error.
1
PERMISSION_DENIED
The method failed to retrieve the location of the device because the application does not have permission to use the Location Service.
2
POSITION_UNAVAILABLE
The location of the device could not be determined.
3
TIMEOUT
The method was unable to retrieve the location information within the specified maximum timeout interval.

Here’s how you can make use of the PositionError object. The errorHandler method is a callback method −

Updated on: 16-Jun-2020

743 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements