How to locate the user\'s position in HTML?

The HTML Geolocation API allows web applications to access the user's current geographic location through JavaScript. This feature enables websites to provide location-based services like displaying coordinates, showing maps, or finding nearby places. The user must grant permission before the browser can access their location data.

HTML Geolocation API

The Geolocation API is accessed through the navigator.geolocation object, which provides methods to retrieve the user's current position. The API works with GPS, WiFi networks, cellular towers, and IP addresses to determine location coordinates.

Syntax

Following is the basic syntax for getting the user's current location

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

The getCurrentPosition() method takes three parameters

  • successCallback Function called when location is successfully retrieved
  • errorCallback Function called when an error occurs (optional)
  • options Configuration object for timeout, accuracy, etc. (optional)

Checking Browser Support

Before using geolocation, always check if the browser supports it

if (navigator.geolocation) {
    // Geolocation is supported
    navigator.geolocation.getCurrentPosition(successFunction);
} else {
    // Geolocation is not supported
    alert("Geolocation is not supported by this browser.");
}

Basic Location Display Example

Following example shows how to retrieve and display the user's location coordinates

<!DOCTYPE html>
<html>
<head>
    <title>Get User Location</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>Find My Location</h2>
    <button onclick="getLocation()">Get My Coordinates</button>
    <p id="location-display"></p>
    
    <script>
        function getLocation() {
            const locationDisplay = document.getElementById("location-display");
            
            if (navigator.geolocation) {
                locationDisplay.innerHTML = "Locating...";
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            } else {
                locationDisplay.innerHTML = "Geolocation is not supported by this browser.";
            }
        }
        
        function showPosition(position) {
            const lat = position.coords.latitude;
            const lon = position.coords.longitude;
            const accuracy = position.coords.accuracy;
            
            document.getElementById("location-display").innerHTML = 
                "Latitude: " + lat.toFixed(6) + "<br>" +
                "Longitude: " + lon.toFixed(6) + "<br>" +
                "Accuracy: " + accuracy + " meters";
        }
        
        function showError(error) {
            const locationDisplay = document.getElementById("location-display");
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    locationDisplay.innerHTML = "User denied the request for geolocation.";
                    break;
                case error.POSITION_UNAVAILABLE:
                    locationDisplay.innerHTML = "Location information is unavailable.";
                    break;
                case error.TIMEOUT:
                    locationDisplay.innerHTML = "The request to get user location timed out.";
                    break;
                default:
                    locationDisplay.innerHTML = "An unknown error occurred.";
                    break;
            }
        }
    </script>
</body>
</html>

When the user clicks the button and grants permission, their coordinates are displayed with accuracy information

Find My Location
[Get My Coordinates]

Latitude: 40.712776
Longitude: -74.005974
Accuracy: 20 meters

Displaying Location on a Map

Following example shows how to display the user's location on an interactive map using the Leaflet library

<!DOCTYPE html>
<html>
<head>
    <title>Location on Map</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <style>
        body { font-family: Arial, sans-serif; margin: 0; padding: 20px; }
        #map { height: 400px; width: 100%; margin-top: 20px; border: 2px solid #ccc; }
        .controls { margin-bottom: 15px; }
        button { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background-color: #0056b3; }
    </style>
</head>
<body>
    <h2>My Location on Map</h2>
    <div class="controls">
        <button onclick="findAndShowLocation()">Show My Location</button>
        <p id="coordinates"></p>
    </div>
    <div id="map"></div>
    
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <script>
        let map;
        let marker;
        
        // Initialize map
        function initMap() {
            map = L.map('map').setView([40.7128, -74.0060], 10);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap contributors'
            }).addTo(map);
        }
        
        function findAndShowLocation() {
            const coordsDisplay = document.getElementById("coordinates");
            
            if (navigator.geolocation) {
                coordsDisplay.innerHTML = "Getting your location...";
                navigator.geolocation.getCurrentPosition(displayOnMap, handleLocationError);
            } else {
                coordsDisplay.innerHTML = "Geolocation not supported by this browser.";
            }
        }
        
        function displayOnMap(position) {
            const lat = position.coords.latitude;
            const lon = position.coords.longitude;
            
            // Update coordinates display
            document.getElementById("coordinates").innerHTML = 
                `Location: ${lat.toFixed(6)}, ${lon.toFixed(6)}`;
            
            // Center map on user location
            map.setView([lat, lon], 15);
            
            // Remove previous marker if exists
            if (marker) {
                map.removeLayer(marker);
            }
            
            // Add new marker
            marker = L.marker([lat, lon]).addTo(map)
                .bindPopup('You are here!')
                .openPopup();
        }
        
        function handleLocationError(error) {
            document.getElementById("coordinates").innerHTML = 
                "Error getting location: " + error.message;
        }
        
        // Initialize map when page loads
        window.onload = function() {
            initMap();
        };
    </script>
</body>
</html>

This example creates an interactive map that centers on the user's location and places a marker to indicate their position.

Location Options and Configuration

The geolocation API accepts an options object to configure the location request

const options = {
    enableHighAccuracy: true,  // Use GPS if available
    timeout: 10000,           // Wait max 10 seconds
    maximumAge: 300000        // Cache location for 5 minutes
};

navigator.geolocation.getCurrentPosition(success, error, options);

Example with Options

<!DOCTYPE html>
<html>
<head>
    <title>Precise Location with Options</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
    <h2>High-Accuracy Location</h2>
    <button onclick="getPreciseLocation()">Get Precise Location</button>
    <p id="precise-location"></p>
    
    <script>
        function getPreciseLocation() {
            const display = document.getElementById("precise-location");
            
            const options = {
                enableHighAccuracy: true,
                timeout: 15000,
                maximumAge: 0
            };
            
            if (navigator.geolocation) {
                display.innerHTML = "Getting high-accuracy location...";
                navigator.geolocation.getCurrentPosition(showPrecisePosition, showLocationError, options);
            } else {
                display.innerHTML = "Geolocation not supported.";
            }
        }
        
        function showPrecisePosition(position) {
            const lat = position.coords.latitude;
            const lon = position.coords.longitude;
            const accuracy = position.coords.accuracy;
            const timestamp = new Date(position.timestamp);
            
            document.getElementById("precise-location").innerHTML = 
                "Latitude: " + lat.toFixed(8) + "<br>" +
                "Longitude: " + lon.toFixed(8) + "<br>" +
                "Accuracy: " + accuracy + " meters<br>" +
                "Time: " + timestamp.toLocaleString();
        }
        
        function showLocationError(error) {
            let message = "Error: ";
            switch(error.code) {
                case 1: message += "Permission denied"; break;
                case 2: message += "Position unavailable"; break;
                case 3: message += "Request timeout"; break;
                default: message += "Unknown error"; break;
            }
            document.getElementById("precise-location").innerHTML = message;
        }
    </script>
</body>
</html>

Geolocation Position Object Properties

The position object returned by the geolocation API contains the following properties

Property Description
coords.latitude Latitude in decimal degrees
coords.longitude Longitude in decimal degrees
coords.accuracy Accuracy of position in meters
coords.altitude Height in meters above sea level (may be null)
coords.altitudeAccuracy Accuracy of altitude in meters (may be null)
coords.heading Direction in degrees from north (may be null)
coords.speed Speed in meters per second (may be null)
timestamp Time when position was acquired
Geolocation API Workflow User clicks "Get Location" button Browser requests user permission Permission granted: Get coordinates & display result
Updated on: 2026-03-16T21:38:54+05:30

472 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements