How to get a user's location with JavaScript
Tags: javascript, webapis, geolocation, api
Published: 2020-03-10 17:40:00

---
title: How to get a user's location with JavaScript
published: true
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/gt4zcx8gymahas4861wu.jpg
description: Using the Geolocation API and a 3rd party Geocoding service we can find out where current user is.
tags: javascript, web apis, geolocation, API
---

*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.


```javascript
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.

```javascript
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.

```javascript
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:

```javascript
{
  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.

```javascript
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.

```javascript
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:

```javascript
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](https://youtu.be/Xd43hZKaUS0).