Skip to content

Instantly share code, notes, and snippets.

@venkat
Last active April 13, 2023 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save venkat/e7b6e498ba87a2a6b7423ca7525773d6 to your computer and use it in GitHub Desktop.
Save venkat/e7b6e498ba87a2a6b7423ca7525773d6 to your computer and use it in GitHub Desktop.
US map shipping animation
license: gpl-3.0
height: 600
border: no
<!DOCTYPE html>
<style>
.states :hover {
fill: red;
}
.state-borders {
fill: none;
stroke: #fff;
stroke-width: 0.5px;
stroke-linejoin: round;
stroke-linecap: round;
pointer-events: none;
}
</style>
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
<script>
//Width and height of map
var width = 960;
var height = 500;
var svg = d3.select("svg");
var projection = d3.geoAlbersUsa()
.translate([width/2, height/2]) // translate to center of screen
.scale([1000]); // scale things down so see entire US
var path = d3.geoPath(projection);
// points
var origin = [-122.336422, 47.610902];
var destination = [-73.986740, 40.662688];
var us = d3.json("us-states.json", function(error, us) {
if (error) throw error;
svg.append("g")
.attr("class", "states")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("d", path);
svg.append("path")
.attr("class", "state-borders")
.attr("d", path(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; })));
// add circles to svg
svg.selectAll("circle")
.data([origin,destination]).enter()
.append("circle")
.attr("cx", function (d) { console.log(projection(d)); return projection(d)[0]; })
.attr("cy", function (d) { return projection(d)[1]; })
.attr("r", "8px")
.attr("fill", "red");
var route = svg.append("path")
.datum({type: "LineString", coordinates: [origin, destination]})
.attr("class", "route")
.attr("d", path)
.attr("stroke", "#d3d3d3")
.attr("fill", "none");
var totalLength = route.node().getTotalLength();
route
.attr("stroke-dasharray", totalLength + "," + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(2000)
.ease(d3.easeCubic)
.attr("stroke-dashoffset", totalLength*2)
.transition()
.duration(2000)
.attr("stroke-dashoffset", totalLength*3);
});
</script>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment