How to handle Geolocation errors in HTML5?

The HTML5 Geolocation API allows websites to access a user's geographical location with their permission. While this API provides powerful location-aware functionality, geolocation requests can fail due to various reasons such as user denial, network issues, or hardware problems. Proper error handling is essential to provide a good user experience when location services are unavailable.

Syntax

The geolocation methods use an error callback function to handle failures −

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
navigator.geolocation.watchPosition(successCallback, errorCallback, options);

The error callback receives a PositionError object containing error details.

PositionError Object

The PositionError object is passed to the error callback function when a geolocation request fails. This object contains information about what went wrong during the location request.

Properties

Property Type Description
code Number Contains a numeric code indicating the type of error that occurred.
message String Contains a human-readable description of the error.

Error Codes

The code property of the PositionError object can have one of four possible values −

Code Constant Description
0 UNKNOWN_ERROR The method failed to retrieve the location due to an unknown error.
1 PERMISSION_DENIED The user denied the request for geolocation access.
2 POSITION_UNAVAILABLE Location information is unavailable due to network or satellite issues.
3 TIMEOUT The request timed out before the location could be retrieved.

Basic Error Handling Example

Following example demonstrates basic error handling with the Geolocation API −

<!DOCTYPE html>
<html>
<head>
   <title>Geolocation Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Geolocation Error Handling</h2>
   <button onclick="getLocation()">Get My Location</button>
   <div id="result" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc;"></div>

   <script>
      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
         } else {
            document.getElementById("result").innerHTML = "Geolocation is not supported by this browser.";
         }
      }

      function showPosition(position) {
         document.getElementById("result").innerHTML = 
            "Latitude: " + position.coords.latitude + 
            "<br>Longitude: " + position.coords.longitude;
      }

      function showError(error) {
         var errorMsg = "";
         switch(error.code) {
            case error.PERMISSION_DENIED:
               errorMsg = "User denied the request for Geolocation.";
               break;
            case error.POSITION_UNAVAILABLE:
               errorMsg = "Location information is unavailable.";
               break;
            case error.TIMEOUT:
               errorMsg = "The request to get user location timed out.";
               break;
            case error.UNKNOWN_ERROR:
               errorMsg = "An unknown error occurred.";
               break;
         }
         document.getElementById("result").innerHTML = "Error: " + errorMsg;
      }
   </script>
</body>
</html>

This example shows different error messages based on the error code. If the user denies permission or location services are unavailable, appropriate error messages are displayed.

Advanced Error Handling with Timeout

You can specify timeout and other options to control the geolocation behavior −

<!DOCTYPE html>
<html>
<head>
   <title>Advanced Geolocation Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Advanced Error Handling</h2>
   <button onclick="getLocationWithTimeout()">Get Location (5s timeout)</button>
   <div id="status" style="margin-top: 20px; padding: 10px; background: #f9f9f9;"></div>

   <script>
      function getLocationWithTimeout() {
         document.getElementById("status").innerHTML = "Requesting location...";
         
         var options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
         };

         navigator.geolocation.getCurrentPosition(
            function(position) {
               document.getElementById("status").innerHTML = 
                  "<span style='color: green;'>Success!</span><br>" +
                  "Latitude: " + position.coords.latitude.toFixed(4) + "<br>" +
                  "Longitude: " + position.coords.longitude.toFixed(4) + "<br>" +
                  "Accuracy: " + position.coords.accuracy + " meters";
            },
            function(error) {
               var errorDetails = {
                  code: error.code,
                  message: error.message,
                  timestamp: new Date().toLocaleTimeString()
               };
               
               var userMessage = "";
               switch(error.code) {
                  case 1:
                     userMessage = "Please enable location access in your browser settings.";
                     break;
                  case 2:
                     userMessage = "Unable to retrieve your location. Check your internet connection.";
                     break;
                  case 3:
                     userMessage = "Location request timed out. Please try again.";
                     break;
                  default:
                     userMessage = "An unexpected error occurred. Please try again.";
               }
               
               document.getElementById("status").innerHTML = 
                  "<span style='color: red;'>Error " + error.code + ": " + userMessage + "</span><br>" +
                  "<small>Technical details: " + error.message + " (at " + errorDetails.timestamp + ")</small>";
            },
            options
         );
      }
   </script>
</body>
</html>

This advanced example provides user-friendly error messages and includes technical details for debugging. The timeout option ensures the request doesn't hang indefinitely.

Error Handling Best Practices

When implementing geolocation error handling, consider these best practices −

  • Always check browser support − Use navigator.geolocation to verify the API is available.

  • Provide fallback options − Allow users to manually enter their location if geolocation fails.

  • Use appropriate timeouts − Set reasonable timeout values to prevent hanging requests.

  • Show user-friendly messages − Translate technical errors into actionable user guidance.

  • Handle HTTPS requirement − Geolocation requires HTTPS in most modern browsers.

Example − Complete Error Handling with Fallback

<!DOCTYPE html>
<html>
<head>
   <title>Complete Geolocation Error Handling</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Location Service with Fallback</h2>
   <button onclick="requestLocation()">Get My Location</button>
   
   <div id="locationResult" style="margin: 20px 0; padding: 15px; border-radius: 5px;"></div>
   
   <div id="fallbackForm" style="display: none; margin-top: 20px;">
      <h3>Manual Location Entry</h3>
      <input type="text" id="cityInput" placeholder="Enter your city" style="padding: 8px; margin-right: 10px;">
      <button onclick="useManualLocation()">Use This Location</button>
   </div>

   <script>
      function requestLocation() {
         var resultDiv = document.getElementById("locationResult");
         resultDiv.innerHTML = "Requesting your location...";
         resultDiv.style.background = "#f0f8ff";
         resultDiv.style.border = "1px solid #0066cc";
         
         if (!navigator.geolocation) {
            showError("Geolocation is not supported by your browser.", true);
            return;
         }

         var options = {
            enableHighAccuracy: false,
            timeout: 10000,
            maximumAge: 300000
         };

         navigator.geolocation.getCurrentPosition(
            function(position) {
               resultDiv.innerHTML = 
                  "<strong style='color: green;'>Location found successfully!</strong><br>" +
                  "Latitude: " + position.coords.latitude.toFixed(6) + "<br>" +
                  "Longitude: " + position.coords.longitude.toFixed(6) + "<br>" +
                  "Accuracy: ± " + Math.round(position.coords.accuracy) + " meters";
               resultDiv.style.background = "#f0fff0";
               resultDiv.style.border = "1px solid #008000";
            },
            function(error) {
               showError(getErrorMessage(error), true);
            },
            options
         );
      }

      function getErrorMessage(error) {
         switch(error.code) {
            case 1:
               return "Location access was denied. Please enable location services and try again.";
            case 2:
               return "Your location could not be determined. Please check your internet connection.";
            case 3:
               return "Location request timed out. Please try again or enter your location manually.";
            default:
               return "An unknown error occurred while getting your location.";
         }
      }

      function showError(message, showFallback) {
         var resultDiv = document.getElementById("locationResult");
         resultDiv.innerHTML = "<strong style='color: red;'>Error: </strong>" + message;
         resultDiv.style.background = "#fff0f0";
         resultDiv.style.border = "1px solid #cc0000";
         
         if (showFallback) {
            document.getElementById("fallbackForm").style.display = "block";
         }
      }

      function useManualLocation() {
         var city = document.getElementById("cityInput").value.trim();
         if (city) {
            var resultDiv = document.getElementById("locationResult");
            resultDiv.innerHTML = "<strong style='color: blue;'>Manual location set: </strong>" + city;
            resultDiv.style.background = "#f0f0ff";
            resultDiv.style.border = "1px solid #0000cc";
            document.getElementById("fallbackForm").style.display = "none";
         }
      }
   </script>
</body>
</html>

This comprehensive example includes fallback functionality for when geolocation fails, allowing users to manually enter their location as an alternative.

Geolocation Error Handling Flow Request Location Check Support Get Position Permission Denied Position Unavailable
Updated on: 2026-03-16T21:38:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements