Advance JavaScript (DOM, BOM, Web API) / Web API

Geolocation

The Geolocation API lets a website request your current location — but only if you allow it.

❓ Why Use the Geolocation API?

Many web apps rely on user location, such as:

  • Search engines

  • eCommerce websites

  • Maps and navigation apps

  • Weather apps

Example:

An online store may ask for your location to show nearby product availability or location-based discounts.

Another example:

If you’re in San Francisco and search “pizza”, Google shows pizza places near you.


🔰 Geolocation Object

The API is accessed through:

navigator.geolocation

✅ Check Browser Support

Before using it, check if the browser supports geolocation:

if (!navigator.geolocation) {
    console.error("Your browser doesn't support Geolocation");
}

🚩 Get the Current Position

To get a user’s location, call:

navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

What happens:

  • The browser requests permission from the user.

  • If permission is granted, the API uses GPS or network data to find the latest location.

  • The request is asynchronous (it takes time).

On success:

You receive a GeolocationCoordinates object containing:

  • latitude

  • longitude


📌 Geolocation example

The following example shows a simple application that has one button. When you click the button, the browser will request you to share your location. If you agree, it’ll show your current latitude and longitude.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Geolocation Demo</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div class="container">
        <button id="show" class="btn">Show my location</button>
        <div id="message"></div>
    </div>
    <script src="js/app.js"></script>
</body>
</html>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

body {
  background: linear-gradient(135deg, #f0f4f8, #d9e4f5);
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  background-color: #ffffff;
  padding: 2rem 3rem;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 400px;
  width: 100%;
}

.btn {
  padding: 0.75rem 1.5rem;
  background-color: #007bff;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-bottom: 1rem;
}

.btn:hover {
  background-color: #0056b3;
}

#message {
  font-size: 1rem;
  padding: 0.5rem;
  border-radius: 6px;
  margin-top: 0.5rem;
  transition: all 0.3s ease;
}

.success {
  color: #155724;
  background-color: #d4edda;
  border: 1px solid #c3e6cb;
}

.error {
  color: #721c24;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
}
(() => {
    const message = document.querySelector('#message');

    // check if the Geolocation API is supported
    if (!navigator.geolocation) {
        message.textContent = `Your browser doesn't support Geolocation`;
        message.classList.add('error');
        return;
    }

    // handle click event
    const btn = document.querySelector('#show');
    btn.addEventListener('click', function () {
        // get the current position
        navigator.geolocation.getCurrentPosition(onSuccess, onError);
    });

    // handle success case
    function onSuccess(position) {
        const {
            latitude,
            longitude
        } = position.coords;

        message.classList.add('success');
        message.textContent = `Your location: (${latitude},${longitude})`;
    }

    // handle error case
    function onError() {
        message.classList.add('error');
        message.textContent = `Failed to get your location!`;
    }
})();

How it works :

  1. First, select the #message element by using the querySelector() method.

  2. Next, show an error message if the browser doesn’t support the Geolocation API.

  3. Then, select the button and attach a click event handler. The click event handler calls the getCurrentPosition() method of the navigator.geolocation object to get the current position of the user.

  4. The onSuccess and onError callback functions are for handling the success and error cases.

  5. After that, define the onSuccess() function that gets the latitude and longitude from the position.coords and shows them on the <div> element with id message.

  6. Finally, define the onError() function that shows an error message in case the getCurrentPosition() method fails.

  • When you click the Show my location button, the browser will request you to share your location like this.

  • If you click the Allow button, you’ll see your location as shown in the following picture :

  • This time if you click the Never allow button.

  • The app will show an error message :