The Geolocation API

Learn how to get the location of users with the web Geolocation API.

Overview

The Geolocation API allows webpages to detect the physical location of the user’s device. However, we must prompt the user for permission before accessing their location. The browser will show a permission dialogue, which users can allow or block.

With the user’s permission, a webpage can get the user’s location, display it on a map, or use it in other ways. This is useful for showing nearby points of interest, location-based searches, or tracking a user’s current location.

How it works

The Geolocation API works by detecting the IP address of the user’s device or using GPS/location services on mobile devices or Wi-Fi access points. The browser uses the most accurate method available to determine the physical location.

To use the API, we first need to get user permission. We do this by calling navigator.geolocation.getCurrentPosition() and passing a callback function. The browser will prompt the user to allow or deny location access. After getting the permission, this callback function passes the user’s current position.

Once the user allows access, we can make subsequent calls to navigator.geolocation.watchPosition() to continuously track the user’s location. Both the getCurrentPosition() and watchPosition() methods accept options (a configuration object) as their third parameter. Using the options.timeout property, we can specify how often we want the callback function to be called to provide the location updates.

Demo app

Steps to use this app:

  • Run the below app and open it in another tab.
  • Click on the “Get Location” button and give permission when the browser prompts it.

After getting permission, the app will show the location.

Get hands-on with 1200+ tech skills courses.