I'm new to D3 and I want to call my function drawlink to draw lines between some of my elements. I tried adding an each call to my link variable to call it, i.e.:
var link = layer.selectAll(".link")
.data(data.links)
.enter().append("line")
.attr("class", "link")
.each(drawlink);
but that did not work. Before I add that line I have got the stage where the Google Map has drawn and my 4 svg elements have been drawn.
How should I be doing this ? Other code improvement comments very welcome too.
stations.json
{
"nodes":[
{"name":"A","long":0.0000,"lat":51.4800},
{"name":"B","long":-0.1684,"lat":51.4875},
{"name":"C","long":-0.2043,"lat":51.5096},
{"name":"D","long":-0.1269,"lat":51.5295}
],
"links":[
{"source":0,"target":1},
{"source":0,"target":2},
{"source":0,"target":3},
{"source":2,"target":3}
]
}
index.html
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<html>
<head>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<style>
html, body, #map {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.link {
stroke: #ccc;
stroke-width: 1.5px;
}
.stations, .stations svg {
position: absolute;
}
.stations svg {
width: 60px;
height: 20px;
padding-right: 100px;
font: 12px sans-serif;
}
.stations circle {
fill: brown;
stroke: black;
stroke-width: 1.5px;
}
</style>
</head>
<body>
<div id="map" style="width: 1200px; height: 600px;"></div>
<script type="text/javascript">
// Create the Google Map…
var map = new google.maps.Map(d3.select("#map").node(), {
zoom: 12,
center: new google.maps.LatLng(51.5195, -0.1269),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
d3.json("stations.json", function(error, data) {
if (error) throw error;
var overlay = new google.maps.OverlayView();
overlay.onAdd = function() {
var layer = d3.select(this.getPanes().overlayLayer).append("div")
.attr("class", "stations");
overlay.draw = function() {
var projection = this.getProjection(),
padding = 10;
var node = layer.selectAll(".stations")
.data(data.nodes)
.each(transform)
.enter().append("svg")
.each(transform)
.attr("class", "node");
var link = layer.selectAll(".link")
.data(data.links)
.enter().append("line")
.attr("class", "link");
node.append("circle")
.attr("r", 4.5)
.attr("cx", padding)
.attr("cy", padding);
node.append("text")
.attr("x", padding + 7)
.attr("y", padding)
.attr("dy", ".31em")
.text(function(d) { return d.name; });
function transform(d) {
d = new google.maps.LatLng(d.lat, d.long);
d = projection.fromLatLngToDivPixel(d);
return d3.select(this)
.style("left", (d.x - padding) + "px")
.style("top", (d.y - padding) + "px");
}
function drawlink(d) {
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; });
}
};
};
overlay.setMap(map);
});
</script>
</body>
</html>
See Question&Answers more detail:
os