Skip to content

Instantly share code, notes, and snippets.

@mtaptich
Last active December 11, 2015 00:42
Show Gist options
  • Select an option

  • Save mtaptich/6bc99e5030074a15f584 to your computer and use it in GitHub Desktop.

Select an option

Save mtaptich/6bc99e5030074a15f584 to your computer and use it in GitHub Desktop.
map + point translation
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>
.land {
fill: #eee;
stroke: #777777;
}
circle {
fill: steelblue;
stroke: #fff;
stroke-width: 3px;
}
.journey{
fill: none;
stroke: #000;
stroke-width: 4;
stroke-dasharray: 4px,8px;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="http://d3js.org/d3.geo.projection.v0.min.js"></script>
<script src="http://d3js.org/queue.v1.min.js"></script>
<script>
var width = 960,
height = 500;
var projection = d3.geo.conicConformal()
.rotate([98, 0])
.center([0, 38])
.parallels([29.5, 45.5])
.scale(1000) // Change to 300 to zoom out
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var points = [
[-122.2728, 37.8717],
[-104.9903, 39.7392],
[-93.2650, 44.9778],
[-75.6008, 41.0144],
[-86.7833, 36.1667],
[-96.7970, 32.7767],
[-110.9264,32.2217]
];
var line = d3.svg.line()
.interpolate("cardinal-closed")
.x(function(d) { return projection(d)[0]; })
.y(function(d) { return projection(d)[1]; });
queue()
.defer(d3.json, "http://mtaptich.github.io/d3-lessons/d3-maps/state_pol.json")
.await(ready);
function ready (error, us) {
svg.append("g")
.attr("class", "land")
.selectAll("path")
.data(topojson.feature(us, us.objects.state_pol).features)
.enter().append("path")
.attr("class", function(d) {return d.id})
.attr("d", path)
var linepath = svg.append("path")
.data([points])
.attr("d", line)
.attr('class', 'journey');
svg.selectAll(".point")
.data(points)
.enter().append("circle")
.attr("r", 8)
.attr("transform", function(d) { return "translate(" + projection(d) + ")"; });
var circle = svg.append("circle")
.attr("r", 19)
.attr("transform", "translate(" + projection(points[0]) + ")");
// Create a loop by calling 'itself' as a callback function
transition();
function transition() {
circle.transition()
.duration(10000)
.attrTween("transform", translateAlong(linepath.node()))
.each("end", transition);
}
};
// Returns an attrTween for translating along the specified path element.
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 + ")";
};
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment