Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning D3.js 5 Mapping - Second Edition

You're reading from  Learning D3.js 5 Mapping - Second Edition

Product type Book
Published in Nov 2017
Publisher
ISBN-13 9781787280175
Pages 298 pages
Edition 2nd Edition
Languages
Authors (3):
Thomas Newton Thomas Newton
Profile icon Thomas Newton
Oscar Villarreal Oscar Villarreal
Profile icon Oscar Villarreal
Lars Verspohl Lars Verspohl
Profile icon Lars Verspohl
View More author details

Table of Contents (13) Chapters

Preface Gathering Your Cartography Toolbox Creating Images from Simple Text Producing Graphics from Data - the Foundations of D3 Creating a Map Click-Click Boom! Applying Interactivity to Your Map Finding and Working with Geographic Data Testing Drawing with Canvas and D3 Mapping with Canvas and D3 Adding Interactivity to Your Canvas Map Shaping Maps with Data - Hexbin Maps Publishing Your Visualization with GitHub Pages

Click-Click Boom! Applying Interactivity to Your Map

In the previous chapter, you learned what is needed to build a basic map with D3.js. We also discussed the concepts of enter, update, and exit and how they apply to maps. You should also understand how D3 mixes and matches HTML with data. However, let's say you want to take it a step further and add more interactivity to your map. We covered only the tip of the iceberg regarding click events in the previous chapter. Now, it's time to dig deeper.

In this chapter, we will expand our knowledge of events and event types. We will progress by experimenting and building upon what you've learned. The following topics are covered in this chapter:

  • Events and how they occur
  • Experiment 1 - hover events and tooltips
  • Experiment 2 - tooltips with visualizations
  • Experiment 3 - panning and zooming
  • Experiment 4 - orthographic...

Events and how they occur

The following is taken directly from the w3 specifications:

"The Event interface is used to provide contextual information about an event to the handler processing the event. An object that implements the Event interface is generally passed as the first parameter to an event handler. More specific context information is passed to event handlers by deriving additional interfaces from Event which contain information directly relating to the type of event they accompany. These derived interfaces are also implemented by the object passed to the event listener."

In other words, an event is a user input action that takes place in the browser. If your user clicks, touches, drags, or rotates, an event will fire. If you have event listeners registered to those particular events, the listeners will catch the event and determine the event type. The listeners...

Experiment 1 – hover events and tooltips

Building on our previous example, we can easily swap our click method with a hover method. Instead of having var click, we will now have var hover with the corresponding function. Feel free to open example-1.html of the chapter-5 code base to go over the complete example (http://localhost:8080/chapter-5/example-1.html). Let's review the necessary code to change our click event to a hover event. In this particular case, we will need a little more CSS and HTML. In our <style> tag, add the following lines:

#tooltip{ 
  position: absolute; 
  z-index: 2; 
  background: rgba(0,153,76,0.8); 
  width:130px; 
  height:20px; 
  color:white; 
  font-size: 14px; 
  padding:5px; 
  top:-150px; 
  left:-150px; 
  font-family: "HelveticaNeue-Light", "Helvetica Neue Light", 
"Helvetica Neue", Helvetica...

Experiment 2 – tooltips with visualizations

In this next experiment, we will enhance our tooltips with additional visualizations. In a similar fashion, we will outline the additional code to provide this functionality (http://localhost:8080/chapter-5/example-2.html).

To our CSS, we will need to add the following lines of code:

#tooltip svg{ 
  border-top:0; 
  margin-left:-5px; 
  margin-top:7px; 
} 

This will style our SVG container (inside our tooltip DOM element) to align it with the label of the state.

Next, we'll include two new scripts to create visualizations:

<script src="base.js"></script> 
<script src="sparkline.js"></script> 

The preceding JavaScript files contain the D3 code for creating a line chart visualization. The chart itself contains and leverages the Towards Reusable Chart described by Mike Bostock at...

Experiment 3 – panning and zooming

A very common request when working with maps is to provide the ability to pan and zoom around the visualization. This is especially useful when a large map contains abundant detail. Luckily, D3 provides an event listener to help with this feature. In this experiment, we will outline the principles to provide basic panning and zooming for your map. This experiment requires us to start with example-1.html; however, feel free to look at http://localhost:8080/chapter-5/example-3.html for reference.

First, we will add a simple CSS class in our <style> section; this class will act as a rectangle over the entire map. This will be our zoomable area:

.overlay { 
  fill: none; 
  pointer-events: all; 
} 

Next, we need to define a function to handle the event when the zoom listener is fired. The following function can be placed right below...

Experiment 4 – orthographic projections

For the next set of experiments in this chapter, we will switch gears and look at interactivity with orthographic projections (representing a three-dimensional map on a two-dimensional screen). A better visualization to illustrate these concepts is the entire globe instead of a single country. This experiment will start with http://localhost:8080/chapter-5/example-4.html and require a new datafile, which is provided for you. You will notice that the code base is almost identical, with the exception of three changes that we will outline here:

var height = 600; 
var width = 900; 
var projection = d3.geoOrthographic().clipAngle(90); 
var path = d3.geoPath().projection(projection); 

First, we will change our d3.geo projection from d3.geoMercator to d3.geoOrthographic. We also have an additional setting to configure: the clipAngle at 90...

Experiment 5 – rotating orthographic projections

Our previous example was very fascinating. We went from visualizing a map in two dimensions to three dimensions with just a few lines. The next step is to animate it. For this experiment, open http://localhost:8080/chapter-5/example-5.html in the code samples. Let's now piece it together.

First, we’ll load the world data and reformat it from TopoJSON to GeoJSON:

d3.json('world.json').then(function(data) {
var countries = topojson.feature(data, data.objects.countries); var mexico = countries.features[102];

As Mexico is the center of the universe and requires special attention, we isolated it into its own variable by taking the corresponding feature from the countries' feature array. This will allow us to manipulate it separately from the rest of the globe.

Next, we will data join the information...

Experiment 6 – dragging orthographic projections

For our last example, we will add the ability to drag our globe so that the user can spin it to the left or right. Open http://localhost:8080/chapter-5/example-6.html from the code samples and let's get started:

var dragging = function(d) { 
  var c = projection.rotate(); 
  projection.rotate([c[0] + d3.event.dx/2, c[1], c[2]]); 
  map.selectAll('path').attr('d', path);
};

Our first piece of new code is our dragging event handler. This function will be executed every time the user drags the mouse on the screen. The algorithm executes the following steps:

  1. Stores the current rotation value.
  2. Updates the projection's rotation based on the distance it is dragged.
  3. Updates all the paths on the map.

The second step deserves a little more explanation. Just like the d3.zoom() event handler, d3.drag()...

Summary

We covered many examples to get you started with interactivity for your D3 map visualizations. We went over the basics of event handling, explored various methods to bind events to the map, outlined the two behavior APIs d3.zoom() and d3.drag(), and even dipped our toes into orthographic projections. If you wish to dig deeper into world rotations, and the math involved, check out the Jason Davies article at:
http://www.jasondavies.com/maps/rotate/.

After two chapters of drawing and interacting with maps, the next chapter will explain how to obtain geo data in order to create any map you want. We'll also include some techniques to optimize the data files for viewing the web.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning D3.js 5 Mapping - Second Edition
Published in: Nov 2017 Publisher: ISBN-13: 9781787280175
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}