Back to JavaScript Notes
Topic #395

Geolocation API

You will learn how to request the user's current location in JavaScript using the Geolocation API, handle permission and errors, and read coordinates safely.

What it is

The Geolocation API is a browser interface that lets a web page ask the user for permission to read their approximate physical location. The main object is navigator.geolocation. A successful request returns a GeolocationPosition object, whose coords property contains values such as latitude, longitude, and accuracy. Related terms include permission prompt, secure context, watch position, and position error.

Why it matters

  • It enables location-aware features such as nearby stores, weather, or map centering.
  • It gives more accurate results than IP-based location when the user agrees.
  • It respects privacy by requiring explicit permission in most browsers.
  • It supports both one-time checks and continuous tracking.

Syntax or steps

The smallest useful pattern is navigator.geolocation.getCurrentPosition(success, error, options). The success callback receives a position object. The error callback receives a GeolocationPositionError. The optional options object can include enableHighAccuracy, timeout, and maximumAge. The page must run in a secure context, usually HTTPS or localhost.

Example

const options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function showPosition(position) {
  const { latitude, longitude, accuracy } = position.coords;
  console.log(`Lat: ${latitude}, Lon: ${longitude}, Accuracy: ${accuracy} m`);
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      console.warn("User denied location permission.");
      break;
    case error.POSITION_UNAVAILABLE:
      console.warn("Location information is unavailable.");
      break;
    case error.TIMEOUT:
      console.warn("Location request timed out.");
      break;
    default:
      console.warn("Unknown error:", error.message);
  }
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(showPosition, showError, options);
} else {
  console.warn("Geolocation is not supported.");
}

The options object asks for high accuracy, stops after five seconds, and avoids cached positions. showPosition reads the coordinates. showError explains common failures. The final block checks support before calling the API.

Common mistakes

  • Assuming permission is granted. Always provide an error callback and handle denial.
  • Testing on HTTP. Use HTTPS or localhost, or the API may be unavailable.
  • Ignoring accuracy. accuracy is in meters; do not treat the coordinates as exact.
  • Tracking forever. If using watchPosition, call clearWatch when tracking is no longer needed.

When to use it

NeedUseWhy
One-time locationgetCurrentPositionSimple and stops after one result.
Live movementwatchPositionReceives updates as the user moves.
No permission or fallbackIP geolocation serviceLess accurate but does not require browser permission.

Practice

Guided exercise: Add a button that calls getCurrentPosition and displays latitude and longitude in the page. Expected output: Lat: 37.7749, Lon: -122.4194.

Challenge: Use watchPosition to log updates, then stop tracking after ten seconds.

Hint: Store the watch ID returned by watchPosition and pass it to clearWatch.

Quick check

What does accuracy mean in position.coords?

It is the radius, in meters, within which the browser believes the user is located.

Summary

The Geolocation API provides browser-based location data only after the user grants permission. Use getCurrentPosition for one-time checks, handle errors carefully, and treat coordinates as approximate.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Geolocation API – FAQs

Quick answers about learning Geolocation API in JavaScript.

This free note from Coding Now Tech Institute explains Geolocation API in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including Geolocation API, is 100% free with no signup required.
With focused practice, most students grasp Geolocation API in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now