Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're at a massive outdoor music festival. You've wandered too far from your friends and you have no idea where the food trucks are. You pull out your phone and ask, "Where am I right now?" Your phone doesn't just magically know; it sends out a request to GPS satellites and nearby cell towers, waits for them to respond, and then translates those signals into a coordinate on a map. It's a conversation: you ask for the location, the system verifies you have permission to know, and then it hands you the coordinates.

The Geolocation API works exactly like that. In JavaScript, the navigator.geolocation object is your interface to the device's location hardware. Here is how that festival analogy maps to the code:

  • Asking "Where am I?" is calling getCurrentPosition().
  • The permission popup is the browser's security layer ensuring the user actually wants to share their location with your site.
  • The coordinates are delivered as a Position object containing the latitude and longitude.
  • The "lost signal" is handled by an error callback if the GPS is off or the user says "No."

Asking the Browser for a Pin on the Map

To get a user's location, we use navigator.geolocation.getCurrentPosition(). Now, this is an asynchronous operation. The browser can't just freeze your whole website while it waits for a satellite in space to respond, so it uses callbacks. You provide one function to handle success and another to handle failure.

const findMe = () => {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      const lat = position.coords.latitude;
      const lon = position.coords.longitude;
      console.log(`You are at Lat: ${lat}, Lon: ${lon}`);
    },
    (error) => {
      console.error(`Error getting location: ${error.message}`);
    }
  );
};

findMe();

I should mention that this will only work over HTTPS. Browsers consider location data extremely sensitive, so if you're trying to run this on a plain HTTP site in production, it'll just fail silently or throw a security error. Localhost is usually an exception for development purposes.

Dealing with "No" and "I can't find you"

In a real app, you can't just assume the user will click "Allow." People are protective of their privacy, and sometimes the hardware simply fails. The error callback provides a GeolocationPositionError object. I always recommend checking the code property of that error to give the user a helpful message instead of a generic "something went wrong."

navigator.geolocation.getCurrentPosition(
  (pos) => { /* handle success */ },
  (err) => {
    switch(err.code) {
      case err.PERMISSION_DENIED:
        alert("You denied the request for Geolocation. I can't find your nearby coffee shops!");
        break;
      case err.POSITION_UNAVAILABLE:
        alert("Location information is unavailable.");
        break;
      case err.TIMEOUT:
        alert("The request to get user location timed out.");
        break;
      default:
        alert("An unknown error occurred.");
        break;
    }
  }
);

Keeping Tabs on a Moving Target

Sometimes getCurrentPosition isn't enough. If you're building a fitness tracker or a delivery app, you need to know when the user moves. That's where watchPosition() comes in. It works almost identically to the previous method, but instead of firing once, it keeps the "conversation" open and triggers the success callback every time the device's location changes significantly.

const watchId = navigator.geolocation.watchPosition(
  (position) => {
    console.log(`Moved to: ${position.coords.latitude}, ${position.coords.longitude}`);
  },
  (error) => { console.error(error); },
  { 
    enableHighAccuracy: true, 
    timeout: 5000, 
    maximumAge: 0 
  }
);

// When you're done tracking, don't forget to stop it to save battery!
// navigator.geolocation.clearWatch(watchId);

Notice the third argument in watchPosition? Those are options. enableHighAccuracy: true tells the device to use GPS rather than just Wi-Fi triangulation. It's more precise, but it'll drain the user's battery faster—use it sparingly.




📋 Practical Task

Build a "Local Weather Trigger" Simulator

Create a small application that simulates a weather alert system based on a user's actual location. Your code should:

  1. Implement a button labeled "Check Local Weather".
  2. When clicked, use the Geolocation API to retrieve the user's current latitude and longitude.
  3. If the location is successfully retrieved, display a message saying: "Fetching weather for coordinates: [Lat], [Lon]..."
  4. If the user denies permission, display a specific message: "Weather access denied. Please enable location permissions in your browser settings to see local forecasts."
  5. Include a "Stop Tracking" button that uses clearWatch() to stop a background watchPosition() process that logs the coordinates to the console every time the user moves.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.