/* fundación h-orizontal / Secretaría Distrital de Seguridad de Bogotá Mapa de Actores e Iniciativas del Sistema de Responsabilidad Penal Adolecente v1.0 2018 Aportes y ayuda de - Andrew Reid: https://stackoverflow.com/questions/51411646/d3js-force-layout-on-a-map - rioV8: https://stackoverflow.com/questions/51829097/nodes-as-list-in-force-layout-over-a-map */ //Tamaño de la viz var width = screen.width; var height = screen.height; // ancho y alto cuadro actores var anchoCuadroActores = (width / 100) * 16; var altoCuadroActores = (height / 100) * 80; //Setup del mapa leaflet en un centro específico y un "estilo" (layer) b/n var map = L.map('map', { zoomControl:false }).setView([4.624565, -74.101109], 12); //mapLink = L.tileLayer('https://tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png').addTo(map); //mapLink = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png').addTo(map); //mapLink = L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png').addTo(map); //mapLink = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/rastertiles/voyager_labels_under/{z}/{x}/{y}{r}.png').addTo(map); mapLink = L.tileLayer('https://api.mapbox.com/styles/v1/pierreee1/cjnuqt47g2juo2snde808p6xr/tiles/256/{z}/{x}/{y}@2x?access_token=pk.eyJ1IjoicGllcnJlZWUxIiwiYSI6ImNqazh2dWlzdjFobm4za3AyN2Q5NTAwa3oifQ.ai-LoEOZs22rAXe0br8E0g').addTo(map); map.doubleClickZoom.disable(); //map.dragging.disable(); //map.scrollWheelZoom.disable(); //cuando ya está el mapa se agrega un svg en donde dibujar var svgLayer = L.svg(); svgLayer.addTo(map); //seleccion el svg del mapa y crea un grupo var svg = d3.select("#map").select("svg"); var g = svg.select('g'); // crea los tooltip y le da las características var tooltip = d3.select("body") .append("div") .style("top", ((height / 100) * 20) + "px") .style("left", ((width / 100) * 3) + "px") .attr("class", "tooltip") .style("opacity", 1) ; var tooltip_1 = d3.select("body") .append("div") .style("top", ((height / 100) * 63) + "px") .style("left", ((width / 100) * 4) + "px") .attr("class", "tooltip_1") .style("opacity", 1) ; var tooltip_2 = d3.select("body") .append("div") .style("top", ((height / 100) * 63) + "px") .style("left", ((width / 100) * 11) + "px") .attr("class", "tooltip_2") .style("opacity", 1) ; var tooltip_logo1 = d3.select("body") .append("div") .style("top", ((height / 100) * 71) + "px") .style("left", ((width / 100) * 5) + "px") .html("") .attr("class", "tooltip_logo") .style("opacity", 1) ; var tooltip_logo2 = d3.select("body") .append("div") .style("top", ((height / 100) * 69) + "px") .style("left", ((width / 100) * 10) + "px") .html("") .attr("class", "tooltip_logo") .style("opacity", 1) ; //Define la simulación de fuerza var fuerza = d3.forceSimulation() .force("link", d3.forceLink() .id(function(d){ return d.id; }) ) ; //Leer datos de ambos json y llamar la funcion que dibuja todo d3.json('proyectos y actores_v5.json', function(data){ //pasar los datos a una variable var graph = data; //Printea los datos para verificar console.log("Número de Actores y Proyectos: " + graph.nodes.length) console.log(graph.nodes); console.log("Número de links: " + graph.edges.length) console.log(graph.edges); // cuadro debajo de los actores, la posicion se coloca en la funcion que actualiza todo var cuadroActores = g.append("rect") .attr('width', anchoCuadroActores) .attr('height', altoCuadroActores) .style('fill', "#fafafa") .style('opacity', 0.95) .attr('stroke', "#bbbbbb") .attr('stroke-width', 2) .attr('stroke-dasharray', '10') ; //crea los links entre nodos con un svg y los datos de "edges" var lineas = g.append('g') .selectAll("line") .data(data.edges) .enter() .append("path") .attr('class', "link") ; // decide cuales nodos van en el proceso, cuales en el mapa y cuales de los actores function isNodeOnLegend(d) { return d.tipo === "actor"; } function isNodeOnMap(d){ return d.tipo === "iniciativa" || d.tipo === "iniciativa_juvenil"; } //funcion donde se pintan los nodos function constructNodes(nodeList, className) { //crea el grupo donde pintar los nodos var nodes = g .append("g") .attr("class", className) .selectAll(".nodos") .data(nodeList) .enter() .append("g") .attr("class", "gnode") ; //pinta la nodos, características y tooltip nodes.append("circle") .attr('class', function(d){ if (isNodeOnLegend(d)) { if(d.nuevos == "gestion_nuevos" || d.nuevos == "acompañamiento_nuevos" || d.nuevos == "investigacion_nuevos" || d.nuevos == "judicializacion_nuevos" || d.nuevos == "internacional_nuevos" || d.nuevos == "civil_nuevos"){ return "nodos " + d.nuevos; } else { return "nodos " + d.bloque; } } if (isNodeOnMap(d)) return "nodos " + d.tipo; }) .attr('r', 5) .attr("pointer-events","visible") .on("click", connectedNodes) .on('mouseover', function(d){ tooltip .html(function(){ if (d.tipo == "iniciativa" || d.tipo == "iniciativa_juvenil"){ return "

" + d.id + "

" + d.descripción + "
" ; } else { return "

" + d.id + "

" + d.descripción + "
" + '' + "Página Web" + "" + "
" + "

" + "Relación con la víctima" + "

" + "
" + d.víctima + "
" + "

" + "Relación con el ofensor " + "

" + "
" + d.ofensor; } }) .transition() .style("opacity", 1) ; tooltip_1 .html(function(){ if(d.tipo == "actor") return "actor"; else if(d.tipo == "iniciativa") return "Sede" else if(d.tipo == "iniciativa_juvenil") return "SRPA" }) .style("opacity", 1) .style("background", function(){ if (d.tipo == "actor") return "#000000"; else if(d.tipo == "iniciativa") return "#fff05f"; else if(d.tipo == "iniciativa_juvenil") return "#ffad5f"; }) ; tooltip_2 .html(function(){ if(d.bloque == "gestion" || d.bloque == "acompañamiento" || d.bloque == "investigacion" || d.bloque == "judicializacion" || d.bloque == "internacional" || d.bloque == "civil"){ return d.bloque; } }) .style("opacity", 1) .style("background", function(){ if (d.bloque == "gestion") return "#b9def9"; else if(d.bloque == "acompañamiento") return "#68b3ff"; else if(d.bloque == "investigacion") return "#336cc5"; else if(d.bloque == "judicializacion") return "#202b3f"; else if(d.bloque == "internacional") return "#3881bf"; else if(d.bloque == "civil") return "#243f78"; }) ; }) .attr('opacity', 0.9) ; return nodes; } //guarda los nodos en una variable dependiendo de un filtro var nodesOnMap = constructNodes(graph.nodes.filter(isNodeOnMap), "onmap"); var nodesOnLegend = constructNodes(graph.nodes.filter(isNodeOnLegend), "onlegend"); var nodesAll = g.selectAll(".gnode"); // agrega los textos de los nodos de los actores var textoActores = svg .append("g") .selectAll("text") .data(graph.nodes.filter(isNodeOnLegend)) .enter() .append("text") .text(function(d) { return d.id; }) .attr('class', "text") .attr('dx', "1em") .attr('dy', "0.3em") .attr('font-size', '11') ; //le dice a la simulacion cuales son los nodos y los links fuerza.nodes(graph.nodes); fuerza.force("link").links(graph.edges); //simulación y actualizacion de la posicion de los nodos en cada "tick" fuerza.on("tick", function (){ lineas.attr("d", function(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = (Math.sqrt(dx * dx + dy * dy)); return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; }); //funcion para actualizar la posicion de los nodos (rioV8) function nodeUpdate(nodes) { nodes.attr("transform", function (d) { return `translate(${d.x},${d.y})`; }); } nodeUpdate(nodesOnMap); nodeUpdate(nodesOnLegend); }); //saber si las conexiones se ven o no var toggle = 0; //Crea un arreglo de las cosas que estan conectadas entre si var linkedByIndex = {}; for (i = 0; i < graph.nodes.length; i++) { linkedByIndex[i + "," + i] = 1; }; graph.edges.forEach(function (d) { linkedByIndex[d.source.index + "," + d.target.index] = 1; }); //Funcion para determinar si dos nodos estan conectados function neighboring(a, b) { return linkedByIndex[a.index + "," + b.index]; } // Función para saber que hacer cuando se haga click function connectedNodes() { if (toggle == 0) { //Reduce la opacidad de todo menos de los que esten conectados d = d3.select(this.parentNode).datum(); nodesAll .transition() .style("opacity", function (o) { return neighboring(d, o) | neighboring(o, d) ? 1 : 0; }) ; lineas .transition() .style("opacity", function (o) { return d.index==o.source.index | d.index==o.target.index ? 1 : 0; }) ; textoActores .transition() .style('opacity', function(o){ return neighboring(d, o) | neighboring(o, d) ? 1 : 0; }) d3.selectAll('.tooltip') .style("opacity", 1) ; toggle = 1; } else { // devuelve los nodos a la normalidadlos links invisibles nodesAll .transition() .style("opacity", 1) ; lineas .transition() .style("opacity", 0) ; textoActores .transition() .style('opacity', 1) ; toggle = 0; } } //Function which sets the transformation attribute to move the circles to the correct location on the map function drawAndUpdateCircles(){ //Ubicación de los nodos en el mapa var cuadroActoresLatLon = map.latLngToLayerPoint(map.getBounds().getNorthEast()); var cuadroProcesoLatLon = map.latLngToLayerPoint(map.getBounds().getNorthWest()); //Numero de nods de actores y del proceso var numeroNodosActores = graph.nodes.filter(isNodeOnLegend); // variable del espaciado entre Actores var espaciadoActores = (altoCuadroActores) / numeroNodosActores.length; //si tiene ubicacion, anclelos al mapa nodesOnMap.each(function(d) { if (d.lon && d.lat) { p = new L.LatLng(d.lat, d.lon); var layerPoint = map.latLngToLayerPoint(p); d.fx = layerPoint.x; d.fy = layerPoint.y; } }); // posicion arreglada del cuadro de actores cuadroActores .attr('x', cuadroActoresLatLon.x - (anchoCuadroActores * 1.2)) .attr('y', cuadroActoresLatLon.y + ((height / 100) * 5)) ; // nodos del cuadro de actores nodesOnLegend.each( function (d, i) { d.fx = cuadroActoresLatLon.x - (anchoCuadroActores * 1.13); d.fy = cuadroActoresLatLon.y + ((height / 100) * 6.5) + i * espaciadoActores; }); //textos de los actores textoActores.each(function(d, i, nodesOnLegend){ d3.select(nodesOnLegend[i]) .attr('x', cuadroActoresLatLon.x - (anchoCuadroActores * 1.12) ) .attr('y', cuadroActoresLatLon.y + ((height / 100) * 6.5) + i * espaciadoActores) }); fuerza .alpha(1) .restart() ; } //Dibuja los circulos actualizados en el mapa drawAndUpdateCircles(); map.on("moveend", drawAndUpdateCircles); });