Emmanuel Akinfulubi

JavaScriptEvents

Get the user's location with Geolocation API in JavaScript

Intermediate · 5 min read

Maps, ride-hailing apps, weather sites and "find a store near you" pages all start by asking where you are. Browsers can tell them, through the Geolocation API, but only if the user says yes. Many people say no, so handling a refusal well is just as important as reading the position.

In this tutorial you will ask for the user's location, show their latitude and longitude, explain each kind of failure in plain words, and wrap the API in a promise so the rest of your code can use await. You should know what a callback is (a function you pass to another function, to be called later) and have seen async and await.

How the API looks

The API lives at navigator.geolocation. Its main method takes up to three arguments:

  • a success callback, called with a position object if it works,
  • an error callback, called with an error object if it doesn't,
  • an options object, such as { timeout: 5000 }.

It does not return a promise. It reports back through the callbacks, which is the older style many browser APIs still use.

Permission

The first time a page asks, the browser shows the user a prompt. If they refuse, the browser remembers, and later requests fail straight away without asking again. Only the user can change that, in the browser's site settings. The API also only works on secure pages: https addresses and localhost, not plain http.

For this lesson, navigator.geolocation is a stand-in that reports a position in Lagos, so the examples work without a real prompt.

Here is the exercise. Try it yourself first, or read on and we will build it together.

19 Read the current location

fair

Use the Geolocation API to report where the user is. Handle refusal, since it is the most likely outcome.

Stuck? Three hints, smallest first
  1. 1. getCurrentPosition(success, error, options) is callback-based, not a promise.
  2. 2. The error object has a numeric code: 1 denied, 2 unavailable, 3 timed out.
  3. 3. It needs a secure context, and permission is asked once. Refusal is permanent until the user changes it.

Step 1: check the API is there

Step 1

console.log('geolocation' in navigator); // true

'geolocation' in navigator asks whether the property exists. In an old browser, or a restricted environment, it might not, and you'd want to say so instead of crashing.

Step 2: show the position

Step 2

const describe = (position) => {
  const { latitude, longitude, accuracy } = position.coords;
  return `latitude ${latitude.toFixed(4)}, longitude ${longitude.toFixed(4)}, accurate to about ${Math.round(accuracy)}m`;
};
navigator.geolocation.getCurrentPosition((position) => {
  console.log(describe(position)); // latitude 6.5244, longitude 3.3792, accurate to about 18m
});

The position object has a coords property holding the numbers. latitude and longitude are in degrees, and accuracy says roughly how many meters off the position might be. toFixed(4) shows four decimal places, and Math.round turns the accuracy into a whole number.

Step 3: explain each failure

When it fails, the error callback gets an object with a numeric code:

  • 1 means permission was denied.
  • 2 means the position isn't available (for example, no signal).
  • 3 means it took longer than the timeout option allowed.

Bare numbers are hard to read, so give them names:

Step 3

const PERMISSION_DENIED = 1;
const POSITION_UNAVAILABLE = 2;
const TIMEOUT = 3;
const explain = (error) => {
  if (error.code === PERMISSION_DENIED) return 'You refused permission. Nothing more can be done from here.';
  if (error.code === POSITION_UNAVAILABLE) return 'Your position is not available right now.';
  if (error.code === TIMEOUT) return 'It took too long. Try again.';
  return `Something went wrong: ${error.message}`;
};
console.log(explain({ code: 1, message: 'User denied Geolocation' })); // You refused permission. Nothing more can be done from here.
console.log(explain({ code: 3, message: 'Timeout expired' }));         // It took too long. Try again.

In a browser, the error object also carries these names itself, so error.PERMISSION_DENIED is 1 too. The full solution's stand-in keeps them on its pretend geolocation object instead, which is why its explain takes that object as a second argument. A real navigator.geolocation doesn't have them, so in your own code use the error or your own names, as above.

The error isn't an Error like the ones throw creates. It's an object with code and message, and no stack.

Step 4: always pass the error callback

If you leave out the error callback and the user refuses, nothing happens. No error appears, the success callback never runs, and your page waits forever. Always pass both:

Step 4

const refusing = {
  getCurrentPosition: (onSuccess, onError) => onError({ code: 1, message: 'User denied Geolocation' }),
};
refusing.getCurrentPosition(
  (position) => console.log(describe(position)),
  (error) => console.log(explain(error)), // You refused permission. Nothing more can be done from here.
);

refusing is a pretend geolocation that always says no, a handy way to test the failure path without clicking "Block" in a real prompt.

Step 5: wrap it in a promise

Callbacks get awkward when one step depends on another. Wrapping the API once in a promise lets the rest of your code use await:

Step 5

const locate = (geo, options = {}) =>
  new Promise((resolve, reject) => geo.getCurrentPosition(resolve, reject, options));
const refusing = {
  getCurrentPosition: (onSuccess, onError) => onError({ code: 1, message: 'User denied Geolocation' }),
};
const position = await locate(navigator.geolocation);
console.log(position.coords.latitude); // 6.5244
try {
  await locate(refusing);
} catch (error) {
  console.log(error.code); // 1
}

new Promise hands you two functions: resolve for success and reject for failure. Passing them straight in as the two callbacks connects the API to the promise. A refusal now arrives as a rejected promise, which try/catch handles.

Ask at the right moment

Because a refusal is permanent, don't ask the moment the page loads, before the user knows why. Ask when they press a button like "Find stops near me", so the prompt makes sense to them. And when they refuse, say so and carry on. Asking again is pointless.

The full solution

The full solution uses four stand-in geolocation objects, one that succeeds and one for each failure code, so every path is checked. Its checks confirm a granted request reports the coordinates and accuracy, each code gets its own message, the success callback never runs on failure, leaving out the error callback throws nothing, the promise wrapper resolves and rejects with the code, and the error isn't an Error instance. Press Run. In the live demo, the first two buttons use stand-ins, and the third calls the real API.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const out = el('pre', { id: 'out' }, 'not asked yet');
document.body.appendChild(out);

const describe = (position) => {
  const { latitude, longitude, accuracy } = position.coords;
  return `latitude ${latitude.toFixed(4)}, longitude ${longitude.toFixed(4)}, accurate to about ${Math.round(accuracy)}m`;
};

// The codes are numbers, not names. Compare against the named constants on the
// geolocation object rather than writing 1, 2, 3 in your own code.
const explain = (error, geo) => {
  if (error.code === geo.PERMISSION_DENIED) return 'You refused permission. Nothing more can be done from here.';
  if (error.code === geo.POSITION_UNAVAILABLE) return 'Your position is not available right now.';
  if (error.code === geo.TIMEOUT) return 'It took too long. Try again.';
  return `Something went wrong: ${error.message}`;
};

// Callback-based, so wrapping it in a promise is usually the first thing you do.
const locate = (geo, options = {}) =>
  new Promise((resolve, reject) => geo.getCurrentPosition(resolve, reject, options));

const granted = makeGeolocation({ kind: 'success', latitude: 6.5244, longitude: 3.3792, accuracy: 18 });
const denied = makeGeolocation({ kind: 'error', code: 1, message: 'User denied Geolocation' });
const unavailable = makeGeolocation({ kind: 'error', code: 2, message: 'Position unavailable' });
const timedOut = makeGeolocation({ kind: 'error', code: 3, message: 'Timeout expired' });

let shown = '';
granted.getCurrentPosition((p) => { shown = describe(p); out.textContent = shown; });
console.log('granted     :', shown);

for (const [name, geo] of [['denied', denied], ['unavailable', unavailable], ['timed out', timedOut]]) {
  let message = '';
  geo.getCurrentPosition(() => {}, (e) => { message = explain(e, geo); });
  console.log(name.padEnd(12), ':', message);
}

// Omitting the error callback: the real API just does nothing.
let ranAnyway = false;
denied.getCurrentPosition(() => { ranAnyway = true; });
console.log('no error callback, success handler ran?', ranAnyway, '<- silently nothing');

// The promise wrapper.
const position = await locate(granted);
console.log('promise-wrapped:', position.coords.latitude);
let caught = null;
try { await locate(denied); } catch (e) { caught = e.code; }
console.log('rejection code :', caught);

Output


      
15 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 15 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

15 checks

test('a granted request reports coordinates', shown, 'latitude 6.5244, longitude 3.3792, accurate to about 18m');
test('the latitude is a number', typeof position.coords.latitude, 'number');
test('accuracy is reported in metres', position.coords.accuracy, 18);
test('a refusal is code 1', denied.PERMISSION_DENIED, 1);
test('and gets its own message', (() => { let m = ''; denied.getCurrentPosition(() => {}, (e) => { m = explain(e, denied); }); return m; })(), 'You refused permission. Nothing more can be done from here.');
test('unavailable is code 2', unavailable.POSITION_UNAVAILABLE, 2);
test('with a different message', (() => { let m = ''; unavailable.getCurrentPosition(() => {}, (e) => { m = explain(e, unavailable); }); return m; })(), 'Your position is not available right now.');
test('a timeout is code 3', timedOut.TIMEOUT, 3);
test('and is told apart from a refusal', (() => { let m = ''; timedOut.getCurrentPosition(() => {}, (e) => { m = explain(e, timedOut); }); return m; })(), 'It took too long. Try again.');
test('the three codes are distinct', new Set([1, 2, 3]).size, 3);
test('the success callback does not run on failure', ranAnyway, false);
test('omitting the error callback throws nothing', typeof ranAnyway, 'boolean');
test('the promise wrapper resolves on success', position.coords.longitude, 3.3792);
test('and rejects with the error code on failure', caught, 1);
test('the error is not an Error instance, just an object with a code', (() => { let e = null; denied.getCurrentPosition(() => {}, (err) => { e = err; }); return e instanceof Error; })(), false);

Adapted: a stand-in geolocation, controllable so all four outcomes are exercised rather than only the happy one. The demo's third button calls the real API with a 1ms timeout, so you can see a genuine browser response.

Geolocation is callback-based, which is why locate() wraps it in a promise — worth doing once at the boundary so the rest of your code can await.

The error is not an Error; it is a plain object with a numeric code, and the last assertion confirms instanceof Error is false — so error.message exists but error.stack does not, and nothing about it will look familiar in a catch block. Compare against PERMISSION_DENIED, POSITION_UNAVAILABLE and TIMEOUT rather than the bare numbers.

Two practical notes. Permission is asked once, and a refusal is permanent until the user changes it in browser settings, so there is no point re-asking — say what happened and move on. And the API needs a secure context: it works on https and on localhost, and is unavailable on plain http.

Common mistakes

  • Leaving out the error callback. A refusal then does nothing at all, and the page waits forever.
  • Asking on page load. Users refuse what they don't understand, and the refusal sticks. Ask after a clear action.
  • Comparing with bare numbers. error.code === 1 is hard to read. Give the codes names.

Try it yourself

  1. Put the result on the page: a "Where am I?" button that writes either the position or the explanation into a pre element.
  2. Pass { timeout: 1 } as the options to the real API and see which error you get.
  3. Use toFixed(2) instead of toFixed(4). Roughly how much less precise is the position?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.