Skip to content

Instantly share code, notes, and snippets.

@rveciana
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rveciana/b62832e7b32f9afc779c to your computer and use it in GitHub Desktop.
Save rveciana/b62832e7b32f9afc779c to your computer and use it in GitHub Desktop.
JSL 2015: Coropletas con tooltip

Décimotercer ejemplo del taller Mapas web interactivos con D3.js en el programa de las 9as Jornadas SIG Libre .

Dibuja un mapa de coropletas con los resultados electorales de las elecciones de 2011. Al pasar el ratón por las provincias, aparece un +tooltip* con el resultado. Fuente: Wikipedia

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.provincias {
fill: #ccc;
stroke: #fff;
}
div.tooltip {
position: absolute;
text-align: center;
width: 70px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script>
var width = 960,
height = 500;
var colores = {"PP":"#03a9e7","PSOE":"#ff2f2e","IU":"#149f27","UPyD":"#d64b8c","CiU":"#024c97","Amaiur":"#b0d2e9",
"PNV":"#0f7c2f","ERC":"#f9d43f","Compromís":"#faddaa","Podemos":"#82398a","Ciudadanos":"#e28535","Otros":"#e8e8e8"};
var projection = d3.geo.mercator()
.center([0,37])
.scale(3000 / Math.PI)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.json("https://cdn.rawgit.com/rveciana/5919944/raw//provincias.json", function(error, provincias) {
d3.json("https://cdn.rawgit.com/rveciana/5919944/raw//resultados.json", function(error, resultados) {
var land = topojson.feature(provincias, provincias.objects.provincias);
svg.selectAll("path")
.data(land.features)
.enter()
.append("path")
.attr("d", path)
.attr("fill", function(d){
var ganador = Object.keys(resultados[d.properties.nombre])[0];
return colores[ganador];
})
.on("mouseover", function(d) {
d3.select(this)
.transition()
.style("stroke-width", 4);
div.transition()
.duration(200)
.style("opacity", 0.9);
var resultados_provincia = "";
var partido;
for (partido in resultados[d.properties.nombre]) {
resultados_provincia += partido + ": " + resultados[d.properties.nombre][partido] + "</br>";
}
div.html("Resultados: <br/>" + resultados_provincia)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
d3.select(this)
.transition()
.style("stroke-width", 0);
div.transition()
.duration(500)
.style("opacity", 0);
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment