HTML5 Geolocation without SSL connection

HTML5 Geolocation allows web applications to access the user's location information through the browser's built-in geolocation API. While modern browsers typically require HTTPS for geolocation access, there are alternative approaches for non-SSL environments such as using IP-based location services or fallback methods.

Browser Geolocation API

The HTML5 Geolocation API provides access to the user's location through the navigator.geolocation object. This API requires user permission and works best over HTTPS connections.

Syntax

Following is the basic syntax for the geolocation API −

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

Example − Basic Geolocation

<!DOCTYPE html>
<html>
<head>
   <title>HTML5 Geolocation</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>HTML5 Geolocation Example</h2>
   <button onclick="getLocation()">Get Location</button>
   <p id="result"></p>

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

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

      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;
            default:
               errorMsg = "An unknown error occurred.";
               break;
         }
         document.getElementById("result").innerHTML = errorMsg;
      }
   </script>
</body>
</html>

Geolocation Options

The geolocation API accepts an options object with the following parameters −

  • enableHighAccuracy − Boolean value that indicates the application would like to receive the most accurate results possible (default: false)

  • timeout − Maximum time in milliseconds the device is allowed to take to return a position (default: Infinity)

  • maximumAge − Maximum age in milliseconds of a possible cached position (default: 0)

Fallback Method for Non-SSL Environments

When HTTPS is not available, you can use IP-based geolocation services as a fallback. These services estimate location based on the user's IP address.

Example − IP-based Geolocation Fallback

<!DOCTYPE html>
<html>
<head>
   <title>Geolocation with Fallback</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Geolocation with IP Fallback</h2>
   <button onclick="getLocationWithFallback()">Get Location</button>
   <p id="location-result"></p>

   <script>
      function getLocationWithFallback() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
               function(position) {
                  displayLocation(position.coords.latitude, position.coords.longitude, "GPS");
               },
               function(error) {
                  console.log("GPS failed, trying IP geolocation");
                  tryIPGeolocation();
               },
               { timeout: 10000, enableHighAccuracy: true }
            );
         } else {
            tryIPGeolocation();
         }
      }

      function tryIPGeolocation() {
         // Using a free IP geolocation service
         fetch('https://ipapi.co/json/')
            .then(response => response.json())
            .then(data => {
               if (data.latitude && data.longitude) {
                  displayLocation(data.latitude, data.longitude, "IP-based");
               } else {
                  document.getElementById("location-result").innerHTML = "Unable to determine location.";
               }
            })
            .catch(error => {
               document.getElementById("location-result").innerHTML = "Error getting location: " + error.message;
            });
      }

      function displayLocation(lat, lng, method) {
         document.getElementById("location-result").innerHTML = 
            "Location found (" + method + ")<br>" +
            "Latitude: " + lat + "<br>" +
            "Longitude: " + lng + "<br>" +
            "<a href='https://maps.google.com?q=" + lat + "," + lng + "' target='_blank'>View on Google Maps</a>";
      }
   </script>
</body>
</html>

Error Handling

The geolocation API provides specific error codes that help handle different failure scenarios −

Error Code Description Handling Strategy
PERMISSION_DENIED (1) User refused to share location Inform user and offer IP-based fallback
POSITION_UNAVAILABLE (2) Cannot determine position Try again or use alternative method
TIMEOUT (3) Request timed out Increase timeout or retry

Example − Comprehensive Error Handling

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

   <script>
      function getCurrentLocation() {
         var statusDiv = document.getElementById("status");
         statusDiv.innerHTML = "Getting location...";
         
         if (!navigator.geolocation) {
            statusDiv.innerHTML = "Geolocation is not supported by this browser.";
            return;
         }

         var options = {
            enableHighAccuracy: true,
            timeout: 15000,
            maximumAge: 300000  // 5 minutes
         };

         navigator.geolocation.getCurrentPosition(
            function(position) {
               statusDiv.innerHTML = 
                  "<strong>Location Success!</strong><br>" +
                  "Latitude: " + position.coords.latitude.toFixed(6) + "<br>" +
                  "Longitude: " + position.coords.longitude.toFixed(6) + "<br>" +
                  "Accuracy: " + Math.round(position.coords.accuracy) + " meters<br>" +
                  "Timestamp: " + new Date(position.timestamp).toLocaleString();
            },
            function(error) {
               var errorMessage = "";
               switch(error.code) {
                  case error.PERMISSION_DENIED:
                     errorMessage = "Location access denied by user. Please allow location access in your browser settings.";
                     break;
                  case error.POSITION_UNAVAILABLE:
                     errorMessage = "Location information unavailable. Please check your GPS or network connection.";
                     break;
                  case error.TIMEOUT:
                     errorMessage = "Location request timed out. Please try again.";
                     break;
                  default:
                     errorMessage = "An unknown error occurred while retrieving location.";
                     break;
               }
               statusDiv.innerHTML = "<span style='color: red;'>Error: " + errorMessage + "</span>";
            },
            options
         );
      }
   </script>
</body>
</html>
HTML5 Geolocation Flow User Clicks Button Check Browser Support GPS Success Show Coordinates GPS Failed Try IP Fallback Show Error Message ? Success Error Failed

Browser Compatibility Considerations

Modern browsers require HTTPS for the geolocation API to function properly. On HTTP connections, browsers may block geolocation requests or show security warnings. Consider the following approaches for non-SSL environments −

  • Development testing − Use localhost which is exempt from HTTPS requirements in most browsers

  • IP geolocation services − Use third-party APIs that provide location based on IP address

  • Manual location entry − Allow users to manually enter their location as a fallback

Conclusion

While HTML5 Geolocation typically requires HTTPS in modern browsers, you can implement fallback methods using IP-based geolocation services for non-SSL environments. Always include comprehensive error handling and inform users about location access requirements. For production

Updated on: 2026-03-16T21:38:53+05:30

888 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements