JavaScript Geolocation API

In the previous lesson, we learned how to read and write the user’s clipboard. Now let’s learn how to find out where the user is in the world with the Geolocation API.

🌍 What is the Geolocation API?

The Geolocation API lets your code ask the browser for the user’s physical location. You get back a pair of coordinates: a latitude and a longitude. With those two numbers you can show a map, find nearby stores, or request the local weather.

The entry point is navigator.geolocation. Its main method is getCurrentPosition, which takes a success callback and an error callback.

geolocation-api.js
navigator.geolocation.getCurrentPosition(onSuccess, onError);

Let’s walk through this single line:

  • navigator.geolocation is the object the browser exposes for location features.
  • getCurrentPosition is the method that kicks off the location request.
  • onSuccess is the function the browser calls if it gets the location.
  • onError is the function the browser calls if the request fails.

The browser does not hand over the location automatically. It first asks the user for permission, and the user can say yes or no.

📍 Reading Latitude and Longitude

When the user allows access, the success callback runs and receives a position object. The coordinates live on position.coords.

geolocation-api.js
function onSuccess(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(`You are at ${latitude}, ${longitude}`);
}
navigator.geolocation.getCurrentPosition(onSuccess);

Let’s read this from the bottom up:

  • The last line calls getCurrentPosition and hands it onSuccess to run once the location is ready.
  • onSuccess receives the position object the browser passes in.
  • position.coords.latitude pulls out the north-south number, and position.coords.longitude pulls out the east-west number.
  • console.log then prints both coordinates in a readable string.

The success callback runs only after the user grants permission, which can take a few seconds while the browser locates the device. The position.coords object also carries extra fields such as accuracy, altitude, and speed, but latitude and longitude are the ones you will use most.

Property Meaning
position.coords.latitude How far north or south the user is
position.coords.longitude How far east or west the user is
position.coords.accuracy How precise the reading is, in meters

⚠️ Handling the Error Callback

The user can deny permission, or the device may fail to find a location. The second argument to getCurrentPosition is an error callback that runs when something goes wrong. It receives an error object with a code and a message.

geolocation-api.js
function onSuccess(position) {
console.log(position.coords.latitude, position.coords.longitude);
}
function onError(error) {
if (error.code === error.PERMISSION_DENIED) {
console.log("You denied the request for your location.");
} else {
console.log(`Could not get location: ${error.message}`);
}
}
navigator.geolocation.getCurrentPosition(onSuccess, onError);

Let’s step through both callbacks:

  • onSuccess runs when the location comes through, and it logs the latitude and longitude from position.coords.
  • onError runs when the request fails, and it receives an error object instead of a position.
  • Inside onError, we compare error.code to error.PERMISSION_DENIED to check whether the user said no.
  • If it matches, we print a clear “you denied” message; otherwise we fall back to error.message for any other problem.
  • The final line passes both callbacks to getCurrentPosition so the browser knows which one to run.

The error.code value tells you what happened. PERMISSION_DENIED means the user said no, POSITION_UNAVAILABLE means the device could not be located, and TIMEOUT means the request took too long.

Always pass an error callback

If you skip the error callback, your code goes silent when the user denies permission. The user sees nothing happen and assumes the page is broken.

🔒 The Secure Context Requirement

The Geolocation API only works in a secure context. That means the page must be served over https, or run on localhost during development. On a plain http page the API is blocked and the error callback fires.

geolocation-api.js
// ✅ Works: https://yourapp.com or http://localhost:3000
// ❌ Blocked: http://yourapp.com

These comments sum up the rule:

  • An https address is trusted, so the API runs.
  • localhost is treated as secure too, which lets you develop without a certificate.
  • A plain http address is not secure, so the browser blocks the call.

Before calling the API, it is good practice to confirm the browser supports it.

geolocation-api.js
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(onSuccess, onError);
} else {
console.log("Geolocation is not supported in this browser.");
}

Let’s read the check:

  • "geolocation" in navigator asks whether the browser actually has the feature.
  • If it does, the if branch runs and calls getCurrentPosition as usual.
  • If it does not, the else branch logs a fallback message instead of crashing.

🗺️ A Practical Example

Once you have the coordinates, you can use them in a real request. Here we read the user’s location and build a URL for a weather service.

geolocation-api.js
function showWeather(position) {
const { latitude, longitude } = position.coords;
const url = `https://api.example.com/weather?lat=${latitude}&lon=${longitude}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
console.log(`Temperature near you: ${data.temperature}°`);
});
}
function handleError(error) {
console.log(`Location error: ${error.message}`);
}
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(showWeather, handleError);
}

Let’s trace the flow:

  • The bottom if confirms support, then calls getCurrentPosition with showWeather as the success callback and handleError as the error callback.
  • showWeather destructures latitude and longitude out of position.coords in one line.
  • It drops those coordinates into a url string for the weather service.
  • fetch(url) sends the request, the first .then turns the response into JSON, and the second .then logs the temperature from data.
  • handleError runs only when the location request fails, printing error.message so the user is not left guessing.

The same coordinates can drop a pin on a map, sort a list of stores by distance, or auto-fill a delivery address. The pattern is always the same: get the coordinates in the success callback, then pass them to whatever needs them.

⚠️ Common Mistakes to Avoid

Mistake Problem Solution
Skipping the error callback Code goes silent when permission is denied Always pass a second callback to handle errors
Expecting the location without permission The user must say yes first; you cannot force it Wait for the success callback before using coordinates
Testing on an http page The API is blocked outside a secure context Use https or localhost
Treating it as synchronous getCurrentPosition returns nothing right away Read the coordinates inside the success callback

🔧 Try It Yourself!

  1. Check that "geolocation" in navigator is true before calling the API.
  2. Call getCurrentPosition with a success callback that logs latitude and longitude.
  3. Add an error callback that prints a friendly message when permission is denied.
  4. Deny the location request on purpose and confirm your error callback runs.

🧩 What You’ve Learned

  • navigator.geolocation.getCurrentPosition(success, error) requests the user’s location
  • ✅ The success callback receives a position object with position.coords.latitude and position.coords.longitude
  • ✅ The browser asks the user for permission before sharing the location
  • ✅ The error callback handles a denied permission or a failed lookup
  • ✅ The API only works in a secure context: https or localhost

🚀 What’s Next?

Now that you can read the user’s location, let’s move on to organizing your code with reusable blueprints. Let’s continue to Classes.

Share & Connect