Using GeoIP API in Google Tag Manager to Get User Location

There are times when you're working with a client and you don't have access to their website but you do have access to their Google Tag Manager account. Capturing general location details about an inbound lead can be helpful for lead qualification and/or lead routing in a CRM. For example, sales reps may have territories based on regions ie. a sales rep is assigned to the West Coast (California, Oregon & Washington). It's helpful if you can get the location as they fill out the form and pass it along with the rest of the lead's information instead of having sales getting that later.

So - on to the code. There is a great free GeoIP lookup service called Geolocation DB that allows you to drop in a script that returns a JSON document containing the users location https://geolocation-db.com/jsonp.

To access the JSON data all you have to do is define a callBack(data) function and pass a variable to it which will contain the location data. From there you can do whatever you need to with the data - populate a form make an API call, etc. Another option is to make a fetch() request to https://geolocation-db.com/jsonp. Sample code is below - proceed with caution and test! The last you want is some script in Tag Manager breaking the site you're working on. One last tip is to load this on page load - there by loading last after the website's scripts have all loaded incase the geolocation were to go down.

<script type="text/javascript">
// Add Geo Location script to DOM
function addGeoLocationScript(){
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://geolocation-db.com/jsonp';
  var h = document.getElementsByTagName('script')[0];
  h.parentNode.insertBefore(script, h);
}
addGeoLocationScript();

// Callback function that contains location data
function callback(data){
  if(!!document.querySelector('input[name=country]')){
    // Set input value to return country name
    document.querySelector('input[name=country]').value = data.country_name;
  }
}
</script>