Detecting The Location of your Website’s Visitors with JavaScript

Detecting The Location of your Website’s Visitors with JavaScript

Detecting the location of your website’s users is useful for a variety of reasons. You might, for instance, want to display different content, perhaps in different languages for people from different countries, or display targeted information to visitors from different locations.

How To Detect The Location of Your Website’s Visitors Using JavaScript

Detecting the location of your website’s users is useful for a variety of reasons.

You might, for instance, want to display different content, perhaps in different languages for people from different countries, or display targeted information to visitors from different locations.

Whatever your reasons might be, you have two options:

  1. The Geolocation API
  2. IP address lookup
The Geolocation API

The geolocation API is a new HTML5 feature that allows a web page’s visitor to share their location with you if they so choose.

When you try to retrieve the location using this API, a prompt is shown to the user, asking them if they’d like to share their location with your site.

Example of the kind of prompt shown to the user

Obviously, this means that you won’t get the location if the user decides not to share their location with you.

if ("geolocation" in navigator) {
  // check if geolocation is supported/enabled on current browser
  navigator.geolocation.getCurrentPosition(
   function success(position) {
     // for when getting location is a success
     console.log('latitude', position.coords.latitude, 
                 'longitude', position.coords.longitude);
   },
  function error(error_message) {
    // for when getting location results in an error
    console.error('An error has occured while retrieving
                  location', error_message)
  }  
});
} else {
  // geolocation is not supported
  // get your location some other way
  console.log('geolocation is not enabled on this browser')
}

Drawbacks: It only works on secure servers (https). It is not supported on Internet Explorer 10 and below, nor OperaMini.

The output from the code only gives us the coordinates. What if you need the actual location, or get the address in words? We’ll talk about this after we discuss IP lookup.

IP Address Lookup

An IP address lookup is another way to get the location of your visitor. We usually use public IP lookup services/APIs for this option. Some of these are paid services and some are free.

Examples include IP Geolocation API, IPinfo, and GEOIP DB. They provide the data in various formats as well, such as JSON, XML and CSV. To get a good understanding of how to use this services, read their documentation.

I’ll be using IP Geolocation API for my example. I could use Vanilla JavaScript, but I won’t. It’s easier with libraries like jQuery.

function ipLookUp () {
  $.ajax('http://ip-api.com/json')
  .then(
      function success(response) {
          console.log('User\'s Location Data is ', response);
          console.log('User\'s Country', response.country);
      },

      function fail(data, status) {
          console.log('Request failed.  Returned status of',
                      status);
      }
  );
}
ipLookUp()

This as the output on my console:

Drawbacks: Although the country given by most IP lookup services is almost always accurate, the coordinates are not always accurate. Also, if you’re going to be make lots of requests, some of these services require that you get an API Key, and you may need to pay for the service.

You could use the IP lookup as an alternative or backup, for the geolocation API in browsers that don’t support geolocation, or tell you when an error occurs, like this:

if ("geolocation" in navigator) {
  // check if geolocation is supported/enabled on current browser
  navigator.geolocation.getCurrentPosition(
   function success(position) {
     // for when getting location is a success
     console.log('latitude', position.coords.latitude, 
                 'longitude', position.coords.longitude);
   },
 function error(error_message) {
    // for when getting location results in an error
    console.error('An error has occured while retrieving
                  location', error_message)
    ipLookUp()
 }
});
} else {
  // geolocation is not supported
  // get your location some other way
  console.log('geolocation is not enabled on this browser')
  ipLookUp()
}

Now that we have our location in one way or another, we’re going to convert the latitude and longitude we retrieved, to a more comprehensive address using the Google Maps Reverse Geocoding API.

According to google, reverse geocoding is the process of converting geographic coordinates into a human-readable addresses.

function getAddress (latitude, longitude) {
  $.ajax('https://maps.googleapis.com/maps/api/geocode/json?
          latlng=' + latitude + ',' + longitude + '&key=' + 
          GOOGLE_MAP_KEY)
  .then(
    function success (response) {
      console.log('User\'s Address Data is ', response)
    },
    function fail (status) {
      console.log('Request failed.  Returned status of',
                  status)
    }
   )
}
getAddress(6.4531, 3.3958)

Here’s what I got:

Example output of the Reverse Geocoding API

You can play around with the object to get the desired address in the format you like best.

Putting it all together, we have the below code. (Note that the ipLookUp function was modified.)

function ipLookUp () {
  $.ajax('http://ip-api.com/json')
  .then(
      function success(response) {
          console.log('User\'s Location Data is ', response);
          console.log('User\'s Country', response.country);
          getAdress(response.lat, response.lon)
},

      function fail(data, status) {
          console.log('Request failed.  Returned status of',
                      status);
      }
  );
}
function getAddress (latitude, longitude) {
  $.ajax('https://maps.googleapis.com/maps/api/geocode/json?
          latlng=' + latitude + ',' + longitude + '&key=' + 
          GOOGLE_MAP_KEY)
  .then(
    function success (response) {
      console.log('User\'s Address Data is ', response)
    },
    function fail (status) {
      console.log('Request failed.  Returned status of',
                  status)
    }
   )
}
if ("geolocation" in navigator) {
  // check if geolocation is supported/enabled on current browser
  navigator.geolocation.getCurrentPosition(
   function success(position) {
     // for when getting location is a success
     console.log('latitude', position.coords.latitude, 
                 'longitude', position.coords.longitude);
     getAddress(position.coords.latitude, 
                position.coords.longitude)
   },
function error(error_message) {
    // for when getting location results in an error
    console.error('An error has occured while retrieving
                  location', error_message)
    ipLookUp()
 }
});
} else {
  // geolocation is not supported
  // get your location some other way
  console.log('geolocation is not enabled on this browser')
  ipLookUp()
}

At this point, we know how to retrieve the location of our user no matter what, and you can now tailor the code to your own unique project.

I hope you’ve learned something, thanks for reading!

Source Code

You can the find the code for this article on GitHub.

I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others. Thank you !

Programming a Javascript Simon Game Tutorial

Programming a Javascript Simon Game Tutorial

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

In this javascript tutorial, I recorded myself live programming an html5 javascript simon game.

For those who don't know, I'm a full stack web developer who has been in the industry for over 5 years now. There is a lot of things I have learned along the way and I'd like to share that knowledge with anyone wanting to learn!

like this video if you found it useful and would like to see more videos of the same content.

subscribe to my channel if you are trying to improve your abilities as a web developer, software engineer, or even if you are just learning to code.

Don't forget to turn on those bell notifications!

How to do basic Animations with HTML5 Canvas Element and JavaScript API

How to do basic Animations with HTML5 Canvas Element and JavaScript API

In this Canvas crash course, you'll learn how to do basic animations with HTML5 Canvas Element and JavaScript API. We will look at the HTML5 Canvas element and JavaScript API to draw shapes, paths and do some basic animation. <canvas> is an HTML element that allows a user to create graphics using JavaScript. To start a canvas project, we will need an HTML file and a Javascript file. Using JavaScript to control <canvas> elements, it's also very easy to make (interactive) animations

Canvas Crash Course

Learn how to do basic Animations with HTML5 Canvas Element and JavaScript API

In this video we will look at the HTML5 Canvas element and JavaScript API to draw shapes, paths and do some basic animation

  • Intro - 0:20
  • Create Context - 2:05
  • Rectangles (fillRect, strokeRect, etc) - 4:03
  • Paths (moveTo, lineTo) - 9:41
  • Arcs / Circles - 16:15
  • Bezier Curves - 26:18
  • Bounce Animation - 28:45
  • Character Animation - 40:25

GitHub: https://codepen.io/bradtraversy/pen/YzPeNxg

Understanding Memoization And Dynamic Programming in Javascript

Understanding Memoization And Dynamic Programming in Javascript

In this Javascript tutorial I will explain what memoization is, how to use it, when you should use memoization, how to use memoization, what dynamic programming is, how to use memoization in dynamic programming. Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it.

Memoization is a big complicated word that you may have never even heard before, but you may be surprised to know that you are most likely already using memoization without even realizing it. Memoization is just the act of caching values so that they can be calculated quicker in the future. Memoization is really useful in all parts of programming, but where it is most useful is in dynamic programming. In this video I will explain what memoization is, how to use it, and why it is so useful especially in dynamic programming.

🧠 Concepts Covered:

  • What memoization is
  • When you should use memoization
  • How to use memoization
  • What dynamic programming is
  • How to use memoization in dynamic programming