Contact

Create a rotating globe using React and D3

by Peter Cook / 01 Aug 2018

Prerequisites: Moderate experience with React.

This tutorial shows how to create a rotating globe using React and D3. We’ll use React to create a component which’ll contain the rotating globe and D3’s powerful geographic functionality to deal with transforming our geographic data into SVG.

The d attribute in the path element will eventually be a string consisting of a series of draw commands (such as move to, draw a line etc.). In this tutorial we don’t need to know the precise details of these commands as D3 will take care of this for us.

Let’s also render this component:

ReactDOM.render(<Globesize={400}/>,document.getElementById('app'))

(Make sure you have a div element with id app in your HTML!)

3. Load and process geographic data

Two of the most common ways of representing geographic data on the web are GeoJSON and TopoJSON. GeoJSON is a JSON based format for describing geographic features while TopoJSON is also JSON based but it cleverly reduces size by removing redundancy/repetition in the geographic data.

4. Render the globe

The GeoJSON file contains an array of features, each of which is described by arrays of longitude and latitude co-ordinates. Each co-ordinate represents a location on the surface of the earth. Converting these to x and y positions on the screen is known as projection and is something D3 can do for us (saving us some mathematical headaches!).

The first step in setting up a projection in D3 is to choose the type of projection we’d like. We’ll use an orthographic projection as this’ll make the earth look like a globe. Let’s create the D3 projection function at the start of our render() function:

6. Summary

This tutorial has shown how we can use React and D3 to create a rotating globe. React allows us to build a reusable component that handles the creation and updating of our SVG while D3 provides the geographic cleverness.

Have a play around with the code on Codepen - see if you can change things like the size of the globe abd the speed of rotation. If you’re feeling more adventurous you could explore some of the other projections that D3 provides. There’s quite a few to choose from!