JavaScript Navigator geolocation Property

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline

What You’ll Learn

navigator.geolocation returns a Geolocation object — the Geolocation API entry point. Learn permissions, HTTPS rules, getCurrentPosition, watchPosition, five examples, and try-it labs.

01

Kind

Read-only property

02

Returns

Geolocation

03

Baseline

Widely available

04

Context

Secure (HTTPS)

05

One-shot

getCurrentPosition

06

Live

watchPosition

Introduction

Maps, store finders, and weather widgets often need the user’s location. The Geolocation API lets your page request that location — but only after the browser asks the user for permission.

Your entry point is navigator.geolocation. It is read-only and returns a Geolocation object with methods such as getCurrentPosition() and watchPosition().

💡
Permission + HTTPS

MDN: location access notifies the user and requires permission. The API is available in secure contexts (HTTPS / localhost). Always handle “denied” and timeouts kindly.

Understanding the geolocation Property

Think of navigator.geolocation as a handle to the device’s location services for this page. You do not assign to it — you call methods on the object it returns.

  • getCurrentPosition(success, error?, options?) — one location reading.
  • watchPosition(success, error?, options?) — ongoing updates; returns a watch ID.
  • clearWatch(id) — stop a watch.
  • coords — on success, use position.coords.latitude / longitude (and more).

📝 Syntax

General form of the property:

JavaScript
navigator.geolocation

Value

  • A Geolocation object that provides access to the device location.

Common patterns

JavaScript
if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      console.log(pos.coords.latitude, pos.coords.longitude);
    },
    (err) => {
      console.log(err.code, err.message);
    },
    { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }
  );
} else {
  // Geolocation not available
}

⚡ Quick Reference

GoalCode
Get Geolocationnavigator.geolocation
Detect API"geolocation" in navigator
One readinggetCurrentPosition(success, error, options)
Watch updateswatchPosition(success, error, options)
Stop watchingclearWatch(id)
Secure page?window.isSecureContext

🔍 At a Glance

Four facts to remember about navigator.geolocation.

Returns
Geolocation

API entry

Baseline
widely

Since ~2015

HTTPS
required

Secure context

Permission
user prompt

Must allow

📋 getCurrentPosition vs watchPosition

getCurrentPositionwatchPosition
FrequencyOne-shotOngoing updates
Best for“Find stores near me”Live maps / tracking a walk
CleanupNoneclearWatch(id)
BatteryUsually lighterCan use more power
PermissionBoth require user permission when needed

Examples Gallery

Examples follow MDN Geolocation / navigator.geolocation patterns. Prefer Try It Yourself over HTTPS and allow location when prompted. Use View Output for expected messaging.

📚 Getting Started

Detect the API and confirm a secure context.

Example 1 — Feature Detection

Check whether Geolocation is available.

JavaScript
const supported = "geolocation" in navigator;
console.log(supported ? "geolocation available" : "geolocation missing");
Try It Yourself

How It Works

Almost all modern browsers expose the property; still detect it before calling methods.

Example 2 — Secure Context Check

Pair detection with isSecureContext.

JavaScript
const lines = [
  "isSecureContext: " + window.isSecureContext,
  "geolocation: " + (("geolocation" in navigator) ? "present" : "absent")
];
console.log(lines.join("\n"));
Try It Yourself

How It Works

Serve location features over HTTPS (or localhost during development).

📈 Practical Patterns

One-shot location, live watching, and a reusable helper.

Example 3 — getCurrentPosition

Request one reading from a button click (permission prompt).

JavaScript
function getMyLocation(onDone) {
  if (!("geolocation" in navigator)) {
    onDone("geolocation unavailable");
    return;
  }
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      const c = pos.coords;
      onDone("lat: " + c.latitude + ", lng: " + c.longitude);
    },
    (err) => {
      onDone("error " + err.code + ": " + err.message);
    }
  );
}

// Call from a button in Try It
Try It Yourself

How It Works

Success gives a GeolocationPosition. Common error codes include permission denied (1), position unavailable (2), and timeout (3).

Example 4 — watchPosition + clearWatch

Start live updates, then stop them with the watch ID.

JavaScript
let watchId = null;

function startWatch(onUpdate) {
  if (!("geolocation" in navigator)) {
    onUpdate("geolocation unavailable");
    return;
  }
  watchId = navigator.geolocation.watchPosition(
    (pos) => {
      onUpdate("watching lat: " + pos.coords.latitude);
    },
    (err) => {
      onUpdate("watch error: " + err.message);
    }
  );
}

function stopWatch() {
  if (watchId !== null) {
    navigator.geolocation.clearWatch(watchId);
    watchId = null;
  }
}

// Wire Start / Stop buttons in Try It
Try It Yourself

How It Works

Always clear watches when the page no longer needs them to save battery and privacy.

Example 5 — Safe Options Helper

Wrap secure-context checks, options, and structured results.

JavaScript
function getLocationOnce() {
  return new Promise((resolve) => {
    if (!window.isSecureContext) {
      resolve({ ok: false, reason: "insecure-context" });
      return;
    }
    if (!("geolocation" in navigator)) {
      resolve({ ok: false, reason: "unsupported" });
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        resolve({
          ok: true,
          latitude: pos.coords.latitude,
          longitude: pos.coords.longitude,
          accuracy: pos.coords.accuracy
        });
      },
      (err) => {
        resolve({ ok: false, reason: err.message, code: err.code });
      },
      { enableHighAccuracy: false, timeout: 8000, maximumAge: 60000 }
    );
  });
}

// Call from a button in Try It
Try It Yourself

How It Works

maximumAge can reuse a recent cached position; timeout fails if a fix takes too long.

🚀 Common Use Cases

  • Store / restaurant finders — sort results by distance.
  • Maps — center the map on the user (after permission).
  • Weather / local news — tailor content to the region.
  • Fitness / navigationwatchPosition for live trails.
  • Check-in features — confirm the user is near a venue.

🧠 How navigator.geolocation Works

1

Secure page + detect

HTTPS / localhost and "geolocation" in navigator.

Detect
2

User grants permission

Browser prompt (policy varies by browser).

Permission
3

Call get / watch

Receive GeolocationPosition with coords.

Locate
4

Use coords or handle errors

Show maps / distances — or a friendly denial message.

📝 Notes

  • Baseline Widely available (MDN, since about July 2015).
  • Not Deprecated, Experimental, or Non-standard — no status banner required.
  • Secure context required (HTTPS / localhost).
  • Always handle permission denial and timeouts.
  • Related: doNotTrack, globalPrivacyControl, JavaScript hub.

Universal Browser Support

navigator.geolocation is Baseline Widely available across modern browsers (MDN: since about July 2015). Always use a secure context and respect the permission prompt.

Baseline · Widely available

Navigator.geolocation

Feature-detect, require HTTPS, call getCurrentPosition/watchPosition from a user gesture when possible, and handle denials.

Universal Widely available
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
geolocation Excellent

Bottom line: Use navigator.geolocation for location features. Keep a non-location fallback when permission is denied.

Conclusion

navigator.geolocation is the Geolocation API entry point. Feature-detect it, require HTTPS, request permission politely, use getCurrentPosition or watchPosition, and always handle errors.

Continue with globalPrivacyControl, doNotTrack, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Explain why you need location before prompting
  • Serve over HTTPS
  • Provide success and error callbacks
  • Call clearWatch when done watching
  • Offer a manual city / ZIP fallback

❌ Don’t

  • Request location on every page load without context
  • Assume the user will always allow
  • Ignore timeout / unavailable errors
  • Track users continuously without a clear purpose
  • Forget battery cost of high-accuracy watches

Key Takeaways

Knowledge Unlocked

Five things to remember about geolocation

Location API entry — permission, HTTPS, get or watch.

5
Core concepts
🔍 02

One-shot

getCurrentPosition

Read
🔄 03

Live

watchPosition

Watch
🔒 04

HTTPS

secure context

Security
👤 05

Permission

user prompt

Consent

❓ Frequently Asked Questions

It is a read-only Navigator property that returns a Geolocation object — the entry point to the Geolocation API for reading the device’s location (with user permission).
No. MDN marks it Baseline Widely available (since about July 2015). It is not Deprecated, Experimental, or Non-standard. It does require a secure context (HTTPS / localhost).
Yes. When your page requests location, the browser asks for permission. Policies and UI differ by browser. Always handle denial gracefully.
Call navigator.geolocation.getCurrentPosition(success, error, options). The success callback receives a GeolocationPosition with coords.latitude and coords.longitude.
watchPosition(success, error, options) keeps updating as the device moves and returns a watch ID. Stop updates with clearWatch(id).
No. The property is read-only. You call methods on the returned Geolocation object.
Did you know?

MDN emphasizes that every browser has its own policies for asking location permission — so never hard-code assumptions about when the prompt appears or how denial is worded.

Explore globalPrivacyControl Next

Learn the Global Privacy Control signal for sell/share consent.

globalPrivacyControl →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful