HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

Web Geolocation API

The Web Geolocation API allows your web application to access the user's physical location (latitude and longitude). This is incredibly useful for providing local services, mapping, or personalizing content based on where the visitor is.


Live Coordinates Finder

Click the button below to detect your current physical location. Note: Your browser will ask for your explicit permission first.

📍 Your Location Found!
Latitude: --
Longitude: --
Accuracy: --

Using getCurrentPosition()

The primary method is getCurrentPosition(). It takes a callback function that runs when the coordinates are successfully retrieved.

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
}

function showPosition(position) {
    let lat = position.coords.latitude;
    let long = position.coords.longitude;
    console.log("Lat: " + lat + ", Long: " + long);
}

Handling Errors

Geolocation is a sensitive feature. It can fail if the user rejects permission, if the signal is weak, or if the device doesn't have a GPS. You can handle these errors using a second callback function.

navigator.geolocation.getCurrentPosition(success, error);

function error(err) {
    switch(err.code) {
        case err.PERMISSION_DENIED:
            alert("User denied the request for Geolocation.");
            break;
        case err.POSITION_UNAVAILABLE:
            alert("Location information is unavailable.");
            break;
    }
}
Safety Note: Geolocation is only available on Secure Contexts (HTTPS). It will generally not work on insecure sites (HTTP), except for localhost during development.

Watching Position

If you need to track a moving user in real-time (like a navigation app), use watchPosition(). It returns a value every time the user's location changes.

// Start watching
let watchId = navigator.geolocation.watchPosition(showPosition);

// Stop watching
navigator.geolocation.clearWatch(watchId);

Geolocation Properties Table

Property Description
coords.latitude The decimal degree latitude
coords.longitude The decimal degree longitude
coords.accuracy Accuracy of the position in meters
coords.speed Speed in meters per second (null if N/A)
timestamp The date/time the location was found

Key Points to Remember

  • The API belongs to the navigator.geolocation object.
  • It requires explicit user permission to function.
  • It only works on HTTPS secured websites.
  • You can get a single position or **watch** for changes over time.
  • Privacy is paramount; never store location data without informing the user.