Breaking News

HTML GEOLOCATION API | HTML LOCATION API

The HTML Geolocation API is a browser API that allows a website to request the user's current geographic location (latitude and longitude). The user must grant permission before the location is shared.

Basic Syntax

navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
  • successCallback runs if the location is obtained successfully.
  • errorCallback runs if the request fails or is denied.

Example

<!DOCTYPE html>
<html>
<head>
    <title>Geolocation Example</title>
</head>
<body>

<h2>Get Your Current Location</h2>
<button onclick="getLocation()">Get Location</button>

<p id="demo"></p>

<script>
const output = document.getElementById("demo");

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

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

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

</body>
</html>

Geolocation Methods

Method  Description
getCurrentPosition()  Gets the user's current location once.
watchPosition()  Continuously monitors the user's location and calls a callback                  whenever it changes.
clearWatch()     Stops watching the user's location.

Position Object

The position.coords object contains useful information:

PropertyDescription
latitude  Latitude in decimal degrees
longitude  Longitude in decimal degrees
accuracy  Accuracy of the location in meters
altitude  Height above sea level (if available)
heading  Direction of travel (if available)
speed  Speed in meters/second (if available)

Example: Watch Location

<script>
const watchId = navigator.geolocation.watchPosition(position => {
    console.log(position.coords.latitude);
    console.log(position.coords.longitude);
});

// Stop watching later:
// navigator.geolocation.clearWatch(watchId);
</script>

Requirements

  • Most browsers require the page to be served over HTTPS (or http://localhost during development).
  • The user must grant permission to share their location.
  • If permission is denied, the error callback is invoked.

The Geolocation API is commonly used in maps, ride-sharing, food delivery, weather applications, and location-based services.

No comments