For our next experiment, we will take all of our combined knowledge and add some smooth transitions to the map. Transitions are a fantastic way to add style and smoothness to data changes.
This experiment will, again, require us to start with example-3.html. The complete experiment can be viewed at http://localhost:8080/chapter-4/example-5.html.
If you remember, we leveraged the JavaScript setInterval() function to execute updates at a regular timed frequency. We will go back to this method now to assign a random number between 1 and 33 to our existing color() function. We will then leverage a D3 method to smoothly transition between the random color changes.
Right below the update section, add the following setInterval() block of code:
setInterval(function(){
map.selectAll('path').transition().duration(500)
.attr('fill', function(d) {
return color(Math.floor((Math.random() * 32) + 1));
});
},2000);
This method indicates that, for every 2000 milliseconds (2 seconds), the map update section should be executed and the color set to a random number between 1 and 32. The new transition and duration methods transition from the previous state to the new state over 500 milliseconds. Open example-5.html in your browser and you should see the initial color based on the index of the state. After 2 seconds, the colors should smoothly transition to new values.