Geolocation: Getting the user's position

The geolocation object provides the following methods:

  • getCurrentPosition()
  • watchPosition()
  • clearWatch()

The first one is used to get the current position coordinates.

Let’s start with this sample code:

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

When we call this method for the first time, the browser automatically asks the user for the permission to share this information to us:

Allow the permission.

Notice how I passed an empty arrow function, because the function requires we pass a callback function.

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

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

This object has 2 properties:

  • coords, a Coordinates object
  • timestamp, the UNIX timestamp when the position was retrieved

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

  • accuracy the accuracy of the position measured, expressed in meters
  • altitude the altitude value measured
  • altitudeAccuracy the accuracy of the altitude measured, expressed in meters
  • heading the direction towards which the device is traveling. Expressed in degrees (0 = North, East = 90, South = 180, West = 270)
  • latitude the latitude value measured
  • longitude the longitude value measured
  • speed the speed at which the device is traveling, expressed in meters per second

Depending on the implementation and the device, some of those will be null.

For example on Chrome running on my MacBook Pro I only got values for accuracy, latitude and longitude.

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

Lessons in this unit:

0: Introduction
1: ▶︎ Getting the user's position
2: Watching the position for changes
3: If the user denies the position
4: Adding more options
Want to learn more? Check out our courses