HTML Geolocation

Beginner
12 min read
Updated: Nov 2026
5 examples
navigator.geolocation

Definition and Usage

HTML geolocation means reading the device’s location from a webpage so you can show nearby results, place a marker on a map, or personalize content. The browser asks the user for permission first. Access goes through navigator.geolocation (the Geolocation API).

How does an HTML page use it?

Typically a <button> starts the request. A script calls getCurrentPosition or watchPosition, then writes latitude/longitude into a <p> or other element. Never grab location silently on page load without a clear user action.

What about the HTML <geolocation> element?

MDN also documents an experimental <geolocation> element: a browser-defined control with built-in UI and a clearer permission flow. It still uses the Geolocation API underneath. Support is limited today—nest a fallback <button> that calls the API for other browsers.

When should you use geolocation on a site?

Store finders, weather for “near me,” delivery ETA, or check-in features. Always explain why you need location and provide a manual address field if the user declines.

Secure context required.

Modern browsers expose geolocation on HTTPS pages (and usually localhost for development).

Privacy first.

Location can identify a person. Ask only when needed, use the data for the stated purpose, and do not store it longer than necessary.

iframes need permission.

Third-party frames may need Permissions-Policy: geolocation=… and allow="geolocation" on the <iframe>.

HTML / Script Syntax

Classic pattern: button in HTML, Geolocation API in a script:

JS
navigator.geolocation.getCurrentPosition(success, error, options);
navigator.geolocation.watchPosition(success, error, options);
navigator.geolocation.clearWatch(watchId);
HTML
<button type="button" id="get-location">Get Location</button>
<p id="location"></p>

<script>
  document.getElementById("get-location").onclick = function () {
    navigator.geolocation.getCurrentPosition(
      function (position) {
        document.getElementById("location").textContent =
          "Latitude: " + position.coords.latitude +
          ", Longitude: " + position.coords.longitude;
      },
      function (error) {
        document.getElementById("location").textContent = "Error: " + error.message;
      }
    );
  };
</script>

Experimental element (with API fallback inside):

HTML
<geolocation>
  <button type="button" id="fallback">Use location</button>
</geolocation>
<p id="output"></p>

Core HTML Concepts

Pieces that connect location data to your webpage:

ConceptRole
navigator.geolocationEntry point to the Geolocation API from a page script
getCurrentPositionOne-shot location fix
watchPosition / clearWatchLive updates while the device moves; stop when done
GeolocationPositionSuccess result: coords + timestamp
coords.latitude / longitudeCommon values to show in HTML
GeolocationPositionErrorError callback: code and message
Permission promptUser must allow before the browser returns a fix
<geolocation>Experimental declarative control (limited browser support)
watch / autolocateAttributes on <geolocation> (when supported)

Position options

OptionMeaning
enableHighAccuracyPrefer GPS / higher precision when available (may use more power)
timeoutMilliseconds before the error callback runs with TIMEOUT
maximumAgeAccept a cached position no older than this many ms

Error codes for your HTML UI

CodeNameTypical HTML message
1PERMISSION_DENIEDPlease allow location, or enter an address
2POSITION_UNAVAILABLELocation could not be determined
3TIMEOUTTimed out — try again

How to Use Geolocation in an HTML Page

Build around a clear control and visible feedback.

  1. Serve the page over HTTPS (or use localhost while learning).
  2. Add a button (or experimental <geolocation> with a nested fallback button).
  3. On click, check navigator.geolocation exists.
  4. Call getCurrentPosition(success, error, options).
  5. In success, write coords into the HTML; in error, show a friendly message.
  6. For tracking, use watchPosition and call clearWatch when leaving the page or stopping.
GoalPattern
One fix after clickgetCurrentPosition(ok, err)
Live trackingwatchId = watchPosition(ok, err) then clearWatch(watchId)
Prefer GPS{ enableHighAccuracy: true }
Fail fast{ timeout: 10000 }
Show in HTMLp.textContent = lat + ", " + lng

Live Preview

Click the button to request this device’s location (browser permission required). Works best on HTTPS or localhost.

action

Uses navigator.geolocation.getCurrentPosition and writes into the output below.

Location result

Not requested yet.

Click “Get location” to start.

HTML Examples

Five patterns: current position, options, watch, errors, and a full HTML page with a button.

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

  1. Permission — the browser prompts on first request for this origin.
  2. Success callback receives a GeolocationPosition.
  3. coords holds latitude, longitude, accuracy, and more.
  4. Prefer a button so the request follows a clear user gesture.

Example 2 — Options (Accuracy, Timeout, Cache)

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

How It Works

  1. enableHighAccuracy asks for a better fix when the device can provide one.
  2. timeout triggers the error callback if no fix arrives in time.
  3. maximumAge can reuse a recent cached position for faster UI.
  4. Tune for UX — maps may want accuracy; store finders may accept a quick cache.

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

  1. watchPosition keeps calling success as the device moves.
  2. Update HTML each time (for example a live map pin).
  3. clearWatch stops listening and saves battery.
  4. Experimental element: <geolocation watch> maps to similar behavior when supported.

Example 4 — Error Handling in the UI

JS
navigator.geolocation.getCurrentPosition(
  function (pos) { /* success — update HTML */ },
  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

  1. Always pass an error callback for production HTML pages.
  2. Map codes to short messages in a <p> or alert.
  3. Denied — show a form for city/ZIP instead of blocking the feature.
  4. Timeout — offer “Try again” with a higher timeout or lower accuracy.

Example 5 — Full HTML Page

Button click → permission → coordinates in the page:

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

  <script>
    document.getElementById("get-location").onclick = function () {
      if (!navigator.geolocation) {
        document.getElementById("location").textContent =
          "Geolocation is not supported.";
        return;
      }

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

How It Works

  1. HTML provides the control and a place for results.
  2. Feature detect before calling the API.
  3. Success fills the paragraph; error shows the reason.
  4. Same UX goal as <geolocation> with a nested fallback button on unsupported browsers.

Edge Cases & Pitfalls

Most failures are permission, insecure context, or missing error UI—not missing HTML tags.

https

HTTP (non-secure) pages

Geolocation is blocked outside secure contexts. Deploy HTTPS for production HTML.

deny

User denies permission

Handle code 1 and offer a city/ZIP form. Do not spam the prompt.

watch

Leaving watchPosition running

Call clearWatch when the user stops tracking or navigates away.

iframe

Embedded frames

May need Permissions-Policy and allow="geolocation" on the iframe.

geo-el

Relying only on <geolocation>

Limited availability. Always nest a button + API fallback for today’s browsers.

china

Regional availability

Some regions may need local providers instead of the vanilla browser service.

Browser Support

navigator.geolocation is widely available in modern browsers (secure contexts). The HTML geolocation element is experimental with limited availability.

✓ API: Baseline · Element: Limited

Geolocation on HTML pages

Use the Geolocation API from page scripts everywhere users browse securely; treatas progressive enhancement.

API navigator.geolocation
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 Wide

Bottom line: Ship getCurrentPosition behind a button today; addwith a nested fallback when you want declarative UI later.

Key Takeaways

  • navigator.geolocation powers location in HTML pages (HTTPS + permission).
  • Button + script is the reliable pattern; show coords in the DOM.
  • getCurrentPosition once; watchPosition for live updates.
  • <geolocation> is experimental—use a nested button fallback.

One line: User activates a control → browser asks permission → script reads coords → HTML shows the result.

Frequently Asked Questions

It means reading the device’s location from a webpage. The Geolocation API is reached via navigator.geolocation. A page script asks for permission, then getCurrentPosition or watchPosition returns coordinates you can show in HTML.
The experimental <geolocation> element is a browser-defined control for sharing location with clearer UI and permission flow. It uses the Geolocation API under the hood. Support is limited—include a <button> fallback that calls getCurrentPosition.
Yes for real sites. Geolocation is a secure-context feature in modern browsers. Localhost is usually allowed for learning; production pages should be served over HTTPS.
getCurrentPosition fetches one fix. watchPosition calls your success handler whenever the position updates until you clearWatch. Use watch for live tracking; always clearWatch when done.
Location is sensitive. Browsers prompt for permission when you request it. Triggering from a clear user gesture (button click) matches user expectations and pairs well with the upcoming geolocation element’s conscious-choice model.
PERMISSION_DENIED (1), POSITION_UNAVAILABLE (2), and TIMEOUT (3). Show a friendly message in the page and offer a manual address fallback when permission is denied.

Practice in the editor

Open the full HTML demo and allow location when the browser asks.

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.

8 people found this page helpful