JavaScript Geolocation API
Table of Contents + −
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.
navigator.geolocation.getCurrentPosition(onSuccess, onError);Let’s walk through this single line:
navigator.geolocationis the object the browser exposes for location features.getCurrentPositionis the method that kicks off the location request.onSuccessis the function the browser calls if it gets the location.onErroris 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.
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
getCurrentPositionand hands itonSuccessto run once the location is ready. onSuccessreceives thepositionobject the browser passes in.position.coords.latitudepulls out the north-south number, andposition.coords.longitudepulls out the east-west number.console.logthen 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.
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:
onSuccessruns when the location comes through, and it logs the latitude and longitude fromposition.coords.onErrorruns when the request fails, and it receives anerrorobject instead of a position.- Inside
onError, we compareerror.codetoerror.PERMISSION_DENIEDto check whether the user said no. - If it matches, we print a clear “you denied” message; otherwise we fall back to
error.messagefor any other problem. - The final line passes both callbacks to
getCurrentPositionso 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.
// ✅ Works: https://yourapp.com or http://localhost:3000// ❌ Blocked: http://yourapp.comThese comments sum up the rule:
- An
httpsaddress is trusted, so the API runs. localhostis treated as secure too, which lets you develop without a certificate.- A plain
httpaddress is not secure, so the browser blocks the call.
Before calling the API, it is good practice to confirm the browser supports it.
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 navigatorasks whether the browser actually has the feature.- If it does, the
ifbranch runs and callsgetCurrentPositionas usual. - If it does not, the
elsebranch 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.
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
ifconfirms support, then callsgetCurrentPositionwithshowWeatheras the success callback andhandleErroras the error callback. showWeatherdestructureslatitudeandlongitudeout ofposition.coordsin one line.- It drops those coordinates into a
urlstring for the weather service. fetch(url)sends the request, the first.thenturns the response into JSON, and the second.thenlogs the temperature fromdata.handleErrorruns only when the location request fails, printingerror.messageso 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!
- Check that
"geolocation" in navigatoristruebefore calling the API. - Call
getCurrentPositionwith a success callback that logslatitudeandlongitude. - Add an error callback that prints a friendly message when permission is denied.
- 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
positionobject withposition.coords.latitudeandposition.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:
httpsorlocalhost
🚀 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.