HTML Navigator geolocation Property

The navigator.geolocation property in HTML provides access to the Geolocation API, which allows web applications to retrieve the user's current location. This property returns a Geolocation object that contains methods to get the user's position coordinates, track location changes, and handle location-related errors.

The geolocation functionality requires user permission and works best with HTTPS connections. Modern browsers will prompt users to allow or deny location access when a website requests it.

Syntax

Following is the syntax for accessing the navigator geolocation property −

navigator.geolocation

The geolocation object provides three main methods −

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)
navigator.geolocation.watchPosition(successCallback, errorCallback, options)
navigator.geolocation.clearWatch(watchId)

Parameters

The getCurrentPosition() and watchPosition() methods accept the following parameters −

  • successCallback − A function that executes when location is successfully retrieved. Receives a position object as parameter.

  • errorCallback (optional) − A function that executes when an error occurs during location retrieval.

  • options (optional) − An object specifying location retrieval options like enableHighAccuracy, timeout, and maximumAge.

Basic Geolocation Example

Following example demonstrates how to get the user's current position using the geolocation property −

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

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

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

The output displays the user's latitude and longitude coordinates after permission is granted −

Latitude: 40.7128
Longitude: -74.0060

Enhanced Geolocation with Error Handling

Following example includes error handling and additional position information −

<!DOCTYPE html>
<html>
<head>
   <title>Enhanced Geolocation Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; background-color: #f5f5f5;">
   <h2>Enhanced Location Information</h2>
   <button onclick="getLocationInfo()" style="background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer;">Get Detailed Location</button>
   <div id="location-info" style="margin-top: 20px; padding: 15px; background: white; border-radius: 8px;"></div>

   <script>
      function getLocationInfo() {
         if (!navigator.geolocation) {
            document.getElementById("location-info").innerHTML = "<p style='color: red;'>Geolocation is not supported by this browser.</p>";
            return;
         }

         document.getElementById("location-info").innerHTML = "<p>Getting your location...</p>";
         
         navigator.geolocation.getCurrentPosition(showDetailedPosition, showError);
      }

      function showDetailedPosition(position) {
         const coords = position.coords;
         document.getElementById("location-info").innerHTML = 
            "<h3>Your Location Details:</h3>" +
            "<p><strong>Latitude:</strong> " + coords.latitude + "</p>" +
            "<p><strong>Longitude:</strong> " + coords.longitude + "</p>" +
            "<p><strong>Accuracy:</strong> " + coords.accuracy + " meters</p>" +
            "<p><strong>Timestamp:</strong> " + new Date(position.timestamp) + "</p>";
      }

      function showError(error) {
         let 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("location-info").innerHTML = "<p style='color: red;'>" + errorMsg + "</p>";
      }
   </script>
</body>
</html>

This example provides comprehensive location information and handles various error scenarios that may occur during location retrieval.

Watching Position Changes

The watchPosition() method continuously monitors the user's location and triggers a callback whenever the position changes −

<!DOCTYPE html>
<html>
<head>
   <title>Watch Position Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Track Location Changes</h2>
   <button onclick="startTracking()">Start Tracking</button>
   <button onclick="stopTracking()">Stop Tracking</button>
   <div id="tracking-info" style="margin-top: 15px; padding: 10px; background: #f8f9fa; border-radius: 5px;"></div>

   <script>
      let watchId = null;

      function startTracking() {
         if (!navigator.geolocation) {
            document.getElementById("tracking-info").innerHTML = "Geolocation not supported.";
            return;
         }

         watchId = navigator.geolocation.watchPosition(
            function(position) {
               document.getElementById("tracking-info").innerHTML = 
                  "<h4>Current Position:</h4>" +
                  "<p>Lat: " + position.coords.latitude.toFixed(6) + "</p>" +
                  "<p>Lng: " + position.coords.longitude.toFixed(6) + "</p>" +
                  "<p>Time: " + new Date().toLocaleTimeString() + "</p>";
            },
            function(error) {
               document.getElementById("tracking-info").innerHTML = "Error: " + error.message;
            }
         );
      }

      function stopTracking() {
         if (watchId !== null) {
            navigator.geolocation.clearWatch(watchId);
            watchId = null;
            document.getElementById("tracking-info").innerHTML += "<p style='color: blue;'>Tracking stopped.</p>";
         }
      }
   </script>
</body>
</html>

This example allows users to start and stop location tracking, which is useful for applications that need to monitor movement or position changes.

Geolocation Options

The geolocation methods accept an options object to customize location retrieval behavior −

const options = {
   enableHighAccuracy: true,  // Request high accuracy positioning
   timeout: 10000,           // Maximum time to wait (milliseconds)
   maximumAge: 60000         // Maximum age of cached position (milliseconds)
};

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
Geolocation API Flow User Requests Location Browser Prompts for Permission Permission Granted Permission Denied Location Data Retrieved

Browser Compatibility and Security

The Geolocation API has the following considerations −

  • HTTPS Requirement − Most modern browsers require HTTPS connections for geolocation requests due to security policies.

  • User Permission − Users must explicitly grant permission before location data can be accessed.

  • Privacy − Browsers may cache location data temporarily but respect user privacy settings.

  • Accuracy − Location accuracy depends on available positioning methods (GPS, WiFi, cellular towers).

Common Use Cases

The navigator geolocation property is commonly used for −

  • Maps and Navigation − Showing user location on maps and providing directions.

  • Location-based Services − Finding nearby restaurants, stores, or services.

  • Weather Applications − Providing local weather information based on user location.

  • Fitness Tracking − Recording routes and distances for running or cycling apps.

Conclusion

The navigator geolocation property provides a powerful way to access user location data through the browser's Geolocation API. It requires user permission and works best with proper error handling and HTTPS connections. This API enables location-aware web applications that can provide personalized, location-based services to users.

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

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements