I\'m using D3.js to generate and render a path from a GeoJSON file. That works fine, but now I\'d like to animate an object along that path. I know how to do that using D3 and s
Well, I figured it out, but I'm not completely sure if my solution is the "right" way to do it. Basically, I used D3 to select the raw SVG elements that were created by the d3.geo.path() object.
Note the changes to the targetPath
, pathNode
, and pathLength
variables, and also to the transform()
and attrTween()
functions:
// Draw a red circle on the map:
group = vis.append("svg:g");
var targetPath = d3.selectAll('.route')[0][0],
pathNode = d3.select(targetPath).selectAll('path').node(),
pathLength = pathNode.getTotalLength();
circle = group.append("circle")
.attr({
r: 10,
fill: '#f33',
transform: function () {
var p = pathNode.getPointAtLength(0)
return "translate(" + [p.x, p.y] + ")";
}
});
// Animate the circle:
duration = 10000;
circle.transition()
.duration(duration)
.ease("linear")
.attrTween("transform", function (d, i) {
return function (t) {
var p = pathNode.getPointAtLength(pathLength*t);
return "translate(" + [p.x, p.y] + ")";
}
});
Live example is here: http://jsfiddle.net/5m35J/6/