Categories: softare development

Geolocation API

The HTML Geolocation API is used to locate a user’s geographical position. For this to work accurately and not compromise privacy, the user would have to give consent and approval.

The Geolocation API is supported by major browsers including Chrome, Safari, Mozilla Firefox, Edge and Opera.

Fast Track Your Mobile App Development Process

How to Use the Geolocation API

The geolocation is made available through the navigator.geolocation object. This means it has properties that could be called to get certain information.

When using the Geolocation API, the first thing we want to do is to check if it is supported by the user’s browser. If it is, then we can proceed. If not, we return a message to the user.

if ('geolocation' in navigator) {
  /* geolocation is available */} else {
  /* geolocation IS NOT available */}

Getting the Current Position

The getCurrentPosition returns the user’s current position.

This initiates an asynchronous request to detect the user’s position, and queries the positioning hardware to get up-to-date information. After the position is determined, the defined callback function is executed.

You can optionally provide a second callback function to be executed if an error occurs and also a third optional parameter where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

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

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

Error Handling

The getCurrentPosition() method takes in a second parameter that handles error. This error function is expected to run if the application fails to get the user’s position.

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

We can then add this parameter to our function.

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

Watching the Current Position

The watchPosition() is used to actively listen for a change in position. This works best with a GPS or a smartphone so that the change in position or the movement can be monitored.

<script>
var x = document.getElementById("demo");
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition);
  } else {
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}
function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude; 
}
</script>

The getCurrentPosition() Method Properties

The getCurrentPosition() method also returns other properties that are worthy of note.

PropertyResult
coords.latitudeThe latitude as a decimal number (always returned)
coords.longitudeThe longitude as a decimal number (always returned)
coords.accuracyThe accuracy of position (always returned)
coords.altitudeThe altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracyThe altitude accuracy of position (returned if available)
coords.headingThe heading as degrees clockwise from North (returned if available)
coords.speedThe speed in meters per second (returned if available)
timestampThe date/time of the response (returned if available)

Recent Posts

Service Workers in JavaScript: An In-Depth Guide

Service Workers are one of the core features of modern web applications, offering powerful capabilities…

1 week ago

What are Database Driven Websites?

A database-driven website is a dynamic site that utilizes a database to store and manage…

2 weeks ago

How to show Toast Messages in React

Toasts are user interface elements commonly used in software applications, especially in mobile app development…

2 weeks ago

Exploring the Relationship Between JavaScript and Node.js

JavaScript has long been synonymous with frontend web development, powering interactive and dynamic user interfaces…

3 weeks ago

Key Differences Between Tailwind CSS and CSS3

Introduction: In the world of web development, CSS (Cascading Style Sheets) plays a crucial role…

4 weeks ago

Why Everybody is Learning JavaScript Right Now

JavaScript has emerged as a ubiquitous programming language, powering the modern web and extending its…

4 weeks ago