Skip to content Skip to sidebar Skip to footer

wants to know your location what javascript uses it

Christian Nwamba JS preacher. Developer 🥑. Edifice the web with the community @concatenateConf @forLoopAfrica. JS and Senior Advancement for the Next Billion Users through Microsoft.

Detect location and local timezone of users in JavaScript

7 min read 2129

Detecting the location of your users can be actually useful if you desire to personalize your user's feel when they scan through your website.

Desire to evidence 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 utilise cases for detecting user location. It tin can also be to limit access to your website to either remain compliant or if you lot but do not yet cater to sure locations.

We will explore the various ways we tin get location equally well as their timezone (specially if y'all intend to send a lot of emails or generate a lot of reports for them).

Prerequisites

  1. Bones knowledge of JavaScript

Options for detecting location

In that location are two very pop ways to find a user's location in the browser directly:

  1. Using Geolocation API
  2. Looking up IP Accost

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

Yet, in a scenario where you desire to format the content displayed to the user earlier information technology gets rendered, this isn't exactly ideal. Too, the Geolocation API may not piece of work depending on the user browser permission settings.

To use the Geolocation API, yous can do the post-obit:

// Excerpt from https://developer.mozilla.org/en-The states/docs/Spider web/API/Geolocation_API function geoFindMe() {   if (!navigator.geolocation){    panel.log("Geolocation is not supported by your browser");     return;   }   function success(position) {     var latitude  = position.coords.latitude;     var longitude = position.coords.longitude;     reverseGeocodingWithGoogle(longitude, latitude)   }   function error() {     panel.log("Unable to retrieve your location");   }   navigator.geolocation.getCurrentPosition(success, fault); }

Information technology first checks that the browser has/supports Geolocation API. If it does, it executes the remainder 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 lot can put into Google maps to go the exact user location.

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

function reverseGeocodingWithGoogle(latitude, longitude) {   fetch(`https://maps.googleapis.com/maps/api/geocode/json?       latlng=${latitude},${longitude}&key={GOOGLE_MAP_KEY}`)   .and so( res => res.json())   .so(response => {       console.log("User's Location Info: ", response)    })    .catch(status => {       panel.log('Asking failed.  Returned status of', status)    }) }

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

Looking up IP Addresses This is past far the most common mode of detecting user location. Different Geolocation IP, it can only give you express information similar Country and maybe City, depending on the IP lookup provider you lot are using.

Here is a simple lookup:

fetch('https://extreme-ip-lookup.com/json/') .then( res => res.json()) .and so(response => {     console.log("Country: ", response.country);  })  .catch((data, status) => {     console.log('Request failed');  })

This works by making a asking to the https://extreme-ip-lookup.com/json/ URL from the user'due south browser, and then that their location is detected. This resources provides country, city, time zone, longitude, and breadth among other things.

With a single query, y'all can tell which country a user is in and get their timezone. How convenient.

Many times, the information provided by IP lookup might exist all yous need. In that case, there would exist no need getting the exact coordinates to pinpoint the user's exact location in their city.

Here is a list of other places to check out when performing IP lookup:

Empathize that IP lookup mostly gives y'all accurate information about country and timezone of the originating request. The city may be the location of the your Internet access provider. If you intend to get the exact urban center or region of a user, you lot should apply 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, yous could easily create a date object and send to your server and shop that time. All the same, information technology comes with a lot of challenges as you accept to worry about doing internal calculations and not having them go off. This is why information technology is more than important to fetch the user timezone above everything else.

As y'all saw to a higher place, nosotros can detect timezone from IP address lookup. All you accept 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 nigh recent version.

Beneath is a quick example of how information technology works:

<div id="gauge"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/two.22.ii/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script> <script>   certificate.getElementById('judge').innerText = moment.tz.guess(); </script>

When you lot load the folio, it shows you your current timezone. Create a index.html file and open the file in a browser. Copy the above lawmaking into the file and save it. Then refresh the browser tab you lot only opened. Absurd right?

MomentTz uses Intl API which is a congenital-in JavaScript internationalization API. It also has its data depository financial institution information technology checks the consequence of the Intl API against to provide more than authentic data. It too requires you lot to have included Moment.js earlier information technology can work.

Jstz package

Jstz is a unproblematic lighter package for detecting timezone. I say lighter in comparison with Moment.js. Information technology also makes utilise of the Intl API, so you can be confident of its results. To use the parcel, yous tin can grab the CDN equally follows:

<div id="guess"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/one.0.half dozen/jstz.min.js"></script> <script>   document.getElementById('guess').innerText = jstz.determine().name(); </script>

What y'all tin can notice from these libraries used for detecting timezone is that they practice not require any network calls from your end. This means if you intend to but selection user timezones, you may not demand to exercise IP lookups. And that's good considering they tin get expensive as y'all're paying for every telephone call to the API.

Intl API itself

Don't detest me, but let'due south confront information technology, if I showed you this, y'all may accept ignored the rest of this commodity lol.

Ok, then hither is how to use it:

<div id="judge"></div> <script>   certificate.getElementById('guess').innerText = Intl.DateTimeFormat().resolvedOptions().timeZone; </script>

Before you become like "Wow!!!", understand that the packages highlighted above take a lot into consideration when detecting timezones. This makes them slightly more than authentic than Intl API lonely. You may never discover the difference, but information technology feels good knowing someone's got your dorsum.

Magic App

"Talk is inexpensive. Show me the code." or so the saying goes. Let's get one meliorate and build a really simple app that detects a user'southward location and time zone information, and tell them what the time would be like in 3 other time zones around the earth.

Here is what the simple application looks similar:

Hither is the how nosotros pieced the code together to achieve that: Place information technology in a file named index.html

<!-- index.html --> <!doctype html> <html course="no-js" lang=""> <head>     <meta charset="utf-8">     <meta http-equiv="x-ua-compatible" content="ie=border">     <championship>Magic App</championship>     <meta proper noun="description" content="Magic App">     <meta name="viewport" content="width=device-width, initial-scale=1">     <link rel="stylesheet" href="index.css"> </head>  <torso>     <h1>Magic App Here</h1>     <div id="main">         <div id="time" class="sub">             <div>                 <h2>Your local time</h2>                 <span form="local"></bridge>             </div>             <div>                 <h2>Magic App Server Time</h2>                 <bridge class="server"></span>             </div>         </div>         <div id="location" class="sub">             <h2>And you are in...</h2>             <div class="accost"></div>         </div>     </div>     <!-- Script here --> </body> </html>

Create the alphabetize.css file and add together the following:

/*index.css*/ h1 {   text-align: eye } #principal {   max-width: 900px;   display: table;   margin-left: 30vw;   margin-acme: 10vh; }  #chief .sub {   brandish: block;   float: left;   min-width: 300px;   min-height: 300px;   border: 0.5px solid #bbb;   border-radius: 4px;   padding: 15px; } #chief .sub h2{   font-size: 20px; } #chief #fourth dimension {   margin-correct: 5vw; }  #principal #time div {   display: block;   min-height: 120px; }

This is probably the most unproblematic application you may have e'er seen. We are not doing annihilation fancy, just going straight to the point. Standard HTML and CSS, that'southward all.

At present, allow's add together the JavaScript that brings all of these to life: Add together the following to index.html

[...] <script src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.6/jstz.min.js"></script> <script>   document.addEventListener("DOMContentLoaded", office(upshot) {       // The main sauce here   }); </script> [...]

Nosotros take laid the foundation for what is to come. The first thing we desire to practice is find if the browser has/supports the Geolocation API:

[...] document.addEventListener("DOMContentLoaded", function(event) {   if (!navigator.geolocation){     panel.log("Geolocation is not supported past your browser");     ipLookup();   } else {     navigator.geolocation.getCurrentPosition(success, error);   }   // More sauce hither }); [...]

Now, we get to execute our lawmaking if Geolocation API is bachelor/accessible. If it is not, we just fall back to IP Lookup like we saw above.

Let'south create the success, fault and ipLookup methods:

[...] document.addEventListener("DOMContentLoaded", function(event) {   [...]   part success(position) {     var latitude  = position.coords.latitude;     var longitude = position.coords.longitude;     reverseGeocodingWithGoogle(longitude, latitude)   }   function mistake() {     console.log("Unable to retrieve your location");   }   part ipLookup() {     fetch('https://farthermost-ip-lookup.com/json/')     .then( res => res.json())     .then(response => {         fallbackProcess(response)     })     .catch((data, status) => {         console.log('We could not find your location');     })   }     // More sauce hither }); [...]

We take already seen how these work higher up, then I'm going to skip explaining what each does. Let's add together the reverseGeocodingWithGoogle method now:

[...] document.addEventListener("DOMContentLoaded", function(effect) {   [...]   role reverseGeocodingWithGoogle(latitude, longitude) {     fetch(`https://maps.googleapis.com/maps/api/geocode/json?       latlng=${breadth},${longitude}&key={GOOGLE_MAP_KEY}`)     .so( res => res.json())     .then(response => {       processUserData(response)     })     .grab(condition => {       ipLookup()     })   }   // Fifty-fifty more sauce hither }); [...]

You may have noticed that I introduced 2 new functions processUserData and fallbackProcess. These are only to keep things clean and reusable. Allow's at present add together the both of them:

[...] document.addEventListener("DOMContentLoaded", function(event) {   [...]   function processUserData(response) {     var address = certificate.querySelector('.accost')     address.innerText = response.results[0].formatted_address   }      function fallbackProcess(response) {     var address = document.querySelector('.accost')     address.innerText = `${response.metropolis}, ${response.country}`   }   // timezone sauce here }); [...]

Yous run across the methods only perform assignments and null likewise complex. For the address variable, I should ordinarily define it in the global scope, but I brought it into the function and then yous would not miss it. This is not the best way to reuse code.

Now, let'southward detect timezone:

[...] document.addEventListener("DOMContentLoaded", function(issue) {   [...]   var localTime = jstz.make up one's mind().name();   var serverTime = "Asia/Novosibirsk";   document.querySelector('.server').innerText = new Date().toLocaleString("en-U.s.a.", {timeZone: serverTime});   certificate.querySelector('.local').innerText = new Date().toLocaleString("en-US", {timeZone: localTime}); }); [...]

And that completes our magic app. Hither is a link to the projection on codepen.

Observe Timezone and Location in JavaScript

document.addEventListener("DOMContentLoaded", role(event) { var accost = document.querySelector('.address') if (!navigator.geolocation){ panel.log("Geolocation is non supported by your browser"); ipLookup(); } else { navigator.geolocation.getCurrentPosition(success, error); } function success(position) { var latitude = position.coords.breadth; var longitude = position.coords.longitude; reverseGeocodingWithGoogle(longitude, breadth) } function fault() { console.log("Unable to retrieve your location"); } function ipLookup() { fetch('https://farthermost-ip-lookup.com/json/&#8217;) .then( res => res.json()) .and so(response => { fallbackProcess(response) }) .catch((data, status) => { address.innerText = 'Nosotros could non find your location' }) } function reverseGeocodingWithGoogle(latitude, longitude) { fetch(`https://maps.googleapis.com/maps/api/geocode/json?

Decision

I hope this article has been useful to y'all. I promise information technology helps you improve your user experience and to build a more internationalized application with JavaScript.

Ane concluding thing that tin can come in handy would be to get a DateTime string in a particular timezone using JavaScript. Non to worry, I got you lot. Here is the simple line of lawmaking you need:

new Engagement().toLocaleString("en-US", {timeZone: "TIMEZONE_STRING_HERE"})

Share your experiences using these tools, let's all larn together.

LogRocket: Debug JavaScript errors more than easily by understanding the context

Debugging code is always a deadening task. But the more y'all understand your errors the easier it is to fix them.

LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to requite you the ability to find out exactly what the user did that led to an fault.

LogRocket Dashboard Free Trial Banner

LogRocket records console logs, page load times, stacktraces, ho-hum network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the bear on of your JavaScript code will never be easier!

Try it for gratis.

moffittdiewhou.blogspot.com

Source: https://blog.logrocket.com/detect-location-and-local-timezone-of-users-in-javascript-3d9523c011b9/

Post a Comment for "wants to know your location what javascript uses it"