DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. Livecoding: A Map of Global Migrations, Part 3

Livecoding: A Map of Global Migrations, Part 3

In the third and final part of our series, we're going to to use React and D3 to animate our SVG elements, so they'll follow a curve. Which maps the map look great!

Swizec Teller user avatar by
Swizec Teller
·
Apr. 13, 17 · Tutorial
Like (1)
Save
Tweet
Share
4.15K Views

Join the DZone community and get the full member experience.

Join For Free

Since finishing Part 1 and Part 2, we've 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 the 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 that the tween gives a "point at t percent of full length of path" coordinates.

Great.

We apply it in our MigrationLine component like this:

// inside MigrationLine
    _transform(circle, delay) {
        const { start } = this.props,
              [ x1, y1 ] = start;

        d3.select(circle)
          .attr("transform", `translate(${x1}, ${y1})`)
          .transition()
          .delay(delay)
          .duration(this.duration)
          .attrTween("transform", translateAlong(this.refs.path))
          .on("end", () => {
              if (this.state.keepAnimating) {
                  this._transform(circle, 0);
              }
          });
    }

    componentDidMount() {
        const { Ncircles } = this.props;

        this.setState({
            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 functionalities! Of anything!

// in SVG rendering component
    onZoom() {
        this.setState({
            transform: d3.event.transform
        });
    }

    get transform() {
        if (this.state.transform) {
            const { x, y, k } = this.state.transform;
            return `translate(${x}, ${y}) scale(${k})`;
        }else{
            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!

Element Tween (software) Data store SVG IT Pan (newsreader) Visualization (graphics) Strings GitHub

Published at DZone with permission of Swizec Teller, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • GitLab vs Jenkins: Which Is the Best CI/CD Tool?
  • How To Build an Effective CI/CD Pipeline
  • 3 Main Pillars in ReactJS
  • Understanding and Solving the AWS Lambda Cold Start Problem

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: