Nathan Pasko

Nathan Pasko Facts


1 serving per container

Serving size

5ft 8in


Amount per serving

Calories

421


% Daily Value*


Designer/Developer

34%



Web

24%



Games/Toys

17%







* 

Nathan Pasko is a designer, developer & musician. The % Daily Value tells you how much an aspect of Nathan contributes to a daily diet. 2,000 calories in a day is used for general nutrition advice.

How to Check a User's Location with JavaScript

January 24, 2021

This little series is all about expanding our definition of "responsive design" to consider more than just screen size. Last time we talked about using CSS media queries to automatically shift between light and dark display modes. Today, let's talk about another part of the environment we can respond to: the user's location.

Location-Based Responsiveness

Responsiveness is all about embracing the context that surrounds our users and their devices. The most urgent responsive concerns are undoubtedly the wide variety of screen sizes that those devices might employ, but there's a lot more context beyond screen size that designers can respond to. What if our responsive designs could respond not just to screen size, but to the user's location as well?

Geolocation

To achieve this, we can use the Geolocation API. This API is available only in secure contexts—HTTPS—in some supporting browsers, and yet it provides a super easy way to read a device's location. Today we'll look at two different geolocation approaches: one to check location a single time, and one to watch location continuously.

How to Get the User's Location Once

Let's start with a blank HTML page to try getting device location. We'll just add a button that will trigger the location check. Something like this:

<button id="get-location">Get Location</button>

We want to be able to click this button and get location data in the console. To achieve this, we'll write three JavaScript functions. The first is the function we'll stick to our button via event listener. We can access the Geolocation API at navigator.geolocation. Inside our first function, we'll check whether the Geolocation API is supported by testing navigator.geolocation, and if it is supported, we can get our location data using navigator.geolocation.getCurrentPosition().

function getLocation() {
  if (!navigator.geolocation) {
    console.log('Geolocation API not supported by this browser.');
  } else {
    console.log('Checking location...');
    navigator.geolocation.getCurrentPosition(success, error);
  }
}

The Geolocation API provides getCurrentPosition() so we can quickly locate users. This function will get the job done quite easily, but you might have noticed that it expects two arguments, called success and error in this example. These are the two other functions we need to write.

The first argument should be a function to call if geolocation is successful. We need to carve out an argument in this function, too; this argument is called position and it's how the browser will pass the geolocation results back to us.

function success(position) {
  console.log(position);
}

The error() function will only be called if the geolocation fails. Hopefully we won't even hit this function.

function error() {
  console.log('Geolocation error!');
}

Don't forget to attach getLocation() to the button by adding a click event listener!

document.getElementById('get-location').addEventListener('click', getLocation);

Now we have all the JavaScript we need to grab some location data. If we try it out by clicking the Get Location button, it'll ultimately result in a GeolocationPosition object being printed in the console. This object is a packet of the results from our geolocation check. Its keys include a timestamp and another object called coords that contains data like latitude, longitude, and so on. The data found in coords is what we can work with to create a responsive design that consider's the user's location.

We can use the console to poke around the coords object or we can directly log values from coords to the console in success().

function success(position) {
  console.log('Latitude:', position.coords.latitude);
  console.log('Longitude:', position.coords.longitude);
}
Note!
Latitude traditionally precedes longitude. If you explore location APIs on the web you might see latitude and longitude out of order, but just remember they should usually appear in alphabetical order!

How to Continuously Watch the User's Location

Instead of getting the user's location once, we can also watch their location continuously. Using the watchPosition() function we can set up a handler function that will be called each time geolocation updates. We need to pass in a function to call when a new location is successfully returned, so let's reuse our success() function.

This example is pretty easy to set up for our purposes. We can just add one line of JavaScript:

navigator.geolocation.watchPosition(success);

Now we can continuously get location data! This comes with the processing, data, and energy overhead that you'd expect, but maybe you're as pleased as I was to learn how simple it is to start working with the Geolocation API.

A Word of Caution

This series offers practical examples illustrating how to add different kinds of responsiveness, but it's also a conversation starter; a brain teaser. It's worthwhile to look at a user's location as part of the context they bring to our app or website, especially as a mental exercise, but devices will need to get permission to check location, and this will prove a UX wrinkle.

It's really not a good idea for our users to be faced with a dialog in the browser immediately upon arriving at our site, however the kind of location-based responsiveness that we used as an example above will trigger those dialogs to get permissions for the location check. That's not ideal. Putting this stuff into practice will require a more thoughtful approach, or at least the deferral of location responsiveness away from the initial landing experience. Nevertheless, I think you'll find the expansion of the commonly held definition of responsiveness to include location is an exciting addition to your web design playbook.

© 2024 Nathan Pasko