-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
740 lines (688 loc) · 29 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
<!DOCTYPE html>
<!-- Copyright (C) 2018 André Ourednik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
<html>
<head>
<meta charset="utf-8">
<meta title="GéoRécits">
<script src="d3/d3.v5.min.js"></script>
<script src="d3/d3-geo.v1.min.js"></script>
<script src="d3/d3-geo-projection.v2.min.js"></script>
<script src="d3/d3-scale-chromatic.v0.3.min.js"></script>
<style>
h1 {
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana;
font-size: 13px;
position:fixed;
right:20px;
bottom: 15px;
padding:0;
margin:0;
z-index: 1000;
}
button{
position:fixed;
top:20px;
z-index: 1000;
}
#maptofile{left:20px;}
#nettofile{right:20px;}
.dropzone, .dropzonebottom {
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana;
font-size:11px;
position:fixed;
color:lightgrey;
left: 50%;
transform: translateX(-50%);
width: 60%;
text-align: center;
z-index:1000;
}
.dropzone {
top:17px;
}
.dropzonebottom {
bottom:37px;
}
#dropzone1, #dropzone2, #dropzone3 {
position: absolute;
width:45%;
padding: 3px;
height:20px;
background-color: lightgrey;
filter:blur(5px);
}
#dropzone1 {left:0;}
#dropzone2 {right:0;}
#dropzone1text, #dropzone2text, #dropzone3text {
position: absolute;
width:45%;
padding: 6px;
color:white;
}
#dropzone1text {left:0;}
#dropzone2text {right:0;}
#dropzone3 {left:0;}
#dropzone3text {left:0;}
#topomap {
position:fixed;
top:5px;
left:5px;
border:black solid 0.5px;
}
#network {
position:fixed;
top:5px;
right:5px;
border:black solid 0.5px;
}
#sqrtscale {
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana;
font-size: 13px;
z-index: 1000;
position:fixed;
bottom: 14px;
left: 52%;
}
circle:hover{
stroke:black;
stroke-width:2px;
}
</style>
</head>
<body>
<h1>GéoRécits - <a href="https://ourednik.info/georecits">ourednik.info/georecits</a></h1>
<button id="maptofile" onClick="saveSvg('topomap', 'georecit_map.svg')">Save Map SVG</button>
<button id="nettofile" onClick="saveSvg('network', 'georecit_network.svg')">Save Network SVG</button>
<div class="dropzone" >
<div id="dropzone1"></div>
<div id="dropzone2"></div>
<div id="dropzone1text" ondrop="dropHandler(event,1);" ondragover="dragOverHandler(event,1);" ondragleave="dragLeaveHandler(event,1)">Drag <i>places.csv</i> here...</div>
<div id="dropzone2text" ondrop="dropHandler(event,2);" ondragover="dragOverHandler(event,2);" ondragleave="dragLeaveHandler(event,2)">Drag <i>movements.csv</i> here...</div>
</div>
<div class="dropzonebottom" >
<div id="dropzone3"></div>
<div id="dropzone3text" ondrop="dropHandler(event,3);" ondragover="dragOverHandler(event,3);" ondragleave="dragLeaveHandler(event,3)">Drag <i>basemap.geojson</i> here...</div>
</div>
<div id="sqrtscale">√ line length <input type="checkbox" id="myCheck" onclick="GraphView()"></div>
<svg id="topomap"></svg>
<svg id="network"></svg>
<script>
var w = window,
doc = document,
el = doc.documentElement,
bod = doc.getElementsByTagName('body')[0],
wid = w.innerWidth || el.clientWidth || bod.clientWidth,
hei = w.innerHeight|| el.clientHeight|| bod.clientHeight;
var width = wid/2 - 8,
height = hei-10;
var topomap = d3.select("#topomap")
.attr("width",width)
.attr("height",height);
var network = d3.select("#network")
.attr("width",width)
.attr("height",height);
var colorScale = d3.scaleOrdinal(d3.schemeCategory10);
var circlesizer, linewidthsizer, placesmovements, basemap, p, placelessmovements = Array(), pojection, dropzone = 0;
var sqrtscale = false; // this is for the network
function uppercaseKeys(d) {
Object.keys(d).forEach(function(origProp) {
var lowerCaseProp = 'ABCD' + origProp.toLocaleUpperCase();
if (origProp != 'source' & origProp != 'target' & lowerCaseProp !== origProp) {
d[lowerCaseProp] = d[origProp];
delete d[origProp];
}
});
return d;
}
Promise.all([
d3.csv("data/places.csv"),
d3.csv("data/movements.csv"),
d3.json("data/basemap.geojson")
]).then(([pla,mov,bas]) => {
space = {
'places' : pla,
'movements' : mov
};
// spacebackup = JSON.parse(JSON.stringify(space)); // a untouchable clone of space
basemap = bas;
render(""); // the csv content is empty on startup
});
function render(filecontent) {
filecontent = filecontent.replace(/;/g,",").replace(/, /g,",");
//~ var filecontent =
//~ `source,target,idperson,time
//~ "Khovsgol","OulanBator",1,540
//~ "OulanBator","Zurich",1,1200
//~ "Zurich","Neuchatel",1,60
//~ "Paris","Geneve",2,180`
if (dropzone == 1 | dropzone == 2) {
var parsedcsv = d3.csvParse(filecontent);
console.log("parsed csv",parsedcsv);
if (dropzone == 1) {space['places'] = parsedcsv;}
else if (dropzone == 2) {space['movements'] = parsedcsv;}
} else if (dropzone == 3) {
try {
basemap = JSON.parse(filecontent);
} catch(e) {
var errtext = "The basemap you have uploaded does not appear to be in GeoJSON format\n\n";
alert(errtext + e);
throw new Error(errtext + e);
}
}
space['places'] = space['places'].filter(sp => sp.id != '' & typeof sp.id != 'undefined'); // empty places can be produced by empty lines in the csv. This filters them out.
space['movements'] = space['movements'].filter(sm => sm.source != '' & typeof sm.source != 'undefined'); // empty places can be produced by empty lines in the csv. This filters them out.
console.log("space",space);
definepandsizers();
TopoView();
if (dropzone != 3) { // on changed basemap, no need to redraw network view
var targets = Array();
space['movements'].forEach(movement => { // keyed representation of places for later variables retrieval
targets.push(movement.target);
});
// console.log("targets",targets);
if (Object.keys(p).includes('GOAL') & targets.includes('GOAL') ) {
GraphViewGoal();
} else {
GraphView();
}
}
}
function definepandsizers() {
p=Array();
space['places'].forEach(place => { // keyed representation of places for later variables retrieval
p[place.id] = place;
});
// console.log("p",p);
errorhandling(); // long execution, could need to make this to a promise.
// Set sizers, defaulting 5 and 1 for missing values for frequency and duration
circlesizer = space['places'][0].duration ?
d3.scalePow().exponent(0.5).range([5, 25]).domain(
d3.extent(space['places'],function(d) { return +d.duration})
) : function (d) {return 5;}
;
linewidthsizer = space['movements'][0].frequency ?
d3.scaleLinear().range([1, 10]).domain(
d3.extent(space['movements'],function(d) { return +d.frequency})
) : function (d) {return 1;}
;
}
function errorhandling () {
// console.log('Error handling');
if (dropzone == 1 & typeof space['places'][0] === 'undefined') { // we have filtered out all places without id before
alert('No “id” column in places.csv.\n\nHave you uploaded the correct file to the correct zone?\n\nSee the documentation on https://ourednik.info/georecits');
throw new Error("places.csv in incorrect format!");
}
if (dropzone == 2 & typeof space['movements'][0] === 'undefined') {
alert('No “source” column in movements.csv.\n\nHave you uploaded the correct file to the correct zone?\n\nSee the documentation on https://ourednik.info/georecits');
throw new Error("movements.csv in incorrect format!");
}
var placesCount = d3.nest()
.key(function(d) { return d.id; })
.rollup(function(v) { return v.length; })
.entries(space['places']);
// console.log("placesCount", placesCount);
var duplicateplaces = placesCount.filter(p => p.value > 1);
if (duplicateplaces.length > 0) {
var duplicateplacest = Array();
duplicateplaces.forEach(place => { // keyed representation of places for later variables retrieval
duplicateplacest[place.key] = place.value;
});
console.log("Duplicate places !", duplicateplacest);
alert(
"The following place id's appear more than once. Please verify places.csv : \n\n" +
Object.keys(duplicateplacest).join('\n')
+ "\n\nSee the documentation on ourednik.info/georecits"
);
}
var movementPlaces = Array();
space['movements'].forEach(m => {
movementPlaces[m.source]={'placed':Object.keys(p).includes(m.source),'idperson':m.idperson};
movementPlaces[m.target]={'placed':Object.keys(p).includes(m.target),'idperson':m.idperson};
});
// console.log("movementPlaces", movementPlaces);
placelessmovements = Array(); // empty it
Object.keys(movementPlaces).filter(key => movementPlaces[key].placed !== true).forEach(mpkey => {
placelessmovements[mpkey] = movementPlaces[mpkey];
});
// console.log("placeless movements", placelessmovements);
if (Object.keys(placelessmovements).length > 0) {
console.log("placeless movements", placelessmovements);
network.selectAll('*').remove();
alert(
`The following movements in movements.csv refer to places without coordinates:\n\n` +
Object.keys(placelessmovements).join('\n')
+ `\n\nPlease add these places to places.csv or remove them from your movements.csv file.
\nSee the documentation on ourednik.info/georecits`
);
}
// console.log("space end error handling",space);
}
/////////////////////////////////////////////////
// Topographic view.
function TopoView() {
// console.log("TOPOVIEW")
// if (transform != null) { console.log("d3 zoom transform", transform); }
topomap.selectAll('*').remove();
if (dropzone != 3) { // no need to redefine projection if replaced basemap
var minlon = d3.min(space['places'],function(d) { return +d.lon});
var minlat = d3.min(space['places'],function(d) { return +d.lat});
var maxlon = d3.max(space['places'],function(d) { return +d.lon});
var maxlat = d3.max(space['places'],function(d) { return +d.lat});
var clon = (minlon+maxlon) / 2;
var clat = (minlat+maxlat) / 2;
var center = [clon,clat] // in spherical coordinates, normaly
var offset = [width/2, height/2];
var scale = (width - 1) / 2 / Math.PI; // shows the whole world
s = (Math.min(
360/Math.abs(Math.abs(minlon)-Math.abs(maxlon)),
180/Math.abs(Math.abs(minlat)-Math.abs(maxlat))
));
scale = scale * 0.8 * s;
projection = d3.geoNaturalEarth1()// automatic centering has trouble with the more fun polyedric projections
.precision(0.1)
.scale(scale)
.center(center)
.translate(offset)
;
}
var path = d3.geoPath().projection(projection);
var zoom = d3.zoom()
.scaleExtent([0.2, 100])
.on("zoom", zoomed);
topomap.call(zoom);
topomap.append("g")
.selectAll("path")
.data(basemap.features)
.enter().append("path")
.attr("d", path)
.attr("fill", "lightgrey")
.attr("stroke","white")
;
topomap.append("g")
.selectAll("circle")
.data(space['places'].sort(function(a, b) { return b.duration - a.duration; }))
.enter().append("circle")
.attr("cx", function (d) { return projection([d.lon,d.lat])[0]; })
.attr("cy", function (d) { return projection([d.lon,d.lat])[1]; })
.attr("r", function (d) { return circlesizer(d.duration); })
.attr("fill", function (d) { return colorScale(d.idperson);})
.attr("fill-opacity", 0.7)
;
topomap.append("g")
.selectAll("text")
.data(space['places'])
.enter()
.append("text")
.text(function(d) { return d.nameplace; })
.style("fill", "#555")
.style("font-family", "Arial")
.style("font-size", "9px")
.attr("x", function (d) { return projection([d.lon,d.lat])[0] + (circlesizer(d.duration)/1.414) ; })
.attr("y", function (d) { return projection([d.lon,d.lat])[1] - (circlesizer(d.duration)/1.414) ; })
.style("pointer-events", "none") // to prevent mouseover/drag capture
;
linecoors = function(id) {
if (typeof p[id] !== "undefined") {
return projection([p[id].lon,p[id].lat]);
} else return [0.5*width,0.1*height];
}
topomap.append("g")
.selectAll("line")
.data(space['movements'].sort(function(a, b) { return b.frequency - a.frequency; }))
.enter().append("line")
.attr("x1", function (d) { return linecoors(d.source)[0]; })
.attr("y1", function (d) { return linecoors(d.source)[1]; })
.attr("x2", function (d) { return linecoors(d.target)[0]; })
.attr("y2", function (d) { return linecoors(d.target)[1]; })
.attr("stroke", function (d) { return colorScale(d.idperson); })
.attr("stroke-width",function (d) { return linewidthsizer( d.frequency ) ; })
;
if (Object.keys(placelessmovements).length > 0) {
topomap.append("text").text("Where is " + Object.keys(placelessmovements).join() + "?")
.attr("x",width/2 - Object.keys(placelessmovements).join().length * 4)
.attr("y",0.1*height)
.style("font-family", "'Monaco',monospace")
.style("font-size", "10px")
.style("font-weight", "bold")
// .style("fill", "red")
;
}
if (dropzone == 3 & typeof transform != 'undefined') {
zoom.transform(topomap, transform);
dropzone = 0; // not necessary, but just to make sure.
}
function zoomed() {
transform = d3.event.transform;
topomap.selectAll("g")
.attr("transform", transform)
.style("stroke-width", 1 / transform.k + "px")
;
topomap.selectAll("g").selectAll("line")
.attr("stroke-width",function (d) { return linewidthsizer(d.frequency) / transform.k; })
;
topomap.selectAll("g").selectAll("circle") // keep circles the same size
.attr("r",function(d) {return circlesizer(d.duration) / transform.k;})
;
topomap.selectAll("g").selectAll("text")
.style("font-size", 9 / transform.k + "px")
.attr("x", function (d) { return projection([d.lon,d.lat])[0] + (circlesizer(d.duration)/1.414) / transform.k ; })
.attr("y", function (d) { return projection([d.lon,d.lat])[1] - (circlesizer(d.duration)/1.414) / transform.k ; })
;
}
// console.log("space end topoview",space);
}
/////////////////////////////////////////////////
// Graph view 1 : force-directed --------------------------------
function GraphView() {
d3.select("#sqrtscale").style( "visibility", "visible");
network.selectAll('*').remove();
// Even if we make a local copy of space['places'] and space['movements'],
// functions like simulation.force('link').links(space['movements']) modify the orginal space object
// adding data from trom places to movements.csv making it unusable for other visuals
// This is standard javascript behavior. The orkaround is to make a deep copy of the object
var places = JSON.parse(JSON.stringify(space['places'])) ;
var movements = JSON.parse(JSON.stringify(space['movements']));
Object.keys(placelessmovements).forEach(pmkey => {
places.push({
'id':pmkey,
'nameplace': '[ ' + pmkey + ' ? ]',
'personid':placelessmovements[pmkey].idperson,
'lat':'placeless',
'duration':0
})
});
places = places.filter(pl => typeof pl.id !== 'undefined');
// console.log("places",places);
// console.log("movements",movements);
var linesizer = function(tm) {
sqrtscale = document.getElementById("myCheck").checked;
var sumtimes = d3.sum(movements,function(d) { return +d.time});
var t = tm;
if (sqrtscale) {
sumtimes = Math.sqrt(sumtimes) ;
t = Math.sqrt(tm) ;
}
var multiplier = Math.min(
width / sumtimes,
height / sumtimes
);
return t * multiplier ;
};
var simulation = d3.forceSimulation()
.force('charge', d3.forceManyBody()
.strength(-200)
.distanceMax(width/2)
)
.force('center', d3.forceCenter(width / 2, height / 2)) // translates nodes uniformly so that the mean position of all nodes (the center of mass if all nodes have equal weight) is at the given position ⟨x,y⟩
.force('link',d3.forceLink()
.id(function(d) { return d.id; })
.distance(function(d) { return linesizer(d.time); }).strength(2)
)
//.force("y", d3.forceY(0))
//.force("x", d3.forceX(0))
//.force("r",d3.forceRadial(width/2).strength(0.1))
.on('tick', ticked);
;
simulation.nodes(places);
simulation.force('link').links(movements); // Do not apply this directly to space['movements']: it changes the original array!
// draw the lines first, we want them below circles the background
var links = network.selectAll('lines')
.data(movements)
.enter()
.append("line")
.attr("stroke", function (d) { return colorScale(d.idperson); })
.attr("stroke-width",function (d) { return linewidthsizer(d.frequency); })
;
var nodes = network.selectAll('circle')
.data(places).enter()
.append('g')
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended)
);
;
nodes.append('circle')
.attr('r', function (d) { return circlesizer(d.duration); })
.attr('stroke','none')
.attr('fill',function (d) { return colorScale(d.idperson);})
.attr("fill-opacity", 0.9)
;
nodes.append("text")
.text(function(d) { return d.nameplace; })
.style("fill", "#555")
.style("font-family", "Arial")
.style("font-size", "9px")
.attr("x", function (d) { return (circlesizer(d.duration)/1.414) ; })
.attr("y", function (d) { return - (circlesizer(d.duration)/1.414) ; })
.style("pointer-events", "none") // to prevent mouseover/drag capture
.style("z-index",100); // SVG 2.0 property. Bugged in Firefox for now.
function ticked() {
// width and height are involved, so the nodes cannot escape outside the window.
nodes
.attr("transform", function(d){return "translate("+
Math.max(25, Math.min(width - 25, d.x))
+","+
Math.max(25, Math.min(height - 25, d.y))
+")"})
;
// links just follow the nodes, since simulation.force('link').links(movements) has replaced all source and target values in movements with identified object in places
links
.attr("x1", function(d) { return Math.max(25, Math.min(width - 25, d.source.x)); })
.attr("y1", function(d) { return Math.max(25, Math.min(height - 25, d.source.y)); })
.attr("x2", function(d) { return Math.max(25, Math.min(width - 25, d.target.x)); })
.attr("y2", function(d) { return Math.max(25, Math.min(height - 25, d.target.y)); })
;
}
function dragstarted() {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
}
function dragged() {
d3.event.subject.fx = d3.event.x;
d3.event.subject.fy = d3.event.y;
}
function dragended() {
if (!d3.event.active) simulation.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}
}
/////////////////////////////////////////////////
// GRAPH VIEW 2 : common GOAL, vertical time ---------
function GraphViewGoal() {
d3.select("#sqrtscale").style( "visibility", "hidden");
network.selectAll('*').remove();
network.append('rect')
.attr('width',width*0.9)
.attr('height',25)
.attr("transform", "translate(" +width * 0.05 + ",50)")
.attr("rx",10)
.attr("ry",10)
;
network.append('text')
.text(space['places'].filter(p => p.id == "GOAL")[0].nameplace)
.attr('x','50%')
.attr('y','68')
.attr("alignement-base","middle")
.attr('fill','white')
.attr('letter-spacing','2px') // works only in Chrome and Safari
;
var iplaces = d3.nest()
.key(function(d) { return d.idperson;})
.rollup(function(d) {
return d3.sum(d, function(g) {return g.duration; });
})
.entries(space['places']);
console.log("iplaces",iplaces);
var imovements = d3.nest()
.key(function(d) { return d.idperson;})
.rollup(function(d) {
return d3.sum(d, function(g) {return g.time; });
})
.entries(space['movements']);
console.log("iplaces",imovements);
var individuals = iplaces.concat(imovements);
var individuals = d3.nest()
.key(function(d) { return d.key;})
.rollup(function(d) {
return d3.sum(d, function(g) {return g.value; });
}).entries(individuals);
console.log("individuals",individuals);
var xpositions = Array();
individuals.forEach(individual => {
xpositions[individual.key] = (individuals.indexOf(individual) + 1) * width / (individuals.length + 1);
});
// console.log("xpositions", xpositions);
var maxvlength = d3.max(individuals,function(d) { return +d.value});
// console.log(maxvlength);
var vscaler = function(l) {
return (l / maxvlength) * (height*0.75);
};
individuals.forEach(individual => {
network.append('line')
.attr("x1", xpositions[individual.key])
.attr("y1", 75)
.attr("x2", xpositions[individual.key])
.attr("y2", vscaler(individual.value))
.attr("stroke", colorScale(individual.key))
.attr("stroke-width", 2)
;
// etaps
var mov = space['movements'].filter(m => m.idperson == individual.key);
// console.log(mov);
var start = mov.filter(m => m.target == "GOAL");
// console.log(start);
var y2 = 75;
var y1 = y2;
while (start.length > 0) {
y1 = y2;
y2 = y1 + vscaler(start[0].time);
network.append('line')
.attr("x1", xpositions[individual.key])
.attr("y1", y1)
.attr("x2", xpositions[individual.key])
.attr("y2", y2)
.attr("stroke", colorScale(individual.key))
.attr("stroke-width", 2)
;
network.append('text')
.text(
space['places'].filter(p => p.id == start[0].source)[0].nameplace
+ " → " +
space['places'].filter(p => p.id == start[0].target)[0].nameplace
)
.style("fill", colorScale(individual.key))
.style("font-family", "Arial")
.style("font-size", "9px")
.attr("x", xpositions[individual.key] + 10)
.attr("y", (y2+y1)/2 + 3)
.style("pointer-events", "none"); // to prevent mouseover/drag capture
;
y1 = y2;
y2 = y1 + vscaler(space['places'].filter(p => p.id == start[0].source)[0].duration);
// console.log(y2);
network.append('line')
.attr("x1", xpositions[individual.key])
.attr("y1", y1)
.attr("x2", xpositions[individual.key])
.attr("y2", y2)
.attr("stroke", colorScale(individual.key))
.attr("stroke-width",6)
;
network.append('text')
.text(space['places'].filter(p => p.id == start[0].source)[0].nameplace)
.style("fill", colorScale(individual.key))
.style("font-family", "Arial")
.style("font-size", "9px")
.attr("x", xpositions[individual.key] + 10)
.attr("y", (y2+y1)/2 + 3)
.style("pointer-events", "none"); // to prevent mouseover/drag capture
;
start = mov.filter(m => m.target == start[0].source);
}
});
// console.log("space after goalview",space);
}
/////////////////////////////////////////////////
// Export graphics as SVG.
function saveSvg(svgEl, name) {
var svgEl = document.getElementById(svgEl);
svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg");
var svgData = svgEl.outerHTML;
var preface = '<?xml version="1.0" standalone="no"?>\r\n';
var svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = name;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
/////////////////////////////////////////////////
// Drag and drop data into the interface.
function dropHandler(ev,zone) {
ev.preventDefault(); // Prevent default behavior (Prevent file from being opened)
console.log("---- DROPHANDLER ---");
dropzone = zone;
d3.select('#dropzone' + zone + 'text').style('font-weight','normal');
d3.select('#dropzone' + zone ).style('filter','blur(5px)');
var filecontent, file;
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[i].kind === 'file') {
file = ev.dataTransfer.items[i].getAsFile();
// console.log('... file[' + i + '].name = ' + file.name);
var reader = new FileReader();
reader.onload = function(event) {
filecontent = event.target.result;
console.log(file);
// console.log("file content", filecontent);
render(filecontent);
};
reader.readAsText(file); // this calls the reader.onload
}
}
} else {
// TODO : fallback: Use DataTransfer interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
}
}
removeDragData(ev, zone) // Pass event to removeDragData for cleanup
}
function dragOverHandler(ev,zone) {
ev.preventDefault(); // Prevent default behavior (Prevent file from being opened as such by the browser)
d3.select('#dropzone' + zone + 'text').style('font-weight','bold');
d3.select('#dropzone' + zone ).style('filter','blur(9px)');
}
function dragLeaveHandler(ev,zone) {
ev.preventDefault(); // Prevent default behavior (Prevent file from being opened as such by the browser)
d3.select('#dropzone' + zone + 'text').style('font-weight','normal');
d3.select('#dropzone' + zone ).style('filter','blur(5px)');
}
function removeDragData(ev,zone) {
if (ev.dataTransfer.items) {
ev.dataTransfer.items.clear(); // Use DataTransferItemList interface to remove the drag data
} else {
ev.dataTransfer.clearData(); // Use DataTransfer interface to remove the drag data
}
}
</script>
</body>
</html>