function drag() {
let dx, dy;
function subject() {
let s = -1,
dist = Infinity;
for (let i = 0; i < targets.length; i++) {
const p = projection.rotate([0, 0])(targets[i]),
d = Math.hypot(p[0] - d3.event.x, p[1] - d3.event.y);
if (d < 20 && d < dist) {
s = i;
dist = d;
}
}
return s;
}
function dragstarted() {
if (d3.event.subject > -1) {
d3.select(this).style("cursor", "grabbing");
const p = projection.rotate([0, 0])(targets[d3.event.subject]);
dx = d3.event.x - p[0];
dy = d3.event.y - p[1];
}
}
function dragged() {
d3.select(this).style("cursor", "grab");
if (d3.event.subject > -1) {
targets[d3.event.subject] = projection
.rotate([0, 0])
.invert([d3.event.x - dx, d3.event.y - dy]);
}
}
return d3
.drag()
.subject(subject)
.on("start", dragstarted)
.on("drag", dragged);
}