There is a new version of this post for GTM V2 here.

[Last updated June 2014] I’ve fallen in love with Universal Analytics and Google Tag Manager. Together they form an incredibly powerful tool for marketing professionals. In most cases, I no longer need to post recommendations to my client for yet another page template revision, since with the tag manager in place, I can just add custom code via the admin panel. Add to that the power of Universal Analytics with its ultra-sensitive Measurement Protocol, and the ability to craft custom dimensions and metrics, and voila! I’m in a happy place.

In this post, I take you through a short JavaScript dev journey of utilizing weather data as a custom dimension in your site’s Analytics. You only need to have Universal Analytics and Google Tag Manager installed on your site.

The end result

This is what you get:

As you can see, I’ve created a custom report which shows visits, pageviews and conversion rates (Pages / Visit > 2) for various weather conditions. This report unequivocally, with a plain-as-day-without-a-doubt display of causality, proves that when it rains, people are more likely to convert. I should do more targeting to British audiences…

Create a new tag in GTM

  • Name the tag “Weather API”
  • Choose Custom HTML Tag as the tag type
  • Enter the following code into the HTML field (Note! You need to load jQuery for this to work! See here for more information):
<script>
  var lat = geoplugin_latitude();
  var lon = geoplugin_longitude();
  var weather = "";
  var weatherAPI = "http://api.openweathermap.org/data/2.5/weather?lat="+lat+"&lon;="+lon;

  $.ajax({
    type : "POST",
    dataType : "jsonp",
    url : weatherAPI+"&units;=metric&callback;=?",
    async : true,
    success : function(data) {
      weather = data.weather[0].main;
      dataLayer.push({"weather": weather});
    },
    error : function(errorData) {
      console.log("Error while getting weather data :: "+errorData.status);
    },
    complete : function() {
      dataLayer.push({"event": "weatherDone"});
    }
  });
</script>
  • Add rule to fire tag on every page ({{url}} matches RegEx .*)

Here’s what’s going on.

First, a couple of external JavaScript functions are called to retrieve the longitude and latitude of the visitor by using their IP addresses. I’m using the free geoPlugin service. You can load it on your site by adding <script src="http://www.geoplugin.net/javascript.gp"></script> in your template.

Remember to load this script BEFORE the weather API runs. It’s best to put it in the <head/> of your page template. If you want, you can also put the script load as the first line of the custom HTML tag you just created.

Next, I use the API of OpenWeatherMap to retrieve the weather data for the latitude and longitude I got in the previous step. Matt Aster modified my solution so that it works with the Weather Underground API.

In the AJAX call, I make an asynchronous call to the API, requesting the data in JSONP (since it originates from a different domain than mine). If the call is successful, I look for the /weather/main/ node, as it has a nice, short description of the weather in the area (e.g. “Clear”). I then push the string into the data layer.

Finally, whether the API call is a success or not, I push an event “weatherDone” into the data layer. This is used to make sure the API call is done before the Universal Analytics tag is fired (see below).

Create new custom dimension in GA

  • Go to the admin panel of your Google Analytics site
  • Under Property, choose Custom Definitions / Custom Dimensions
  • Create a new Custom Dimension with the name “Weather”
  • Scope the new dimension to Session
  • Set the dimension as Active
  • Click Save
  • Make note of the index of the new dimension

Here you create a new dimension in Google Analytics and set it active. You need to make note of the dimension index, since you will be referring to this in a short while.

Create new macro in GTM

  • In Google Tag Manager, go to your container and click New Macro
  • Name the macro “Weather”
  • Set Macro Type as Data Layer Variable
  • Type “weather” in Data Layer Variable Name
  • Click Save

You create the macro to access the weather string you pushed into the data layer a couple of steps ago.

Edit your GA tag

(NOTE! I suggest you take a look at this post for details on sending the weather data using a non-interaction event instead. This way your precious pageviews will never be compromised if the weather script fails to work.)

Steps:

  • Go to the tag that tracks your pageviews and sends them to GA
  • Choose More Settings
  • Choose Custom Dimensions
  • Add the index number of your new dimension in the Index field
  • In the Dimension field, click {{+macro}} and choose the macro you just created
  • Edit the firing rule and add condition {{event}} equals weatherDone
  • Save the tag
  • Create a new container version
  • Publish the new container version

Here you send a new custom dimension with the pageview, and it gets its content from the data layer variable you pushed into the data layer during the weather API call. Since the calls are asynchronous, you’ll need to make sure the UA tag is fired only after the weather API call has been made. This is done by waiting for the event weatherDone to be pushed into the data layer.

Make sure everything works

  • Visit your site
  • Take a look at the requests your site sends by using Firebug or something similar

Enjoy

I created a new custom report in GA, with visits, pageviews and conversion rate as metrics, and my new custom dimension as the dimension.

Note that it might take some time for the new dimension to start pulling in data. If Firebug tells you that the weather data is sent along with your pageview data, you’re fine.

This could be done in so many different ways, but I chose JavaScript simply for this quick prototype. I’m pretty pleased with the result, and even though I make a couple of external calls, page load speed is not an issue. There’s always a risk with asynchronous scripting that the user is quick enough to interact with the site before the pageview is sent, but I don’t think that will be an issue with this light-weight scripting.

I can think of a number of cool applications for this weather API, but I’ll leave those to your imagination.

Google Tag Manager and Universal Analytics do a terrific job of providing high value for marketing professionals. I love the fact that you don’t need to mess with the page template, and you can test and preview your tags as much as you want before publishing them.

EDIT: I edited the firing rules so that the UA tag occurs only after the weather API call has completed.

EDIT II: Note that you need to load jQuery for this to work! The $.ajax call is a jQuery function! So either load the jQuery resource in the <head/> of your page method (so that it gets loaded before the GTM container) OR have the following as the first line of the custom HTML tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

EDIT III: Be sure to check my post on how to make sure the weather API is polled just once per visit. This will improve site performance, and decrease the burden on the external API.

EDIT IV: Finally, see this post on sending custom dimensions with events rather than pageviews for the optimal version of the code above.