Using Multiple Heat Layers with Google Maps

1 minute read

For one of the assignments in Cloud & Big Data course at Columbia University, we had to display a Heat Map Layer showing positive and negative tweets from Twitter.

Now, using Heatmaps with Google Maps is pretty trivial. Google Maps has pretty decent documentation along with working examples.

But how do we do it when we want to show multiple heat maps working independently on the same Google Map?

Let's take a closer look at the standard Heatmap example first.

Go through the example given here.

As we see, the following piece of code is responsible for initializing the heat map. It also has a function called changeGradient() which is of interest to us.



function initialize() {
  var mapOptions = {
    zoom: 13,
    center: new google.maps.LatLng(37.774546, -122.433523),
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  var pointArray = new google.maps.MVCArray(taxiData);

  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray
  });

  heatmap.setMap(map);
}


function changeGradient() {
  var gradient = [
    'rgba(0, 255, 255, 0)',
    'rgba(0, 255, 255, 1)',
    'rgba(0, 191, 255, 1)',
    'rgba(0, 127, 255, 1)',
    'rgba(0, 63, 255, 1)',
    'rgba(0, 0, 255, 1)',
    'rgba(0, 0, 223, 1)',
    'rgba(0, 0, 191, 1)',
    'rgba(0, 0, 159, 1)',
    'rgba(0, 0, 127, 1)',
    'rgba(63, 0, 91, 1)',
    'rgba(127, 0, 63, 1)',
    'rgba(191, 0, 31, 1)',
    'rgba(255, 0, 0, 1)'
  ]
  heatmap.set('gradient', heatmap.get('gradient') ? null : gradient);
}

The changeGradient function changes the default gradient values to anything you specify. If you notice, the color is changing from light blue rgba(0, 255, 255, 0) for low density points to Sharp Red rgba(255, 0, 0, 1) as the density increases.

What you can simply do is, initiate two different heatmaps, say heatmapPositive (light blue to dark blue) and heatmapNegative (yellow to red) in case you want to show two different heat maps for the positive and negative sentiment tweets.

If you want sample code for this, you can find it here. If you want to see how this looks, you can check out this video which shows the default state and then with the dual heat maps.

If you want to do much more, there is this neat library called heatmap.js. It has bunch of features like adding legends and tool tips, customized maps, etc.

Hope you found this useful. If you're aware of any better libraries out there, then Let me know!