Skip to content

Instantly share code, notes, and snippets.

@christiannwamba
Created November 21, 2018 06:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christiannwamba/6024133c0a57f58740d2f0ad7df60710 to your computer and use it in GitHub Desktop.
Save christiannwamba/6024133c0a57f58740d2f0ad7df60710 to your computer and use it in GitHub Desktop.

Detect location and local timezone of users in JavaScript

Detecting location of your users can be really useful if you want to personalize your user’s experience when they browse through your website. Want to show a uniquely tailored promotion? Want to change the language of your site or design based on where your users are coming from?

These are some common use cases for detecting user location. It can also be to limit access to your website if you do not yet cater for certain locations. We will explore the various ways we can get location as well as their timezone (especially if you intend to send a lot of emails or generate a lot of reports for them).

Prerequisites

  1. Basic knowledge of JavaScript

Options for detecting location

There are two very popular ways to detect a user’s location in the browser directly:

  1. Using Geolocation API
  2. Looking up IP Address

Geolocation API Geolocation API allows you ask the user to share their present location with you. You can argue that it is the most trusted method for detecting location, as the user will tell you themselves.

However, in a scenario where you want to format the content displayed to the user before it get’s rendered, this no longer serves as an ideal situation. This is something to keep in mind. Also, the Geolocation API may not work depending on the user browser permission settings.

To use the Geolocation API, you can do the following: https://gist.github.com/72aade0182aed666df0d1b213fd729df

It first checks that the browser has/supports Geolocation API. If it does, it executes the rest of the code which includes a success and error callback function. The navigator.geolocation.getCurrentPosition(success, error) gives you the exact coordinates of the user, which you can put into Google maps to get the exact user location.

You can send a request to Google’s reverse Geocoding API. It would require getting an API key.

https://gist.github.com/d9747a1d6dbf64d69ed15427496fe89d

The downside of using this method is that if the user does not allow you to get their location, you cannot detect their position accurately, or you may not even detect it at all. Also, it only works on secure servers (https). It is not supported on Internet Explorer 10 and below and OperaMini.

Looking up IP Addresses This is by far the most common way of detecting user location. Unlike Geolocation IP, it can only give you limited information like Country and maybe City, depending on the IP lookup provider you are using.

Here is a simple lookup: https://gist.github.com/74c1fbdfc4309573431e4f4c8e0c07e2

This works by making a request to the https://extreme-ip-lookup.com/json/ URL from the user’s browser, so that their location is detected. This resource provides country, city, timezone, longitude and latitude among other things. With a single query, you can tell which country a user is in and also get their timezone. How convenient?

Many times, the information provided by IP lookup might be all you need. In that case, there would be no need getting the exact coordinates to pinpoint the user’s exact location in their city. Here is a list of other places to checkout when performing IP lookup:

Understand that IP lookup mostly gives you accurate information about country and timezone of the originating request. The city may be the location of the your ISP. If you intend to get the exact city or region of a user, you should use the Geolocation API and find ways to convince the user to share their location with you.

Getting local timezone of users in JavaScript

It is tempting to conclude “this is easy”. Well, you could easily create a date object and send to your server and store that time. However, it comes with a lot of challenges as you have to worry about doing internal calculations and not having them go off. This is why it is more important to fetch the user timezone above everything else.

As you saw above, we can detect timezone from IP address lookup. All you have to do is pick out the timezone from the response object along with the user location. Below, we will explore other ways of detecting timezone

Moment Timezone Moment Timezone has a function that guesses the timezone of a user. It is quite accurate, provided you are using the most recent version at all times. Below is a quick example of how it works: https://gist.github.com/416dc193e0804558dfb685f86806fee3

When you load the page, it show you your current timezone. Create a index.html file and open the file in a browser. Copy the above code into the file and save it. Then refresh the browser tab you just opened. Cool right?

MomentTz uses Intl API which is a built in JavaScript internationalization API. It also has it’s data bank it checks the result of the Intl API against to provide more accurate information. It also requires you have included Moment.js before it can work.

Jstz package Jstz is a simple lighter package for detecting timezone. I say lighter in comparison with Moment.js. It also makes use of the Intl API, so you can be confident of it’s results. To use the package, you can grab the CDN as follows: https://gist.github.com/ed19da16055fb85b6a123f67d94daca2

What you can notice from these libraries used for detecting timezone is that they do not require any network calls from your end. This means if you intent to only pick user timezones, you may not need to do IP lookups, which can get expensive as you will be expected to pay for the API when you make so many calls to it.

Intl API itself Don’t hate me, but let’s face it, if I showed you this, you may have ignored the rest of this article lol. Ok, so here is how to use it: https://gist.github.com/7dcfbda2b111724c2c9e1ac4cc49cffb

Before you go like “Wow!!!”, understand that the packages highlighted above take a lot into consideration when detecting timezones. This makes them slightly more accurate than Intl API alone. You may never notice the difference, but it feels good knowing someone’s got your back.

Magic App

“Talk is cheap… Show me your workings” or so the saying goes. However it goes, that is the least of our concerns at the moment. We are going to build a really simple app that would detect a user’s location and timezone information, and tell them what the time would be like in 3 other areas around the world.

Here is what the simple application will look like:

Here is the how we pieced the code together to achieve that: Place it in a file named index.html https://gist.github.com/8a5e5a4b7f3bfa106a8d92016411fd12

Create the index.css file and add the following: https://gist.github.com/0edc2529b5f15d8fb28e802507ce26d7

This is probably the most simple application you may have ever seen. We are not doing anything fancy, just going straight to the point. Standard HTML and CSS, that’s all.

Now, let’s add the JavaScript that brings all of these to life: Add the following to index.html https://gist.github.com/fcea1b2cd9a32e58b22320411a4a298b

We have laid the foundation for what is to come. The first thing we want to do is detect if the browser has/supports the Geolocation API: https://gist.github.com/6c4c29c6cb46ec85689428adfff7bb53

Now, we get to execute our code if Geolocation API is available/accessible. If it is not, we just fallback to IP Lookup like we saw above.

Let’s create the success, error and ipLookup methods: https://gist.github.com/00421d01d8b239d98d186b76407ef7d2

We have already seen how these work above, so I’m going to skip explaining what each does. Let’s add the reverseGeocodingWithGoogle method now: https://gist.github.com/4d3dc2e12d274e62305e3960b51128ae

You may have noticed that I introduced two new functions processUserData and fallbackProcess. These are just to keep things clean and reusable. Let’s now add the both of them: https://gist.github.com/fa57ebcc85bf22cd183430fa4634d2bd

You see the methods just perform assignments and nothing too complex. For the address variable, I should ordinarily define it in the global scope, but I brought it into the function so you would not miss it. This is not the best way to reuse code.

Now, let’s detect timezone: https://gist.github.com/4d73d457a31d094a336cf61ba555be3b

And that completes our magic app. Here is a link to the project on codepen. https://codepen.io/chiefoleka/full/WYjEOX/

Conclusion

I hope this article has been useful to you. I hope it helps you improve your user experience and to built a more internationalized application with JavaScript.

One last thing that can come in handy would be to get a datetime string in a particular timezone using JavaScript. Not to worry, daddy’s got you. Here is the simple line of code you need: https://gist.github.com/16c6070bfd98dd6996537fa0af98a62e

Share your experiences using these tools, let’s all learn together

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment