loading...
Cover image for How to get a user's location with JavaScript

How to get a user's location with JavaScript

codebubb profile image James Bubb ・2 min read

This article was originally a video tutorial on my YouTube channel which you can see here: https://youtu.be/Xd43hZKaUS0

So let's say you have some need to get the location of the current user of your web page or app.

Maybe you have some need to show them their location (like Google does at the bottom of search pages) or adjust the content for them depending on where they are.

You can retrieve the user's current position using the Geolocation Web API.

Gelocation API

On the window object inside the browser there is a property called navigator which is itself an object that contains a further property called geolocation which again is another object.

if (window.navigator.geolocation) {
 // Geolocation available
} 

It might be worth wrapping your code in an if statement as not all browsers will support the Geolocation Web API

If the browser supports it, you can request the user’s location from the Geolocation API using the getCurrentPosition function.

window.navigator.geolocation
  .getCurrentPosition(console.log, console.log);

I say 'request' it as the user has to confirm that they want to give your website/app permission to lookup your location.

Get current position

The getCurrentPosition function takes two arguments.

These are the callback functions to be performed when there is a successful geolocation lookup or a failure.

getCurrentPosition(successCallback, failureCallback);

If the user gives consent (by clicking an acceptance in a popup you’ll get back an object in the success callback that has the user’s longitude and latitude values.

The result looks a bit like this:

{
  coords = { 
    latitude: 51.4554803,
    longitude: -2.0843058,
    altitude: null,
    accuracy: 49,
    altitudeAccuracy: null,
    heading: null,
    speed: null,
  },
  timestamp: 1583860898576
}

These aren’t much use on their own if you’re looking to identify the user’s location in a human readable format so you’ll need to use a Geocoding service to translate these to real locations.

Geocoding

There are several Geocoding providers. For the tutorial I used opencagedata.com (free but an account and API key are required for requests) to translate the longitude and latitude values.

If you're using Opencagedata, once you have your API and account keys, you can create a function like this to be used for the success callback.

const successfulLookup = position => {
  const { latitude, longitude } = position.coords;
  fetch(`https://api.opencagedata.com/geocode/v1/json?q=${latitude}+${longitude}&key=1234`)
    .then(response => response.json();
    .then(console.log); // Or do whatever you want with the result

Then you can simply plugin that in to the getCurrentPosition function.

window.navigator.geolocation
  .getCurrentPosition(successfulLookup, console.log);

The response you get back will have lots of metadata attached but there is a results array which should just give you back one item that has details of the location.

You can access the 'formatted' version of your user's location from:

results[0].formatted; // Gives something like '54, My street, My Town, My Post Code, My Country

And there is also a components property inside each item in the results array that gives you direct access to each part of the location.

Enjoy!

If you want to see an example, feel free to watch the tutorial for more details.

Discussion

pic
Editor guide
 

Great work!

A drawback requiring permission to share visitors' locations with your site. In case of negative response you have no way to get the user's location.
Please check out my article I've published recently "How to detect the location of your website's users with Javascript for free?"