Table of Contents for
Learning D3.js 4 Mapping - Second Edition

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Learning D3.js 4 Mapping - Second Edition by Lars Verspohl Published by Packt Publishing, 2017
  1. Learning D3.js 4 Mapping, Second Edition
  2. Title Page
  3. Second Edition
  4. Copyright
  5. Learning D3.js 4 Mapping
  6. Second Edition
  7. Credits
  8. About the Authors
  9. About the Reviewers
  10. www.PacktPub.com
  11. Why subscribe?
  12. Customer Feedback
  13. Table of Contents
  14. Preface
  15. What this book covers
  16. What you need for this book
  17. Who this book is for
  18. Conventions
  19. Reader feedback
  20. Customer support
  21. Downloading the example code
  22. Downloading the color images of this book 
  23. Errata
  24. Piracy
  25. Questions
  26. Gathering Your Cartography Toolbox
  27. Quick bootstrap
  28. Step-by-step bootstrap
  29. A lightweight web server
  30. Using the web browser as a development tool
  31. Installing the sample code
  32. Working with the developer tools
  33. Summary
  34. Creating Images from Simple Text
  35. The SVG coordinate system
  36. Line
  37. Rectangle
  38. Circle
  39. Polygon
  40. Path
  41. Experiment
  42. Paths with curves
  43. Transform
  44. Translate
  45. Scale
  46. Grouping
  47. Text
  48. Summary
  49. Producing Graphics from Data - the Foundations of D3
  50. Creating basic SVG elements
  51. The enter() function
  52. The update function
  53. The exit() function
  54. AJAX
  55. Summary
  56. Creating a Map
  57. Foundation - creating your basic map
  58. Including the dataset
  59. Experiment 1 – adjusting the bounding box
  60. Experiment 2 – creating choropleths
  61. Experiment 3 – adding click events to our visualization
  62. Experiment 4 – using updates and transitions to enhance our visualization
  63. Experiment 5 – adding points of interest
  64. Experiment 6 – adding visualizations as a point of interest
  65. Summary
  66. Click-Click Boom! Applying Interactivity to Your Map
  67. Events and how they occur
  68. Experiment 1 – hover events and tooltips
  69. Experiment 2 – tooltips with visualizations
  70. Experiment 3 – panning and zooming
  71. Experiment 4 – orthographic projections
  72. Experiment 5 – rotating orthographic projections
  73. Experiment 6 – dragging orthographic projections
  74. Summary
  75. Finding and Working with Geographic Data
  76. Geodata file types
  77. What are shapefiles and how do I get them?
  78. Acquiring shapefiles for a specific country
  79. GeoJSON
  80. A quick map in D3 with only GeoJSON
  81. TopoJSON basics
  82. TopoJSON command-line tips
  83. Preserving specific attributes
  84. Simplification
  85. Merging files
  86. Summary
  87. Testing
  88. Code organization and reusable assets
  89. Project structure
  90. Exploring the code directory
  91. Other administrative files
  92. Writing testable code
  93. Keeping methods/functions small
  94. Preventing side effects
  95. An example with viz.js
  96. Unit testing
  97. Creating resilient visualization code
  98. Adding a new test case
  99. Summary
  100. Drawing with Canvas and D3
  101. Introducing Canvas
  102. Drawing with Canvas
  103. The three drawing steps of every Canvas visual
  104. Drawing various shapes with Canvas
  105. Animating the Canvas
  106. Animating the Canvas way
  107. Getting a general overview
  108. Preparing the rain data
  109. Updating each drop
  110. Drawing frame by frame
  111. Canvas and D3
  112. Getting an overview of our experiment
  113. The data
  114. Updating each drop
  115. Binding the data
  116. Drawing the data
  117. Running the app
  118. Summary
  119. Mapping with Canvas and D3
  120. Choosing Canvas or SVG
  121. Reasons to choose SVG
  122. Reasons to choose Canvas
  123. Visualizing flight paths with Canvas and D3
  124. The data
  125. Building the flight path map in SVG
  126. Measuring the performance
  127. Building the flight path map in Canvas
  128. Setting up the map
  129. Drawing the map and listening for user input
  130. Preparing and drawing with Canvas
  131. Drawing the background scene
  132. Defining the planes
  133. Calculating the plane's positions
  134. Animating the plane
  135. Measuring the performance
  136. Optimizing performance
  137. Continuing with measuring performance
  138. Summary
  139. Adding Interactivity to Your Canvas Map
  140. Why Canvas interaction is different
  141. Drawing the world on a Canvas
  142. Setting up
  143. Drawing the world
  144. Making the world move
  145. Setting up the behavior
  146. Handling zoom and rotation
  147. Finding the Canvas object under the mouse - Picking
  148. Picking, the theory
  149. Creating all things hidden
  150. Drawing the hidden Canvas
  151. Picking the values
  152. Storing more data and using a lookup array
  153. Highlighting the country on mouse over
  154. Visualizing data per country and adding a tooltip
  155. Adding new data to our old globe
  156. Coloring the globe
  157. Adding a tooltip
  158. The HTML
  159. Building the static parts of the tooltip
  160. Showing and hiding the tooltip
  161. Summary
  162. Shaping Maps with Data - Hexbin Maps
  163. Reviewing map visualization techniques
  164. Choropleth maps
  165. Cartograms
  166. Dot density maps
  167. Value and use of the hexagon
  168. Making a hexbin map
  169. Reviewing the hexbin algorithm
  170. Setting it up
  171. Drawing the map
  172. Drawing a point grid for our hexagons
  173. Keeping only the points within the map
  174. Making the hex tile
  175. Retrieving the hexagon center points
  176. Drawing the hex tiles
  177. Joining data points to the layout points
  178. Dressing our data for the final act
  179. Turning our visual into an interactive app
  180. Adding additional information on hover and click
  181. Changing the hexagon size
  182. Changing the color scale interpolator
  183. Browsing different datasets
  184. Encoding data as hexagon size
  185. Summary
  186. Publishing Your Visualization with Github Pages
  187. What we will publish
  188. Understanding the type of content you can publish
  189. Hosting your code on GitHub
  190. Making sense of some key terms and concepts
  191. Tracking historic changes of your files
  192. Collaborating on a project
  193. Working on project branches
  194. Setting up a GitHub account
  195. Creating a repository
  196. Editing a file on GitHub
  197. Uploading files to the repository
  198. Publishing your project on GitHub Pages
  199. Preparing the files for publishing
  200. Keeping your paths absolute
  201. Changing the main HTML filename to index.html
  202. Publishing your project
  203. Summary

Handling zoom and rotation

We set up the zoom behavior, meaning that our Canvas is

  1. listening on every mouse wheel and drag
  2. firing the zoomed() handler on each of these events

Let’s now fill our handler to do something to the globe.

What do we want to do? From a bird’s perspective, for each zoom, we want to establish the scale for the projection, apply it to the path, and redraw the globe a little bit bigger or a little smaller. For each drag, we would want to establish the new rotation values, apply them to the projection and path, and redraw the globe a little bit rotated. To get there, the handler should distinguish between a zoom and a drag. A zoom should lead to a projection-scale change and a drag should lead to a rotation change. For each path, you calculate the position change. Once that’s done, you will need to redraw the globe. It’s the game-loop mantra: process user-input, clear the Canvas, then redraw the Canvas with updated data.

Let’s start with the zoom action:

function zoomed() {
var event = d3.event.sourceEvent.type;

if (event === 'wheel') {
var transformScale = d3.event.transform.k;
projectionScaleChange = (transformScale – prevTransformScale) *
origProjectionScale;
projectionScale = projectionScale + projectionScaleChange;
projection.scale(projectionScale);
prevTransformScale = transformScale;
} else if (event === 'mousemove'){
// Here goes the rotation logic as this will be triggered upon dragging
}

requestAnimationFrame(function() {
renderScene(countries);
});
}

At first, we will need to distinguish between a zoom and a drag event. D3 makes this easy for us with the d3.event object holding a sourceEvent property specifying what event type the user triggers. If it’s a wheel event, we change the scale if it's a mousemove event, we change the rotation. Simple.

Changing the scale looks involved but is pretty straightforward. Before we dive into the code, let’s make one important distinction. The projection has a scale, and the transformation upon user zoom also has a scale. However, they are different. Projection scales differ between projections. Our d3.geoOrthographic() projection has an initial scale of around 286 (we set it to height / 2.1 = 286). Our transformation has an initial scale of 1. That’s the default.

So, you retrieve the current transformScale via d3.transform.k. You note down the change of this scale to the previous transform scale, which can be negative for zoom in or positive for zoom out. However, as your projection scale is quite a big number (as in 286 to start with) and the transform scale change per zoom will be small (for a normal mouse wheel turn the change might be around 0.005), you will want to boost this number up to get a noticeable change in your projection. Hence, you will multiply it with a larger number. You can choose any large number you like, but choosing your initial projection scale we called origProjectionScale allows you to port this calculation over to any other projection, and it should work nicely. You then just change the current projectionScale by this projectionScaleChange.

The rest is simple. Just apply it to your globe’s projection with projection.scale(projectionScale), set the previous transform scale to the updated transform scale, and re-render the globe. Note, that you don’t need to update the path generator, as whenever it’s called, it will use the projection as is at the moment of being called, which we’ve changed accordingly.

That was the hard bit. Rotating is even simpler. You just need to track the changes in the user’s mouse movements and apply them to D3’s projection.rotate() parameters. Let’s track the change in mouse coordinates right at the top of the zoomed() handler:

function zoomed(
var dx = d3.event.sourceEvent.movementX;
var dy = d3.event.sourceEvent.movementY;

// all the rest

Note, that the two MouseEvent properties .movementX and .movementY are not available in Safari or Internet Explorer. You can see a cross-browser implementation, which is calculating the two values on the fly in code example 10_02.html at https://github.com/larsvers/Learning-D3.js-4-Mapping.

The rotation logic will trigger when the user drags or rather triggers the mousemove event, which goes into the else if part of our conditional:

if (event === ‘wheel’) {
// here goes the zoom logic described previously
} else if (event === ‘mousemove’) {
var r = projection.rotate();
rotation = [r[0] + dx * 0.4, r[1] - dy * 0.5, r[2]];
projection.rotate(rotation);
} else {
console.warn('unknown mouse event in zoomed()'); // alerting issues
}

In the preceding code, we first retrieve the current rotation values from the projection in the variable r. Then, you change the r[0], the yaw value (responsible for rotating the world around its normal or vertical axis) by the x change of the mouse coordinates. You further change r[1], the roll value (rotating the world around its lateral axis, going horizontally from left to right) by the y change of the mouse coordinates. We leave the third pitch value as is, and yes, the best way is to throttle these values to a reasonable speed of rotation with dx * 0.4 and dy * 0.5, respectively. Note that this is the straightforward but naive way to rotate the globe. It will fully do in our case. If you want to apply utmost precision, you could use versor dragging (check out http://tiny.cc/versor). The key difference is that versor dragging rotates the globe in the right direction even when it's upside down.

That’s it for rotation. Remember, the world gets re-rendered after this conditional as we do this in the following Canvas game loop: get user input – calculate the new position – re-render.

Here’s a static attempt to show dynamic zooming and rotations:

Zooming and rotating a Canvas globe
View the step shown in the preceding screenshot in the browser at https://larsvers.github.io/learning-d3-mapping-10-2 and its code example at 10_02.html.

The main benefit of zooming via a projection change is that it allows rotating (that’s a win) and guarantees semantic zooming of the world rather than geometric zooming. When you zoom into a Canvas object with context.scale(), it naively enlarges anything that’s on the Canvas. So, a country border, for example, gets wider and wider, the more you scale it. That’s geometric zooming. We, however, want to keep everything constant, apart from the area of the individual country polygons. This is called semantic zooming. Another benefit of the projection change is that getting the coordinate of a Canvas object by mouse-over is more straightforward. This is our next stop.