forked from curran's block: Country Centroids on a Map
xxxxxxxxxx
<meta charset="utf-8">
<style>
.link {
fill: none;
stroke: #111;
stroke-width: .5px;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://unpkg.com/topojson@3"></script>
<script src="//d3js.org/queue.v1.min.js"></script>
<script>
var width = 960,
height = 480,
radius = 8,
threshold = 30,
fill = "rgba(255, 49, 255, 0.5)"
var projection = d3.geoEquirectangular()
.scale(153)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geoPath()
.projection(projection);
var g = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
d3.queue()
.defer(d3.json, "https://unpkg.com/world-atlas@1/world/110m.json")
.defer(d3.tsv, "world-country-names.tsv")
.await(ready);
function ready(error, world, names) {
if (error) throw error;
var nodes = []
var links = []
var features = topojson.feature(world, world.objects.countries).features;
features.forEach(function(d, i) {
var centroid = path.centroid(d);
if (centroid.some(isNaN)) return;
centroid.x = centroid[0];
centroid.y = centroid[1];
centroid.feature = d;
for (var i = 0; i < names.length; i++){
if (+(names[i].id) == +(d.id)) {
centroid.name = names[i].name
i = names.length
}
}
nodes.push(centroid);
});
d3.voronoi().links(nodes).forEach(function(link) {
var dx = link.source.x - link.target.x,
dy = link.source.y - link.target.y;
link.distance = Math.sqrt(dx * dx + dy * dy);
//if (link.distance < threshold) {
links.push(link);
//}
});
var force = d3.forceSimulation(nodes)
force.force("x", d3.forceX().x(function(d){ return d[0] }))
force.force("y", d3.forceY().y(function(d){ return d[1] }))
force.force('collision', d3.forceCollide().radius(radius + 2))
force.force("link", d3.forceLink(links)
.strength(0.2)
.distance(function(d){
return d.distance //< threshold ? 20 : 100
})
.iterations(10))
force.stop();
for (var i = 0; i < 120; ++i) force.tick();
g.selectAll("line")
.data(links)
.enter()
.append("line")
.attr("class", "link")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
g.selectAll(".centroid")
.data(nodes)
.enter()
.append("rect")
.attr("class", "centroid")
.attr("fill", fill)
.attr("height", radius*2)
.attr("width", radius*2)
.attr("x", function (d){ return d.x - radius; })
.attr("y", function (d){ return d.y - radius; });
}
</script>
https://d3js.org/d3.v4.min.js
https://unpkg.com/topojson@3
https://d3js.org/queue.v1.min.js