geolocation
coordinates
user location
GPS tracking
location services

Get User's Current Location / Coordinates

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The usual way to get a user's current coordinates in a web application is the browser Geolocation API. It can provide latitude and longitude from GPS, Wi-Fi, cellular data, or other device signals, but only after the user grants permission.

The Basic Browser API

Modern browsers expose location through navigator.geolocation. The simplest method is getCurrentPosition, which requests one position reading and then calls either a success or error callback.

html
1<!DOCTYPE html>
2<html>
3  <body>
4    <button id="locate">Get location</button>
5    <pre id="output"></pre>
6
7    <script>
8      const output = document.getElementById("output");
9
10      document.getElementById("locate").addEventListener("click", () => {
11        if (!("geolocation" in navigator)) {
12          output.textContent = "Geolocation is not supported in this browser.";
13          return;
14        }
15
16        navigator.geolocation.getCurrentPosition(
17          (position) => {
18            const coords = position.coords;
19            output.textContent =
20              `Latitude: ${coords.latitude}\n` +
21              `Longitude: ${coords.longitude}\n` +
22              `Accuracy: ${coords.accuracy} meters`;
23          },
24          (error) => {
25            output.textContent = `Location error: ${error.message}`;
26          },
27          {
28            enableHighAccuracy: true,
29            timeout: 10000,
30            maximumAge: 0,
31          }
32        );
33      });
34    </script>
35  </body>
36</html>

The returned coordinates live under position.coords.latitude and position.coords.longitude. The accuracy field is also important because location precision varies a lot by device and environment.

Permission and HTTPS Requirements

This API is intentionally restricted. Browsers require user consent, and geolocation is generally available only in secure contexts such as https:// or http://localhost during development.

That means location access can fail even when the code is correct. Common reasons include:

  • the user denied the permission prompt
  • the site is running on plain HTTP
  • the device itself has location services disabled

Your code should treat location as optional rather than guaranteed.

Watching Position Changes

If your app tracks movement over time, use watchPosition instead of repeatedly calling getCurrentPosition.

javascript
1const watchId = navigator.geolocation.watchPosition(
2  (position) => {
3    console.log(position.coords.latitude, position.coords.longitude);
4  },
5  (error) => {
6    console.error(error.message);
7  },
8  { enableHighAccuracy: true }
9);
10
11// Later, when tracking should stop:
12navigator.geolocation.clearWatch(watchId);

This is useful for navigation, delivery tracking, fitness apps, or any interface that needs updates as the device moves.

Accuracy Depends on Context

Many developers assume location always means exact GPS coordinates. In practice, the browser may use several sources and return an approximate result. Indoors, on desktops, or on devices with disabled GPS, the reported position can be coarse and sometimes noticeably wrong.

That is why the accuracy value should be taken seriously. For some applications, a 20-meter radius is fine. For others, such as turn-by-turn navigation, it may not be enough.

Fallback Strategies

If geolocation is unavailable or denied, a common fallback is IP-based lookup on the server side. That can estimate city-level location, but it is much less precise than device location and should not be presented as exact coordinates.

For privacy-sensitive applications, it is often better to let the user type a city, postal code, or address rather than trying to infer location when permission is unavailable.

Common Pitfalls

The first pitfall is testing on plain HTTP and wondering why the API fails. Use HTTPS or localhost during development.

Another common mistake is calling the API without user-facing explanation. Users are more likely to deny access when the permission prompt appears with no context.

Do not assume the coordinates are exact. GPS can drift, network-based positioning can be approximate, and some users intentionally disable precise location.

Finally, remember that location data is sensitive personal data. Request it only when there is a clear product reason and store it only if your application genuinely needs it.

Summary

  • Use navigator.geolocation.getCurrentPosition() to fetch one current reading in the browser.
  • Expect a permission prompt and require a secure context such as HTTPS.
  • Read latitude and longitude from position.coords.
  • Use watchPosition() only when you need continuous updates.
  • Treat location as approximate, permission-based, and privacy-sensitive.

Course illustration
Course illustration

All Rights Reserved.