Geolocation API

The HTML Geolocation API is used to get the geographical position of a user. (if they approves)

The getCurrentPosition() method is used to return the user's position. It can be accessed from the navigator object

Example

The example below returns the latitude and longitude of the user's position:

const myElement = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);

    } else {
        myElement.innerHTML = "Geolocation is not supported by this browser.";
    }
}
getLocation();

//show position in HTML
function showPosition(position) {

    myElement.innerHTML = `Latitude: ${position.coords.latitude} 
        
Longitude: ${position.coords.longitude}`; }

Example explained:

  1. Check if Geolocation is supported
  2. If supported, run the getCurrentPosition() method. If not, display a message to the user
  3. If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)
  4. The showPosition() function outputs the Latitude and Longitude

The example above is a very basic Geolocation script, with no error handling. Other examples in W3Schools