HTML Geolocation API Tutorial: How to Get User Location with JavaScript (Step-by-Step Guide)

HTML Tutorials · HTML Geolocation API Tag · Introduction

HTML Geolocation API Explained: How to Get User Location Using JavaScript (Beginner to Advanced Guide)

🔸HTML Geolocation API allows a website to access the geographical location of the user's device (with their permissions). This is commonly used in maps, delivery apps, or local services. Here's a basic example.

Trulli
HTML Geolocation API permission and code structure
Trulli
Geolocation API returning latitude and longitude

What Exactly Is the Geolocation API?

🔸 The Geolocation API isn't an HTML tag at all — it's a JavaScript interface, exposed on the browser's global navigator object as navigator.geolocation, that asks the operating system for the device's current physical position. Under the hood, the browser combines whatever location signals the device has available — GPS on a phone, nearby Wi-Fi network fingerprinting, cell-tower triangulation, or a rough IP-address lookup on a desktop — and returns whichever result it can produce with the highest confidence.

🔒 Important -

✅ Works only on secure origins (https:// or localhost)

✅ Asks the user for permission to access location

✅ Returns latitude and longitude

✅ Can be extended with Google Maps, Leaflet, or other mapping libraries

✅ Basic Geolocation API HTML code Example:-

My Location

Click the button to get your location.

ExampleCopy Code
<!DOCTYPE html>
<html>
<head>
  <title>Geolocation API Example</title>
</head>
<body>

<h1>My Location</h1>
<p id="location">Click the button to get your location.</p>

<button onclick="getLocation()">Get Location</button>

<script>
  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else {
      document.getElementById("location").innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function showPosition(position) {
    document.getElementById("location").innerHTML =
      "Latitude: " + position.coords.latitude +
      "<br>Longitude: " + position.coords.longitude;
  }

  function showError(error) {
    let msg;
    switch(error.code) {
      case error.PERMISSION_DENIED:
        msg = "User denied the request for Geolocation.";
        break;
      case error.POSITION_UNAVAILABLE:
        msg = "Location information is unavailable.";
        break;
      case error.TIMEOUT:
        msg = "The request to get user location timed out.";
        break;
      case error.UNKNOWN_ERROR:
        msg = "An unknown error occurred.";
        break;
    }
    document.getElementById("location").innerHTML = msg;
  }
</script>

</body>
</html>

🔸 Clicking the button above triggers a genuine browser permission prompt (or uses a previously saved choice) and, if allowed, reports your actual approximate coordinates back in this page — exactly the same three-function pattern shown in the code: a trigger function, a success callback that receives a position object, and an error callback that inspects error.code to report what went wrong.

Breaking Down the position.coords Object

🔸 The showPosition callback above reads position.coords.latitude and position.coords.longitude, but the full coords object carries several more properties worth knowing about.

PropertyMeaning
latitude / longitudeThe device's coordinates in decimal degrees
accuracyThe radius of certainty around the reported position, in meters
altitudeHeight above sea level, in meters (often null if unavailable)
altitudeAccuracyCertainty radius for the altitude reading, in meters
headingDirection of travel in degrees, only meaningful while moving
speedCurrent speed in meters per second, if the device can determine it

Understanding the Four Error Codes

🔸 The showError function's switch statement handles every possible failure the API can report, and knowing what triggers each one helps you write clearer user-facing messages than the generic examples above.

Error CodeWhat It Means
PERMISSION_DENIEDThe user explicitly clicked "Block" on the location permission prompt
POSITION_UNAVAILABLEThe device's location sensors couldn't determine a position at all
TIMEOUTThe request took longer than the allowed time (see timeout option below) and was abandoned
UNKNOWN_ERRORA generic failure that doesn't fit the three categories above

Optional Configuration: The PositionOptions Object

🔸 getCurrentPosition accepts an optional third argument beyond the success and error callbacks shown in the basic example, letting you fine-tune accuracy and timing behavior.

ExampleCopy Code
navigator.geolocation.getCurrentPosition(showPosition, showError, {
  enableHighAccuracy: true,
  timeout: 10000,
  maximumAge: 0
});
OptionEffect
enableHighAccuracyRequests the most precise reading available (typically GPS), at the cost of extra battery use and time
timeoutMaximum milliseconds to wait before firing the TIMEOUT error
maximumAgeAllows the browser to reuse a cached position up to this many milliseconds old, instead of requesting a fresh one

getCurrentPosition vs watchPosition

🔸 The basic example above uses getCurrentPosition, which fetches the location exactly once. A second method, watchPosition, is built for continuous tracking.

MethodBehaviorBest For
getCurrentPosition()Fires the callback once with the current location"Find my location" buttons, one-time address lookup
watchPosition()Fires the callback repeatedly whenever position changesLive navigation, delivery tracking, fitness apps
ExampleCopy Code
const watchId = navigator.geolocation.watchPosition(showPosition, showError);

// Later, to stop tracking:
navigator.geolocation.clearWatch(watchId);

Real-World Use Cases

Use CaseHow Geolocation Helps
Store locator / "find nearest branch"Calculates distance from the visitor's coordinates to each location
Food delivery appsAuto-fills the delivery address or tracks a driver's live position with watchPosition
Weather websitesShows local forecast automatically without the visitor typing their city
Maps and directionsCenters the map on the user's current position as the starting point
Local business searchFilters and ranks results by proximity to the visitor

Why HTTPS Is Required

🔸 As the "Important" section above notes, the Geolocation API only works on secure origins — a page served over https://, or a page loaded from localhost during development. This restriction exists because location data is highly sensitive, and browsers refuse to expose it over an unencrypted http:// connection where the request and response could be intercepted or tampered with in transit.

Privacy and Permission Best Practices

Common Mistakes with the Geolocation API

Geolocation API Best Practices

Try It Yourself (Copy This Code and Paste. See how it works). Paste the example above into the live playground below.

</> Try It Yourself (Copy this code and paste. See how it works)

Live Code Preview

Practice Exercises: Test the Geolocation API

  1. Rebuild the basic example, then add position.coords.accuracy to the displayed output.
  2. Add enableHighAccuracy: true and a 10-second timeout to your getCurrentPosition call.
  3. Convert your example from getCurrentPosition to watchPosition and log each update to the console.
  4. Add a clearWatch call triggered by a "Stop Tracking" button.
  5. Write a friendlier error message for each of the four error codes than the ones shown in this tutorial.

Frequently Asked Questions About the HTML Geolocation API

What is the Geolocation API?

It is a browser API that allows websites to access the user's location.

Is Geolocation API safe?

Yes, it requires user permission before accessing location.

Do I need HTTPS for Geolocation?

Yes, modern browsers require HTTPS for geolocation access.

How accurate is the Geolocation API?

Accuracy varies by device and available sensors: GPS-equipped mobile devices can be accurate to a few meters, while desktops relying on Wi-Fi or IP-based lookup may only be accurate to within a city or neighborhood.

What is the difference between getCurrentPosition and watchPosition?

getCurrentPosition retrieves the device's location a single time, while watchPosition continuously monitors position and calls its callback every time the location changes, which is useful for live tracking such as turn-by-turn navigation.

Conclusion

🔸 The Geolocation API distills down to three moving parts: feature-detect with navigator.geolocation, call getCurrentPosition (or watchPosition for continuous tracking) with a success and an error callback, and read the resulting coordinates off position.coords. Layer on HTTPS, thoughtful permission timing, and a graceful fallback for denied requests, and you have everything needed to power store locators, delivery tracking, local search, and map-centered experiences. Work through the example above, then try wiring your own result into a mapping library like Leaflet or Google Maps.