Working with the browser's location API

I was working on a React project recently that made use of the Google Maps API. The app allows a user to find various types of places of interest near them such as restaurants, banks etc.

It makes use the HTML5 Geolocation API to find the location of a user. Doing so is surprisingly simple; it's just a single line:


Of course, you'll invariably use more code for error handling, and callbacks.

Here's an example:

if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(this.success, this.failure)
} else {
   warning.textContent = "Geolocation is not supported by your browser. Please try a more modern browser."

This code first checks that the browser supports the geolocation API.

If the test fails, the else code runs and the user is informed that their browser is not supported.

If it succeeds, the user is presented with a prompt requesting permission to send their location information to the website. If the user agrees, the success function (this.success) is run with the user's coordinates. If the user does not agree, or there's another error, the failure function (this.failure) is run.

In the case of the success function, a coordinates object is sent along with the function call. This object contains several properties: latitude, longitude and accuracy, which are always returned if the function is successful. Other properties which may be returned if available include: altitude, altitudeAccuracy, heading, speed and timestamp.

In other words, the location object looks like this:

var coords = {
   latitude: x,
   longitude: x,
   accuracy: x,
   altitude: x,
   altitudeAccuracy: x,
   heading: x,
   speed: x,
   timestamp: x

In my app, I wanted to plot the user's location on a map. The first step was setting the components state using the coords object:

success = (pos) => {

When a user denies permission, or the browser encounters an error, it returns an error object with a code describing the error.

Examples include:

PERMISSION_DENIED - Where the user refused access to their location information

POSITION_UNAVAILABLE - Location information is not available

TIMEOUT - The request timed out

You can access the error using error.code and display different information to the user using an if or switch statement:

if (error.code === "PERMISSION_DENIED") {
   warning.textContent = "Permission was denied to access your location information";
} else if (error.code === "TIMEOUT") {
   warning.textContent = "The request to retrieve your location timed out";

The error object also has a message property that returns human-readable DOM string describing the error.


W3C Geolocation API Specs

MDN - Using Geolocation

MDN - API Position Error