HTML Geolocation

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples + 3 Try It
navigator.geolocation

Introduction

The Geolocation API allows web applications to retrieve the geographical location of a user’s device. This feature enables location-based services and functionalities, such as displaying nearby places, customizing content based on location, and providing location-based recommendations.

The API provides location data using GPS, Wi-Fi, cell towers, or IP-based methods—whichever the device supports. You access it through JavaScript’s navigator.geolocation object, not through an HTML tag.

What You’ll Learn

01

What it is

Location API.

02

getCurrent

One-time read.

03

watchPosition

Live updates.

04

coords

Lat & lng.

05

Errors

3 error codes.

06

Privacy

User consent.

What Is Geolocation?

Geolocation refers to the process of determining the physical location of a device. The Geolocation API in HTML5 provides a way to access this information programmatically, allowing web applications to use location data for various purposes, such as mapping and location-based services.

💡
Beginner Tip

“HTML Geolocation” really means using geolocation from a web page. The API is JavaScript on navigator.geolocation—there is no <geolocation> element.

How Does Geolocation Work?

The Geolocation API determines a user’s location using various methods, including:

  • GPS — provides precise location data using satellite signals (best outdoors on phones).
  • IP Address — estimates location based on the IP address of the device (rough, often city-level).
  • Network-Based — uses nearby Wi-Fi networks or cell towers to estimate location.

The browser chooses the best available source and returns a Position object with coordinates and an accuracy value in meters.

Using the Geolocation API

To use the Geolocation API, you need to call the navigator.geolocation object, which provides methods for retrieving location data. The main methods are getCurrentPosition and watchPosition.

Getting the Current Position

js
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
  • successCallback — function called with a Position object on success.
  • errorCallback — function called with a PositionError object on failure.
  • options (optional) — object specifying settings such as enableHighAccuracy, timeout, and maximumAge.
js
function successCallback(position) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  console.log('Latitude: ' + latitude + ', Longitude: ' + longitude);
}

function errorCallback(error) {
  console.error('Error occurred:', error.message);
}

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
  enableHighAccuracy: true
});

Watching the Position

js
var watchId = navigator.geolocation.watchPosition(successCallback, errorCallback, options);
  • watchId — identifier for the watch request, used for clearing the watch later.
js
navigator.geolocation.clearWatch(watchId);

Call clearWatch when you no longer need updates—continuous watching uses more battery.

Handling Geolocation Data

The Position object contains information about the user’s location, including:

  • coords.latitude — latitude of the user’s location.
  • coords.longitude — longitude of the user’s location.
  • coords.altitude — altitude (if available, may be null).
  • coords.accuracy — accuracy of the location data in meters.

Additional properties such as coords.speed, coords.heading, and timestamp may be available on supported devices.

Error Handling

The PositionError object provides information about errors encountered while retrieving the location. Common error codes include:

  • 1 — Permission denied.
  • 2 — Position unavailable.
  • 3 — Timeout.

Handle errors to provide appropriate feedback to users:

js
function errorCallback(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      console.error('User denied the request for geolocation.');
      break;
    case error.POSITION_UNAVAILABLE:
      console.error('Location information is unavailable.');
      break;
    case error.TIMEOUT:
      console.error('The request to get user location timed out.');
      break;
    default:
      console.error('An unknown error occurred.');
      break;
  }
}

Privacy and Permissions

Accessing geolocation data requires user permission. Browsers typically prompt users to allow or deny access. It’s important to respect user privacy and use location data responsibly. Inform users why location access is required and how it will be used.

Only request location after a user action (such as clicking “Find near me”)—never on page load without context. Sites must be served over HTTPS (or localhost) for geolocation to work in modern browsers.

Best Practices

  • Request Permissions Thoughtfully — request location access only when necessary and explain why it’s needed.
  • Handle Errors Gracefully — provide informative error messages and fallback options (manual city entry, map center default).
  • Respect Privacy — avoid storing location data longer than necessary and use it only for its intended purpose.
  • Optimize Performance — use high accuracy settings only when needed, as they can consume more battery and resources.

⚡ Quick Reference

TaskCode
One-time locationnavigator.geolocation.getCurrentPosition(ok, err)
Live trackingvar id = navigator.geolocation.watchPosition(ok, err)
Stop trackingnavigator.geolocation.clearWatch(id)
Read latitudeposition.coords.latitude
High accuracy{ enableHighAccuracy: true }
Feature detectif (navigator.geolocation) { ... }

Examples Gallery

Five short examples from a basic read to a full page. Try It Yourself demos use plain HTML with no CSS. Allow location when the browser prompts you.

Example 1 — Get Current Position

js
navigator.geolocation.getCurrentPosition(function (pos) {
  console.log(pos.coords.latitude, pos.coords.longitude);
});
Try It Yourself

How It Works

The browser shows a permission dialog the first time your site requests location.

Example 2 — Options (High Accuracy & Timeout)

js
navigator.geolocation.getCurrentPosition(ok, err, {
  enableHighAccuracy: true,
  timeout: 10000,
  maximumAge: 60000
});
Try It Yourself

How It Works

maximumAge lets the browser return a recent cached fix instead of waiting for a fresh GPS lock.

Example 3 — Watch Position Updates

js
var watchId = navigator.geolocation.watchPosition(function (pos) {
  console.log('Updated:', pos.coords.latitude);
});

// Later:
navigator.geolocation.clearWatch(watchId);
Try It Yourself

How It Works

Ideal for turn-by-turn navigation or live map markers. Always call clearWatch when done.

Example 4 — Error Handling

js
navigator.geolocation.getCurrentPosition(
  function (pos) { /* success */ },
  function (err) {
    if (err.code === 1) alert('Please allow location access.');
    else if (err.code === 3) alert('Timed out — try again.');
  }
);
Try It Yourself

How It Works

Show friendly UI when the user blocks location—offer a manual fallback.

Example 5 — Example (Full Page)

Simple page that gets the current location and displays it when the user clicks a button:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Geolocation Example</title>
</head>
<body>
  <h1>Geolocation Example</h1>
  <button id="get-location">Get Location</button>
  <p id="location"></p>

  <script>
    document.getElementById('get-location').onclick = function () {
      navigator.geolocation.getCurrentPosition(
        function (position) {
          var lat = position.coords.latitude;
          var lng = position.coords.longitude;
          document.getElementById('location').textContent =
            'Latitude: ' + lat + ', Longitude: ' + lng;
        },
        function (error) {
          document.getElementById('location').textContent =
            'Error: ' + error.message;
        }
      );
    };
  </script>
</body>
</html>
Try It Yourself

How It Works

Matches the reference tutorial pattern: user gesture → permission → display coordinates.

🚀 Common Use Cases

  • Store locators — find the nearest branch or pickup point.
  • Maps — center a map on the user’s position.
  • Local weather — fetch forecast for current coordinates.
  • Check-in apps — tag posts with where the user is.
  • Delivery tracking — show driver position with watchPosition.
  • Regional content — show prices or language for the user’s country.

Universal Browser Support

navigator.geolocation is supported in all modern browsers. It requires a secure context (HTTPS or localhost).

Baseline · Since HTML

Geolocation API

navigator.geolocation is supported in all modern browsers. It requires a secure context (HTTPS or localhost).

97% Modern browser support
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 API Excellent

Bottom line: Widely available on mobile and desktop. Always feature-detect with if (navigator.geolocation) and handle denied permissions gracefully.

Conclusion

The Geolocation API provides a robust way to incorporate location-based features into web applications. By understanding how to request and handle location data, you can create dynamic and responsive experiences tailored to the user’s location.

Always ensure to handle user permissions and data with care to maintain trust and provide valuable functionalities. Next, learn one-way server push with Server-Sent Events.

Key Takeaways

🔒 02

Permission

User must allow.

Privacy
🗺 03

coords

Lat & lng.

Data
🔄 04

watch

Live updates.

Tracking
⚠️ 05

HTTPS

Required.

Secure

❓ Frequently Asked Questions

It is a browser API (not an HTML tag) that lets JavaScript read the device's geographic position through navigator.geolocation. It returns latitude, longitude, and optional accuracy data.
Yes. Browsers show a permission prompt before sharing location. If the user denies access, your error callback runs with PERMISSION_DENIED (code 1).
getCurrentPosition fetches the location once. watchPosition calls your success callback whenever the position changes until you call clearWatch with the returned watch ID.
Yes on localhost and secure contexts (HTTPS). Most browsers block geolocation on non-secure HTTP sites except localhost.
Accuracy depends on the device: GPS is most precise outdoors; Wi-Fi and cell towers give rougher estimates indoors. Check position.coords.accuracy (meters) to see the reported error radius.
Yes. Browsers combine GPS, Wi-Fi, cell towers, and IP-based estimates. Desktop machines without GPS often still return an approximate location.
Did you know?

You can pass coordinates to map services without storing them. For example, open Google Maps with https://www.google.com/maps?q= plus latitude and longitude—no API key needed for a simple link.

Try geolocation in the editor

Click Get Location, allow the browser prompt, and see your latitude and longitude—plain HTML, no CSS.

Open Try It editor →

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.

5 people found this page helpful