Skip to content

How to use the Geolocation API

New Course Coming Soon:

Get Really Good at Git

Using the Geolocation API we can ask the browser for the user's position coordinates

The browser exposes a navigator.geolocation object, through which we’ll do all the geolocation operations.

It’s only available on pages served using HTTPS, for security purposes, and it’s available on all modern browsers.

navigator.geolocation

The geolocation object

Since window is the global object, we can access navigator without specifying window.navigator

The window.navigator property exposed by browsers points to a Navigator object which is a container object that makes a lot of Web Platform APIs available to us.

The geolocation object provides the following methods:

The first one is used to get the current position coordinates. When we call this method for the first time, the browser automatically asks the user for the permission to share this information to us.

This is how this interface looks in Chrome:

The permission screen in Chrome

on Firefox:

The permission screen in Firefox

and on Safari:

The permission screen in Safari

This needs to be done only once per origin. You can change the decision you made, and revert a permission decision. This is how you do so with Chrome, by clicking the lock icon near the domain:

Permission details

Once this permission is granted, we can proceed.

Getting the user’s position

Let’s start with this sample code:

navigator.geolocation.getCurrentPosition(() => {})

The permission panel should appear. Allow the permission.

Notice how I passed an empty arrow function, because the function wants a callback function.

This function is passed a Position object, which contains the actual location:

navigator.geolocation.getCurrentPosition((position) => {
  console.log(position)
})

This object has 2 properties:

The Coordinates object comes with several properties that define the location:

Depending on the implementation and the device, some of those will be null. For example on Chrome running on my MacBook Air I only got values for accuracy, latitude and longitude.

navigator.geolocation.getCurrentPosition((position) => {
  console.log(position.coords.latitude)
  console.log(position.coords.longitude)
})

Watching the position for changes

In addition to getting the user position once, which you can do using getCurrentPosition(), you can use the watchPosition() method of navigator.geolocation to register a callback function that will be called upon each and every change that the device will communicate to us.

Usage:

navigator.geolocation.watchPosition((position) => {
  console.log(position)
})

Of course the browser will ask for the permission also with this method, if it was not already granted.

We can stop watching for a position by calling the navigator.geolocation.clearWatch() method, passing it the id returned by watchPosition():

const id = navigator.geolocation.watchPosition((position) => {
  console.log(position)
})

//stop watching after 10 seconds
setTimeout(() => {
  navigator.geolocation.clearWatch(id)
}, 10 * 1000)

If the user denies the permission

Remember the permission popup window the browser shows when we call one of the methods to get the position?

If the user denies that, we can intercept this scenario by adding an error handling function, as the second parameter to the methods getCurrentPosition() and watchPosition().

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position)
  },
  (error) => {
    console.error(error)
  },
)

The object passed to the second parameter contains a code property to distinguish between error types:

Adding more options

When I talked about errors previously, I mentioned the timeout error. Looking up the position can take some time and we can set a maximum time allowed to perform the operation, as an option.

You can add a timeout by adding a third parameter to the methods getCurrentPosition() and watchPosition(), an object.

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position)
  },
  (error) => {
    console.error(error)
  },
  {},
)

Inside this object we can pass the properties

Example usage:

navigator.geolocation.getCurrentPosition(
  (position) => {
    console.log(position)
  },
  (error) => {
    console.error(error)
  },
  {
    timeout: 1000,
    maximumAge: 10000,
    enableHighAccuracy: true,
  },
)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my DOM Tutorial on The Valley of Code
→ Read my Browser Events Tutorial on The Valley of Code
→ Read my Browser APIs Tutorials on The Valley of Code

Here is how can I help you: