Skip to content

Instantly share code, notes, and snippets.

@LuisSevillano
Last active February 19, 2017 16:44
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 LuisSevillano/f52c3e97e895321e0bbe777eef3d3972 to your computer and use it in GitHub Desktop.
Save LuisSevillano/f52c3e97e895321e0bbe777eef3d3972 to your computer and use it in GitHub Desktop.
Simple canvas map
border: none
height: 400
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- nuestro mapa se dibujará en este contenedor -->
<div class="map"></div>
<!-- cargamos las dos librerías que necesitamos-->
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script>
// añadimos un elemento canvas a nuestro contenedor
var canvas = d3.select(".map").append("canvas");
// parametros necesarios poder referenciar al conenedor
context = canvas.node().getContext("2d"),
// función de d3 para poder crear mapas
path = d3.geoPath().projection(null).context(context);
// variables sobre el tamaño de nuestro mapa
var width = 960,
height = 300;
// las añadimos al canvas
canvas
.attr("width", width)
.attr("height", height)
.style("width", width + "px")
.style("height", height + "px");
context.lineJoin = 'round';
context.lineCap = 'round';
// establecemos una escala de color.
// Dado que los datos son muy planos, he ajustado la escala al máximo.
var color = d3.scaleThreshold()
.domain([10.8, 12, 13.6, 14.3, 14.6, 15.6])
.range(["#f7fcf0","#e0f3db","#ccebc5","#a8ddb5","#7bccc4","#4eb3d3"]);
// con este método cargamos el json (!)
// d3 tiene métodos específicos como d3.csv, de.json, d3.tsv
// Con d3.queue podemos cargar varios archivos (csv's, mapas, jsons...)
// una vez cargado llamará a la función ready
d3.queue()
.defer(d3.json, "map.json")
.await(ready);
// esta función recibe como parametro nuestro mapa
// para aclararnos la hemos llamado 'map' (podríamos llamarla como quisieramos)
function ready(error, map) {
if (error) throw error;
// variable que almacena todos los polígonos del mapa con topojson
var municipalities = topojson.feature(map, map.objects.municipalities).features
//vamos a utilizar un bucle for para iterar por todas las unidades del mapa, un bucle por cada municipio
// queremos conocer exactamente el valo de la tasa de paro en cada iteración
for (var i = 0; i < municipalities.length; i++) {
// almacenamos en una variable el valor de la tasa de paro
var desempleo = municipalities[i].properties.csv_desemp;
// la asociamos al canvas con .fillStyle()
context.fillStyle = color(desempleo)
// indicamos que vamos a comenzar a dibujar un path o polígono
context.beginPath()
// pasamos al método de d3 (path()) arriba definido la unidad espacial correspondiente
path(municipalities[i]);
// la coloreamos
context.fill()
}
// estos pasos son similares para el dibujo
// de los contornos de los municipios
// esta vez no iteramos sino que los dibujamos todos de una vez
// color del contorno
context.strokeStyle = "white"
// una línea discontínua
context.setLineDash([1,3])
// grosor de línea
context.lineWidth = .9;
// pasamos a la función TODOS los polígonos
path(topojson.feature(map, map.objects.municipalities));
// dibujamos el contorno
context.stroke()
// reseteamos la línea discontínua
context.setLineDash([0])
// a partir de este momento cualquier línea será continua
// dibujamos el contorno de la isla
context.strokeStyle = "rgb(0, 0, 0)";
context.lineWidth = 0.3;
context.beginPath()
path(topojson.feature(map, map.objects.island));
context.stroke()
};
</script>
</body>
</html>
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment