Chapter 1 of ?
html 8 min read

HTML Mastery — Chapter 16: HTML5 Geolocation API

1. Introduction to navigator.geolocation

The HTML5 Geolocation API allows web applications to access the user’s physical latitude and longitude. Depending on the user’s hardware and device settings, location is determined using:

  • GPS (Global Positioning System): High precision outdoors (smartphones, cellular devices).
  • Wi-Fi Triangulation: Nearby Wi-Fi network BSSIDs and signal strength.
  • IP Address Lookup: City/Country level coarse estimation when hardware GPS is unavailable.
  • Cellular Tower Triangulation: Mobile network tower signals.
Security & HTTPS Requirement: Modern web browsers strictly restrict the Geolocation API to Secure Contexts (HTTPS). Calling navigator.geolocation on unencrypted HTTP pages will fail silently or throw a security error (except on localhost for local development).

Checking Browser Geolocation Support

check-support.js
if ('geolocation' in navigator) { console.log("Geolocation is supported by this browser."); } else { console.warn("Geolocation API is not supported in your environment."); }
Try It Yourself »
Try It Yourself — Check Support & Secure Context

Click below to test if your current browser and origin support the HTML5 Geolocation API live:


2. Geolocation Permission & Resolution Lifecycle

User privacy is paramount. Browsers will never share user coordinates automatically. When a website requests location data for the first time, an explicit browser permission prompt is displayed to the user.

Geolocation API Request & Resolution Workflow
Web Application getCurrentPosition() Browser Prompt "Allow location access?" Allow Block Hardware Resolution GPS / Wi-Fi / IP Triangulation Success Callback coords.latitude, etc. Error Callback (PositionError) PERMISSION_DENIED | POSITION_UNAVAILABLE | TIMEOUT

Querying Permissions API Programmatically

navigator.permissions.query({ name: 'geolocation' }) .then((permissionStatus) => { console.log(`Permission state: ${permissionStatus.state}`); permissionStatus.onchange = () => { console.log(`Permission updated to: ${permissionStatus.state}`); }; });
Try It Yourself »
Try It Yourself — Check Location Permission Status

Query the browser's Permissions API to see whether location access is granted, prompt, or denied:


3. Retrieving Coordinates with getCurrentPosition()

The navigator.geolocation.getCurrentPosition() method requests a one-time location snapshot. It accepts three parameters:

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
Position Property Type Description
coords.latitudeNumber (decimal)Latitude in degrees (e.g. 37.7749).
coords.longitudeNumber (decimal)Longitude in degrees (e.g. -122.4194).
coords.accuracyNumber (meters)The accuracy level of latitude & longitude in meters.
coords.altitudeNumber or nullHeight above sea level in meters (if hardware supports).
coords.speedNumber or nullCurrent velocity in meters per second.
timestampEpoch MSTimestamp when position snapshot was recorded.

Configuring PositionOptions

const options = { enableHighAccuracy: true, // Forces GPS hardware if available timeout: 10000, // Maximum wait time in milliseconds (10s) maximumAge: 0 // Do not return cached positions }; navigator.geolocation.getCurrentPosition( (position) => { console.log(`Lat: ${position.coords.latitude}, Lng: ${position.coords.longitude}`); }, (error) => console.error(error.message), options );
Try It Yourself »
Try It Yourself — Live Coordinates & Location Finder

Click to fetch your live coordinates and generate an OpenStreetMap location link:


4. Continuous Tracking with watchPosition() & clearWatch()

For navigation apps, fitness trackers, or live delivery maps, watchPosition() registers a handler that fires automatically whenever the device’s physical position changes.

Subscribing & Unsubscribing Movement Stream

// Start tracking movement const watchId = navigator.geolocation.watchPosition( (pos) => console.log("New Position:", pos.coords.latitude, pos.coords.longitude), (err) => console.error("Tracking Error:", err), { enableHighAccuracy: true } ); // Stop tracking when user leaves page or toggles off navigator.geolocation.clearWatch(watchId);
Try It Yourself »
Try It Yourself — Live Movement Tracker

Start live position watching to see continuous position updates:


5. Error Handling & PositionError Codes

When location retrieval fails, the error callback receives a PositionError object containing a numerical code and a descriptive message:

Error Code Constant Name Cause & Recommended Recovery Action
1 PERMISSION_DENIED User clicked "Block" on the prompt. Prompt user with manual location search bar.
2 POSITION_UNAVAILABLE Location resolution failed (no GPS fix, offline). Fallback to IP address geolocation API.
3 TIMEOUT Resolution exceeded options.timeout limit. Retry with higher timeout or enableHighAccuracy: false.

Robust Error Handling Pattern

function handleGeoError(error) { switch (error.code) { case error.PERMISSION_DENIED: alert("Please allow location access or type your city manually."); break; case error.POSITION_UNAVAILABLE: alert("Location info unavailable. Switching to IP fallback..."); break; case error.TIMEOUT: alert("Location request timed out. Retrying..."); break; default: alert("An unknown error occurred."); break; } }
Try It Yourself »
Try It Yourself — Error Code Interpreter

Select a simulated PositionError code to test the handler logic:


Hands-On Challenge: Build a Store Distance Finder

Write a function that uses the Haversine Formula to compute the distance in kilometers between the user’s live coordinates and a target store location (e.g. Latitude: 37.7749, Longitude: -122.4194).

Launch Code Playground & Try »

Chapter 16 Key Takeaways

  • navigator.geolocation requires an HTTPS secure context.
  • User permission is required before any location data is returned.
  • Use getCurrentPosition() for single snapshots; use watchPosition() for continuous movement updates.
  • Always pass an error callback to handle PERMISSION_DENIED, POSITION_UNAVAILABLE, and TIMEOUT.
  • Use enableHighAccuracy sparingly as hardware GPS consumes higher device battery power.
Done with this chapter?
Mark it complete to track your progress and unlock your certificate.
Next Up

Learner Reviews

Write a Review
Share your experience to help other learners.
Your Rating *