Academic Block

HTML Geolocation Get Certified

What is HTML Geolocation?

The HTML5 Geolocation API lets a webpage ask the browser for the user’s current geographic location (latitude and longitude). The user must give permission before any location data is shared. This is useful for maps, location-based services, and personalized experiences.

Key Points

  • Requires user permission (the browser shows a prompt).
  • Works best over HTTPS (required in most modern browsers).
  • Returns latitude, longitude, accuracy, and optionally altitude, speed, etc.
  • Always handle errors (permission denied, timeout, unavailable, etc.).

HTML Geolocation Code Examples

1. Basic Geolocation Example

A simple button that retrieves and displays the user’s current coordinates.

What this code does: Asks for the user’s location and shows latitude and longitude when permission is granted.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Basic Geolocation</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
    button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
    #location { margin-top: 15px; font-size: 18px; }
  </style>
</head>
<body>
  <h2>Find Your Location</h2>
  <button onclick="getLocation()">Get My Location</button>
  <p id="location">Location will appear here.</p>

  <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) {
      document.getElementById("location").innerHTML = "Unable to retrieve your location.";
    }
  </script>
</body>
</html>

2. Geolocation with Detailed Error Handling

Shows different messages depending on why the location request failed.

What this code does: Handles permission denied, position unavailable, timeout, and unknown errors separately.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Geolocation with Error Handling</title>
  <style>
    body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
    button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
    #result { margin-top: 15px; font-size: 18px; }
  </style>
</head>
<body>
  <h2>Advanced Geolocation</h2>
  <button onclick="getLocation()">Get Location</button>
  <p id="result">Click the button to get your location.</p>

  <script>
    function getLocation() {
      if (!navigator.geolocation) {
        document.getElementById("result").innerHTML = "Geolocation is not supported by this browser.";
        return;
      }

      navigator.geolocation.getCurrentPosition(showPosition, showError, {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0
      });
    }

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

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

3. Simple Responsive Version

A clean, mobile-friendly version of the basic geolocation example.

What this code does: Same functionality as the first example, with better styling for different screen sizes.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Geolocation</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
      background: #f5f5f5;
      max-width: 500px;
      margin: 0 auto;
    }
    button {
      width: 100%;
      padding: 14px;
      font-size: 18px;
      background: #3498db;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
    }
    button:hover { background: #2980b9; }
    #location {
      margin-top: 20px;
      padding: 15px;
      background: white;
      border-radius: 6px;
      font-size: 16px;
      line-height: 1.6;
    }
  </style>
</head>
<body>
  <h2>Find My Location</h2>
  <button onclick="getLocation()">Get My Location</button>
  <div id="location">Your location will appear here.</div>

  <script>
    function getLocation() {
      const output = document.getElementById("location");
      if (!navigator.geolocation) {
        output.innerHTML = "Geolocation is not supported by this browser.";
        return;
      }

      output.innerHTML = "Locating…";

      navigator.geolocation.getCurrentPosition(
        function(position) {
          output.innerHTML =
            "<strong>Latitude:</strong> " + position.coords.latitude + "<br>" +
            "<strong>Longitude:</strong> " + position.coords.longitude;
        },
        function() {
          output.innerHTML = "Unable to retrieve your location.";
        }
      );
    }
  </script>
</body>
</html>

Important Notes

  • Geolocation only works on HTTPS pages (or localhost).
  • The browser will always ask the user for permission.
  • If the user denies permission, the error callback is triggered.
  • For continuous tracking you can use navigator.geolocation.watchPosition().

Web Resources on HTML Geolocation

1. MDN : Using the Geolocation API (Tutorial)
2. MDN : Geolocation API (Reference)
3. MDN : Geolocation Interface

Questions and Answers related to HTML Geolocation

+ What is the HTML5 Geolocation API? >

It is a browser API that allows a web page to request the user’s current geographic position (latitude and longitude) after the user gives permission.

+ How do I get the user’s current location? >

Call navigator.geolocation.getCurrentPosition(successCallback, errorCallback). The success callback receives a position object containing the coordinates.

+ Why does geolocation require HTTPS? >

Modern browsers only allow the Geolocation API on secure origins (HTTPS or localhost) to protect user privacy.

+ What happens if the user denies permission? >

The error callback is called with error.code === error.PERMISSION_DENIED. You should show a friendly message and not keep asking.

+ Can I track the user’s location continuously? >

Yes. Use navigator.geolocation.watchPosition() instead of getCurrentPosition(). Remember to call clearWatch() when you no longer need updates.

🧪 Test Your HTML Code

Edit the HTML code on the left and click “Run Code” to see the result on the right.

📝 HTML Code
👁️ Preview (Rendered HTML)

Click “Run Code” to see the result here.