learn2kode.in

HTML Geolocation API

The Geolocation API allows websites to access the current location of a user (latitude, longitude, accuracy, etc.). It is commonly used in maps, delivery apps, weather apps, and location-based services.

Important

How Geolocation Works

The browser asks the user for permission. If granted, it returns the device’s coordinates.

Basic Syntax

navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

Example: Get User's Current Location

<!DOCTYPE html>
<html>
<body>

<h2>Get User Location</h2>

<button onclick="getLocation()">Get My Location</button>

<p id="output"></p>

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

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

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

</body>
</html>

Watching Location in Real-Time

navigator.geolocation.watchPosition(position => {
    console.log("Latitude: " + position.coords.latitude);
    console.log("Longitude: " + position.coords.longitude);
});

watchPosition() continuously updates location (useful for navigation apps).

Geolocation Properties Table

Coordinates Returned

Property Description
coords.latitude User’s latitude
coords.longitude User’s longitude
coords.accuracy Accuracy in meters
coords.altitude Height above sea level
coords.speed Speed of the device
timestamp Time the location was taken

Error Codes Table

Error Code Meaning
PERMISSION_DENIED User blocked location access
POSITION_UNAVAILABLE Cannot determine location
TIMEOUT Took too long to get location
UNKNOWN_ERROR An unknown error occurred

Practical Example with Google Maps

<!DOCTYPE html>
<html>
<body>

<h2>Show My Location on Google Maps</h2>

<button onclick="showMap()">Open Map</button>

<script>
function showMap() {
    navigator.geolocation.getCurrentPosition(function(position) {
        const url =
        "https://www.google.com/maps?q=" +
        position.coords.latitude + "," +
        position.coords.longitude;

        window.open(url, "_blank");
    });
}
</script>

</body>
</html>

Show My Location on Google Maps