Little Earth Spatial Programming

Little Earth / Field Notes / Animating a Geographic Boundary

Data Visualization

Animating a Geographic Boundary into a Circle (and Back Again)

A D3 and SVG technique to morph a geographic boundary into a circle and back again by giving both paths the same number of nodes.

Paths in SVG are comprised of points called nodes. In order to transition from one path (the boundary) into another (the circle) the same number of nodes need to exist on both.

From the archive

This post was originally published in September 2014 and has been preserved here with light edits. The live demos below are interactive CodePens — let them load and they will draw, then animate, right in the page.

Start with a boundary

Start by drawing a boundary (Texas) with D3.

The Texas boundary, drawn from GeoJSON with D3 · Open on CodePen ↗

Spokes from the centroid

We want to shrink into a circle that is centred around the centroid of Texas. D3 has a method for finding the centroid. We use this to draw paths from the centroid to each node.

Spokes drawn from the centroid out to each boundary node · Open on CodePen ↗

Placing nodes along each spoke

SVG has a handy dandy method for placing a node along the specified distance of a path, getPointAtLength. We use this to calculate a new point at whatever distance from the centroid. In this example we use a radius of 10 pixels. The nice thing about this approach is we can be assured all nodes in the original boundary are accounted for and have a place in the circle.

A new node placed on each spoke, 10px from the centroid — the future circle · Open on CodePen ↗

Animate the transition

Finally create a path from the new nodes. We use this to animate the original polygon. D3 makes this pretty simple with the transition method.

Voilà.

The finished morph: Texas collapses to a circle, then springs back · Open on CodePen ↗

← All Field Notes