Getting the user's location with JavaScript

Getting the user's location with JavaScript

In this tutorial I will show you how to get the user's location with the JavaScript Geolocation API.

You can use it to redirect them to a site in their language or on sites such as a News or Weather App and use their location to adjust the home page to show content relevant for where they are.

This article was originally a video tutorial, which you can check out here:

Checking if the navigator API is available

The geolocation functions are part of the window object can be accessed with window.navigator.geolocation or simply navigator.geolocation.

Some older browsers may not have support for the geolocation API, so you should use an if statement to check if it exists before using it:

if (navigator.geolocation) {
    /* use the API here */
}

Getting the user's coordinates

If your browser supports the API, you can use its methods. The method to get the user's coordinates is navigator.geolocation.getCurrentPosition.

It requires as parameters, a success callback and optionally an error callback and options.

To test it out, we can use console.log as the the success callback function and console.error as the error callback.

One of these two functions will get called depending on whether the call is successful or not.

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

The user will be prompted to allow the site to access their location the first time this is used.

Once permission is granted, you should see something like this in the JavaScript console:

/* GeolocationPosition */
{
    /* GeolocationCoordinates */
    "coords": {
        "accuracy": 1000,
        "altitude": null,
        "altitudeAccuracy": null,
        "heading": null,
        "latitude": 39.7501,
        "longitude": -104.9957,
        "speed": null
    },
    "timestamp": 1608826371767
}

You will have a GeolocationPosition object containing a GeolocationCoordinates object labeled as coords and a timestamp.

Success function

Instead of using console.log, you can use a custom success callback to do exactly what you need to with the data.

function success(data) {
    // extracting the latitude and longitude from the data
    let latitude = data.coords.latitude;
    let longitude = data.coords.longitude;
    alert("Your location: " + latitude + ", " + longitude);
}

if (navigator.geolocation) {
    window.navigator.geolocation
        .getCurrentPosition(success, console.error);
}

This will tell the getCurrentPosition function to call success when it successfully looks up the location and send it the Geolocation Position as the parameter.

The success function above will extract the latitude and longitude and make a popup telling it to the user.

What if you want to know their city or country?

If you want to know where your user is located in a more meaningful way, you can look that up using a reverse geocoding API.

There are many APIs available to do this. For this tutorial, I used the OpenCage API.

Create a free account at opencagedata.com and get an API key to use with your application.

You can find a code snippet for reverse geocoding with OpenCage in their JavaScript documentation.

We can simplify it using modern JavaScript techniques:

  let apikey = "your API key goes here";
  let latitude = '51.0';
  let longitude = '7.0';

  fetch('https://api.opencagedata.com/geocode/v1/json'
    + '?'
    + 'key=' + apikey
    + '&q=' + encodeURIComponent(latitude + ',' + longitude)
    + '&pretty=1'
    + '&no_annotations=1')
   .then((response) => response.json())
   .then((data) => alert(data.results[0].formatted));

Assuming you have a valid API key from OpenCage, the snippet above should make an alert that says "Grüner Kuhweg, 51061 Cologne, Germany". That is the location for the coordinates 51.0, 7.0.

If you log data.results[0] in the console, you will see there are a few fields in addition to just the formatted address that you can access:

{
  "bounds": {
    "northeast": {
      "lat": 51.0008597,
      "lng": 7.0042934
    },
    "southwest": {
      "lat": 50.9973232,
      "lng": 6.999946
    }
  },
  "components": {
    "ISO_3166-1_alpha-2": "DE",
    "ISO_3166-1_alpha-3": "DEU",
    "_category": "road",
    "_type": "road",
    "city": "Cologne",
    "city_district": "Mülheim",
    "continent": "Europe",
    "country": "Germany",
    "country_code": "de",
    "political_union": "European Union",
    "postcode": "51061",
    "road": "Grüner Kuhweg",
    "road_type": "service",
    "state": "North Rhine-Westphalia",
    "state_code": "NW",
    "suburb": "Flittard"
  },
  "confidence": 9,
  "formatted": "Grüner Kuhweg, 51061 Cologne, Germany",
  "geometry": {
    "lat": 50.999559,
    "lng": 7.0002524
  }
}

Accessing specific components

You can access any component of the returned JSON object.

To access the user's city, we can say data.results[0].components.city.

To get their country, we can say data.results[0].components.country.

Reverse geocoding the user's location

Now that we can access the user's coordinates and reverse geocode coordinates, we can put it all together:

function reverseGeocode(latitude, longitude) {
    let apikey = "your API key goes here";

    fetch('https://api.opencagedata.com/geocode/v1/json'
        + '?'
        + 'key=' + apikey
        + '&q=' + encodeURIComponent(latitude + ',' + longitude)
        + '&pretty=1'
        + '&no_annotations=1')
     .then((response) => response.json())
     .then((data) => alert(data.results[0].formatted));
}

function success(data) {
    // extracting the latitude and longitude from the data
    let latitude = data.coords.latitude;
    let longitude = data.coords.longitude;
    // reverse geocode
    reverseGeocode(latitude, longitude);
}

if (navigator.geolocation) {
    window.navigator.geolocation
        .getCurrentPosition(success, console.error);
}

The alert function at the end of the reverseGeocode call can be replaced with any function you need to use the data for.

In my video, Getting the user's location with JavaScript, I show how this can be used in a weather app to display weather for the user's current location.

Conclusion

I hope you found this tutorial useful.

Check out the video for further explanations and be sure to like and subscribe!

- Jonah Lawrence

Twitter: @DenverCoder1

YouTube: Jonah Lawrence - Dev Pro Tips