Swizec Teller - a geek with a hatswizec.com

    Livecoding #34: A Map of Global Migrations, Part 3

    This is a Livecoding Recap – an almost-weekly post about interesting things discovered while livecoding ?. Always under 500 words and with pictures. You can follow my channel, here. New content almost every Sunday at 2pm PDT. There’s live chat, come say hai ?

    This Sunday, we built a zoomable pannable map with React and D3. We also added animation to our migration curves. Now people can see what they mean.

    Click on the map to see a live example

    See? It zooms and it pans and the circles follow their curves. Just like the color, the amount of circles on each line signifies migration intensity. ?

    Here's how it works ?

    Animate SVG element to follow a curve

    Moving an element along a line is one of those things you think you can figure out on your own but you can't. Then you see how it's done and you think, "I'm dumb".

    But you're not dumb. It's totally un-obvious.

    We used Bostock's Point-Along-Line Interpolation example as our model. It creates a custom tween that we apply to each circle as an attrTween transition.

    function translateAlong(path) {
    var l = path.getTotalLength();
    return function (d, i, a) {
    return function (t) {
    var p = path.getPointAtLength(t * l);
    return "translate(" + p.x + "," + p.y + ")";

    That's the custom tween. I'd love to explain how it works, but… well, we have a getPointAtLength function that SVG gives us by default on every <path> element. We use it to generate translate(x, y) strings that we feed into the transform attribute of a <circle> element. That part is obvious.

    The part I don't get is the 3-deep function nesting for currying. The top function returns a tween, I assume. It's a function that takes d, i, a as arguments and never uses them. Instead, it returns a time-parametrized function that returns a translate(x, y) string for each t.

    We know from D3 conventions that t runs in the [0, 1] interval, so we can assume the tween gives a "point at t percent of full length of path" coordinates.


    We apply it in our MigrationLine component like this:

    // inside MigrationLine
    _transform(circle, delay) {
    const { start } = this.props,
    [ x1, y1 ] = start;
    .attr("transform", `translate(${x1}, ${y1})`)
    .attrTween("transform", translateAlong(this.refs.path))
    .on("end", () => {
    if (this.state.keepAnimating) {
    this._transform(circle, 0);
    componentDidMount() {
    const { Ncircles } = this.props;
    keepAnimating: true
    const delayDither = this.duration*Math.random(),
    spread = this.duration/Ncircles;
    d3.range(delayDither, this.duration+delayDither, spread)
    .forEach((delay, i) =>
    this._transform(this.refs[`circles-${i}`], delay)

    We call _transform on every circle in our component. Each gets a different delay so that we get a roughly uniform distribution of circles on the line. Without this, they come in bursts, and it looks weird.

    delayDither ensures the circles for each line start with a random offset, which also helps fight the burstiness. Here's what the map looks like without delayDither and with a constant delay between circles regardless how many there are.

    See? No good.

    You can see the full MigrationLine code on Github.

    Zoom and pan a map

    This part was both harder and easier than I thought.

    You see, D3 comes with something called d3.zoom. It does zooming and panning.

    Cool, right? Should be easy to implement. And it is… if you don't fall down a rabbit hole.

    In the old days, the standard approach was to .call() zoom on an <svg> element, listen for zoom events, and adjust your scales. Zoom callback would tell you how to change zoominess and where to move, and you'd adjust your scales and re-render the visualization.

    We tried that approach with hilarious results:

    First, it was moving in the wrong direction, then it was jumping around. Changing the geo projection to achieve zoom and pan was not the answer. Something was amiss.

    Turns out in D3v4, the zoom callback gets info to build an SVG transform. A translate() followed by a scale().

    Apply those on the visualization and you get working zooming and panning! Of anything :D

    // in SVG rendering component
    onZoom() {
    transform: d3.event.transform
    get transform() {
    if (this.state.transform) {
    const { x, y, k } = this.state.transform;
    return `translate(${x}, ${y}) scale(${k})`;
    return null;
    // ...
    render() {
    return (
    <svg width={width} height={height} ref="svg">
    <g transform={this.transform}>
    // ...

    Get d3.event.transform, save it in state or a data store of some sort, re-render, use it on a <g> element that wraps everything.

    Voila, zooming and panning. ?

    Click on the map to see a live example

    You can see the full World component on Github.

    Happy hacking! ?

    Did you enjoy this article?

    Published on February 20th, 2017 in d3js, Front End, Livecoding, react, Technical

    Learned something new?
    Want to become an expert?

    Here's how it works 👇

    Leave your email and I'll send you thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

    Join Swizec's Newsletter

    And get thoughtful letters 💌 on mindsets, tactics, and technical skills for your career. Real lessons from building production software. No bullshit.

    "Man, love your simple writing! Yours is the only newsletter I open and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. 👌"

    ~ Ashish Kumar

    Join over 14,000 engineers just like you already improving their careers with my letters, workshops, courses, and talks. ✌️

    Have a burning question that you think I can answer? I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

    Ready to Stop copy pasting D3 examples and create data visualizations of your own?  Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

    Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

    Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first 💰 on the side with ServerlessReact.Dev

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❤️

    Created by Swizec with ❤️