This is in answer to the Stack Overflow question Show info when hovering over voronoi polygons (in D3.js). In this example the title attribute has been used for the 'tooltip' but there are better alternatives around. This example uses an accessor function to specify the x
and y
for the Voronoi polygons and created an object locCities
to store the descriptive variables, although the conversion of co-ordinates using the projection function could have been done in the accessor function and the orginal data used i.e. the cities
variable. Also, note that an old version of d3 has been used due to some change in the Albers Usa projection.
forked from phil-pedruco's block: Map with Voronio Polygons for Tooltip
xxxxxxxxxx
<html>
<head>
<style type="text/css">
#states {
fill: #aaa;
}
</style>
<script src="d3.min3.1.5.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
var width = 960,
height = 500;
var projection = d3.geo.albersUsa();
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var map = svg.append("g").attr("id", "states");
var points = svg.append("g").attr("id", "circles");
var vor = svg.append("g").attr("id", "paths");
var voronoi = d3.geom.voronoi()
.x(function(d) { return (d.coords[0]); })
.y(function(d) { return (d.coords[1]); });
d3.csv("us-cities1.csv", function (cities) {
d3.json("us-states.json", function(error, states) {
var locCities = [];
// create array of co-ordinates for Voronoi
cities.forEach(function (d,i) {
var element = {
coords: projection([+d.lon, +d.lat]),
place: d.place,
rank: d.rank,
population: d.population
};
locCities.push(element);
});
// Create map using geojson
map.selectAll("path")
.data(states.features)
.enter().append("path")
.attr("d", path);
// Place circles on map for reference
points.selectAll("circle")
.data(locCities).enter()
.append("circle")
.attr("id", function (d,i) { return d.place; }) // to confirm correct city allocated to title (note the csv file seems to have some dodgy co-ordinates)
.attr("cx", function (d,i) { return d.coords[0]; })
.attr("cy", function (d,i) { return d.coords[1]; })
.attr("r", "6px")
.style("fill", "red");
// Code based on https://bl.ocks.org/njvack/1405439
// Create Voronoi polygons and add title attribute for tooltip
vor.selectAll("path")
.data(voronoi(locCities))
.enter().append("path")
.attr("d", function(d) { return "M" + d.join(",") + "Z"; })
.style("fill", "white") // polygons need a fill so the titles work
.style('fill-opacity', 0) // set to 0 to 'hide' from view
.style("stroke", "none") // set to none to 'hide' from view
.append("title") // using titles instead of tooltips
.text(function (d,i) { return d.point.place + " ranked " + d.point.rank; });
});
});
</script>
</html>