What is the Geolocation API?

When building web applications, certain features require the user’s location in the development process.

The Geolocation API enables the users to give web applications access to their location. The user is initially asked for permission before the location can be accessed, due to privacy reasons.

The Geolocation API is accessed through the navigator.geolocation property, which causes the user’s browser to ask them for permission to access their location data.

Methods

The Geolocation API provides two main methods, which are:

  1. getCurrentPosition(): This function returns the current location of the user. It takes two parameters, position and error. The error parameter is optional.
Demo Example

From the example above, we can display the current location of the user.

Other properties we can get from the position object are shown below. The different properties

  1. watchPosition(): This second method returns the updated current user location as the user moves or changes location. It also functions like the getCurrentPosition() method mentioned above.

The clearWatch() method stops the watchPosition() method.

Code

To further understand the API better, we will create a web application to display the user’s current location on a map.

Demo Tutorial

From the example above, we can store the user’s location and then pass it to the map for display.

It is important to note that the Geolocation request can only be fulfilled in a secure context.

Free Resources