Add Geolocation data to any form using JavaScript

June 25, 2016
JavaScript Geolocation Performance

Adding geolocation data to form can be helpful to understand where your visitors are coming from. For instance, it’s quite useful to know the timezone of someone who contacted you… Let’s see how to implement this using JavaScript.

For easier understanding, let’s split this into 3 steps:

  1. Pick a suitable third-party geolocation API
  2. Consume this service using JSON or JSONP
  3. Append the response to the form

1) Geolocation Services that supports JSON/JSONP

I had the opportunity to try quite a few geolocation services. In my experience, it’s hard to find a free and reliable API. By reliable, I mean a service that won’t be closing down anytime soon or that don’t become paid.

For a long time, I was using Telize but it suddenly stopped working on several sites I’m maintaining. I immediately headed to their main site to see “The public API will permanently shut down on November 15th, 2015. More information can be found here. To continue using Telize after this date, please spin up your own instance or subscribe to a paid plan.”

So here’s two public geolocation HTTP API that I end up using instead:

2) Getting JSON or JSONP from Geolocation API

If you’re using jQuery, making a GET HTTP request couldn’t be easier thanks to $.getJSON(). I will therefore skip the jQuery version for now and explain to to do the same in vanilla JavaScript.

What are the advantages of using JSONP over JSON? Simply put: much less code required than using JSON but little bit less control over it. Since JSONP is actually JavaScript, there’s no need to parse the response and more importantly it helps overcoming CORS problems. Making an HTTP request with JSONP can be as simple as this:

<!-- The below JSONP request is async -->
<script type="text/javascript" src="https://freegeoip.net/json/?callback=formGeolocation" async></script>

I used the HTML attribute async to make this request asynchronous so that it doesn’t slow slown the page rendering. But if you need to use Geolocation right away, you should probably remove it.

3) Adding the response to the form

We then need to create our callback function formGeolocation and use the JSONP response that it contains. This function needs to be loaded before the GET HTTP request is executed, otherwise it’ll result in an error.

function formGeolocation(jsonp) {
    // Get the form ID
    var form = document.getElementById('contact_form');
    // Loop through the objects
    Object.keys(jsonp).forEach(function (key) {
        dynamicItems += '<input type="hidden" name="geolocation[' + key + ']" value="' + jsonp[key] + '"/>';
    });
    // Append only once for better performance
    form.innerHTML += dynamicItems;
}

Please leave your feedback in the comments.

comments powered by Disqus
Want a beautiful and engaging website for your business? Check out YOSA Digital×