Skip to main content

HTML Geolocation API

By SamK
0
0 recommends
Topic(s)

The HTML Geolocation API is employed to retrieve the geographical position of a user. However, to respect privacy concerns, the position remains inaccessible unless explicitly approved by the user.

Geolocation is most precise on devices equipped with GPS, such as smartphones.

Starting with Chrome 50, the Geolocation API only works on secure contexts like HTTPS. If your site is hosted on an insecure origin (such as HTTP), requests to access the user's location will no longer function.

Using HTML Geolocation

The getCurrentPosition() method is utilized to fetch the user's position. The following example illustrates how it returns the latitude and longitude coordinates:

<div id="location"></div>
<button onclick="getLocation()" >Get Location</button>

<script>
const loc = document.getElementById("location");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showLocation);
  } else {
    loc.innerHTML = "Geolocation not supported by the browser.";
  }
}

function showLocation(position) {
  loc.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
</script>
Using HTML Geo location Demo

Explanation:

First we are checking if Geolocation is supported in if (navigator.geolocation).

If supported, we are executing the getCurrentPosition() method; if not, we are displaying a message to the user that it is not supported.

If getCurrentPosition() is successful in the above step, it passes a coordinates object to the specified function (showLocation).

The showLocation() function then displays the Latitude and Longitude.

The example above is a simple Geolocation script without error handling.

Handling Errors and Rejections

This version includes error handling using the errorHandling() function to handle potential errors that might occur during the geolocation process.

The second parameter of the getCurrentPosition() method is an error handler function. It defines the function to execute if retrieving the user's location fails.

<div id="location"></div>
<button onclick="getLocation()" >Get Location</button>

<script>
const loc = document.getElementById("location");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showLocation, errorHandling);
  } else {
    loc.innerHTML = "Geolocation not supported by the browser.";
  }
}

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

function errorHandling(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      loc.innerHTML = "Geolocation request denied."
      break;
    case error.POSITION_UNAVAILABLE:
      loc.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      loc.innerHTML = "Geolocation request timed out."
      break;
    case error.UNKNOWN_ERROR:
      loc.innerHTML = "An unknown error occurred."
      break;
  }
}
</script>

In case of the above example, the user will see a message shown in the below image, if the geolocation request is denied.

Handling Errors and Rejections Demo

Location-specific Information

Geo location is also highly useful for providing location-specific information, such as:

  • Current local information
  • Displaying points of interest near the user
  • Providing turn-by-turn navigation (GPS)

The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object upon success. This object always includes the latitude, longitude, and accuracy properties. Other properties are included if available.

coords.latitude - The latitude as a decimal number (always returned).
coords.longitude - The longitude as a decimal number (always returned).
coords.accuracy - The accuracy of the position (always returned).
coords.altitude - The altitude in meters above mean sea level (returned if available).
coords.altitudeAccuracy - The altitude accuracy of the position (returned if available).
coords.heading - The heading in degrees clockwise from North (returned if available).
coords.speed - The speed in meters per second (returned if available).
timestamp - The date and time of the response (returned if available).

Geolocation Object - Current User Position

The Geolocation object also includes other useful methods:

  • watch Position() - Retrieves the user's current position and continues to provide updated positions as the user moves (similar to the GPS in a car).
  • clear Watch() - Stops the watch Position() method.

The example below demonstrates the watch Position() method. To test this, you will need an accurate GPS device, such as a smartphone:

<div id="location"></div>
<button onclick="getLocation()" >Get Location</button>

<script>
const loc = document.getElementById("location");

function getLocation() {
 if (navigator.geolocation) {
   navigator.geolocation.watchPosition(showLocation);
 } else {
   loc.innerHTML = "Geolocation not supported by the browser.";
 }
}

function showLocation(position) {
 loc.innerHTML = "Latitude: " + position.coords.latitude +
 "<br>Longitude: " + position.coords.longitude;
}
</script> 

Questions & Answers