Book Image

Learning D3.js 5 Mapping - Second Edition

By : Thomas Newton, Oscar Villarreal, Lars Verspohl
Book Image

Learning D3.js 5 Mapping - Second Edition

By: Thomas Newton, Oscar Villarreal, Lars Verspohl

Overview of this book

D3.js is a visualization library used for the creation and control of dynamic and interactive graphical forms. It is a library used to manipulate HTML and SVG documents as well as the Canvas element based on data. Using D3.js, developers can create interactive maps for the web, that look and feel beautiful. This book will show you how build and design maps with D3.js and gives you great insight into projections, colors, and the most appropriate types of map. The book begins by helping you set up all the tools necessary to build visualizations and maps. Then it covers obtaining geographic data, modifying it to your specific needs, visualizing it with augmented data using D3.js. It will further show you how to draw and map with the Canvas API and how to publish your visualization. By the end of this book, you'll be creating maps like the election maps and the kind of infographics you'll find on sites like the New York Times.
Table of Contents (13 chapters)
6
Finding and Working with Geographic Data

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()...