-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbaltimore.html
More file actions
964 lines (742 loc) · 27.3 KB
/
baltimore.html
File metadata and controls
964 lines (742 loc) · 27.3 KB
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Cure Violence - Crime Heatmap</title>
<script type='text/javascript' src='http://maps.google.com/maps/api/js?key=AIzaSyA5dv_GtqtKCJ0LLVj820Zcx0fF2GfrE-I'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans:700,300' rel='stylesheet' type='text/css'>
<style>
* {
padding:0;
margin:0;
font-family: 'Open Sans', sans-serif;
font-weight:300;
//disable selection
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
html, body {
width: 100%;
height: 100%;
color:black;
background: #95DB8F;
}
#header {
z-index:99;
margin: 20px;
position: fixed;
}
#incidents {
z-index:99;
margin-left: 20px;
margin-top: 90px;
position: fixed;
}
#burden {
z-index:99;
margin-left: 20px;
margin-top: 150px;
position: fixed;
}
h1 {
font-size:45px;
font-weight:700;
line-height: 160%;
margin:0 25px 0 10px;
display:block;
float:left;
}
h1 span {
font-size: 53px;
font-weight:300;
}
#animation-control-button {
float:left;
}
#animation-control-button .play {
border: solid transparent;
margin-left: 5px;
border-width: 25px 0px 25px 39px;
border-left-color: black;
height:0;
width:0;
}
#animation-control-button .pause {
width: 20px;
height: 50px;
border-left: 12px solid black;
border-right: 12px solid black;
}
#heatmapArea {
height: 100%;
width: 100%;
}
#progress-bar-background {
position:fixed;
width:100%;
height:3px;
left:0;
bottom:0;
background:white;
z-index:98;
}
#progress-bar-container {
position:fixed;
overflow:visible;
left:0;
bottom:0;
z-index:99;
}
#progress-bar-pointer {
position: absolute;
right:-160px;
bottom:0;
right:0;
background:#87D69B;
margin-right: -45px;
margin-bottom:20px;
padding-top:17px;
text-align:center;
height:80px;
width:90px;
line-height:150%;
cursor: pointer;
}
#progress-bar-pointer:after {
position: absolute;
content: ' ';
top: 100%;
left: 50%;
border: solid transparent;
border-top-color: #87D69B;
border-width: 15px;
margin-left: -15px;
}
#progress-bar-pointer .date-prefix {
font-size:10px;
}
#progress-bar-pointer .year {
font-size:13px;
}
#progress-bar {
position:absolute;
background:#327CCB;
width:100%;
left:0;
bottom:0;
height:3px;
}
.button {
text-decoration:none;
color:black;
padding:10px;
display:block;
background:#87D69B;
-moz-box-shadow:-5px 5px #222;
-webkit-box-shadow:-5px 5px #222;
box-shadow:-5px 5px #222;
}
.button:hover {
background:#AAEBBB;
}
.button:active {
margin: 3px -3px;
box-shadow:-2px 2px #222;
}
a.button {
display:inline-block;
font-size:20px;
padding:15px;
}
.button.button-right {
float:right;
display:block;
text-decoration:none;
color:black;
padding:15px;
display:block;
background:white;
font-size: 16px;
-moz-box-shadow:5px 5px #222;
-webkit-box-shadow:5px 5px #222;
box-shadow: 5px 5px #222;
margin-right:5px;
}
.button.button-right:hover {
background:#DFD;
}
.button.button-right:active {
box-shadow:2px 2px #222;
margin: 3px 2px -3px 3px;
}
#options-button {margin-right:0;}
#options-button:active {margin: 3px -3px -3px 3px;}
#options, {position:fixed;top:60px;right:0;z-index:97;text-align:right;}
#options-area {
position:fixed;
top:0;
right:0;
z-index: 101;
}
#options-area li {
float:right;
clear:both;
list-style:none;
width:200px;
padding:8px 13px;
margin-right:-240px;
transition:margin-right .25s ease-in-out;
-moz-transition:margin-right .25s ease-in-out;
-webkit-transition:margin-right .25s ease-in-out;
font-size:14px;
background:#BFEADD;
}
#options li:nth-child(5n+1){background:#acf39d;}
#options li:nth-child(5n+2){background:#e85f5c;}
#options li:nth-child(5n+3){background:#9cfffa;}
#options li:nth-child(5n+4){background:#f2688a;}
#options li:nth-child(5n+5){background:#e3b5a4;}
#options-area li.title {
margin-top: 10px;
font-size: 16px;
background:white;
}
input {
margin:10px;
}
a.button {
display:inline-block;
font-size:20px;
padding:15px;
}
</style>
</head>
<body>
<div id=header>
<h1>Gun <span>Violence</span></h1>
<div id='animation-control-button' class=button>
<div class='pause'></div>
</div>
</div>
<div id=incidents>
<h1>Incidents: <span id=incident_value>0</span></h1>
</div>
<div id=burden>
<h1>Burden: <span id=burden_value>$0</span></h1>
</div>
<div id=options-area>
<a href='#' id='options-button' class='button button-right'>options</a>
<ul id=options>
<li class=title id=filter>Filters
<li class=title>Crime Markers
<li><label for='options-markers'>Show on Pause</label><input id='options-markers' type='checkbox' name='crime-markers' unchecked>
<li class=title>Other Cities
<li><label for='options-markers'><a href="newyork.html">New York, NY</a></label>
<li><label for='options-markers'><a href="chicago.html">Chicago, IL</a></label>
</ul>
</div>
<div id='heatmapArea'></div>
<div id='progress-bar-background'> </div>
<div id='progress-bar-container'>
<div id='progress-bar-pointer-container'>
<div id='progress-bar-pointer' onclick='void(0)'></div>
</div>
<div id='progress-bar'> </div>
</div>
<script type='text/javascript' src='libraries/heatmap.js'></script>
<script type='text/javascript' src='libraries/gmaps-heatmap.js'></script>
<script type='text/javascript'>
//http://heatmapdemo.alastair.is/js/map/heatmaplayer.js
//http://eightmedia.github.io/hammer.js/
var DAY_IN_MILLI = 1000 * 60 * 60 * 24;
var userAgent = navigator.userAgent.toLowerCase();
var isMobile = typeof window.orientation !== 'undefined' && !userAgent.match(/iPad/i);
var isBrowserFast = /webkit/.test(userAgent);
if(userAgent.indexOf('msie') >= 0 ? parseInt(navigator.userAgent.toLowerCase().split('msie')[1]) < 9 : false)
alert('This browser is too old to run this app.\nPlease try with a different browser.');
/*
* emits events after each animation frame and after animation is complete
*/
var CrimeAnimator = function(data, codes, heatmap, map) {
this.map = map;
this.data = data;
this.codes = codes;
this.heatmap = heatmap;
this.dataLength = data.length - 1;
//create marker array to track displayed markers and the info window that displays when they are clicked
this.markers = [];
this.showMarkers = false;
this.markerInfoWindow = new google.maps.InfoWindow();
//figure out the date range
this.dateRange = {start: data[0].epoch, end: data[data.length-1].epoch};
this.dayRange = Math.ceil((this.dateRange.end - this.dateRange.start) / DAY_IN_MILLI);
this.isPaused = false;
//calculate the number of days that elapse for each animation frame
this.animationTimeMultiplier = 500000 * (this.dayRange / 365);
//calculate how long crimes should be displayed for based on our range
this.visibleLifespan = Math.ceil(this.dayRange / 10);
if(this.visibleLifespan < 10)
this.visibleLifespan = 10;
else if(this.visibleLifespan > 40)
this.visibleLifespan = 40;
this.visibleLifespan = this.visibleLifespan * DAY_IN_MILLI;
this.lowIndex = 0; //holds the data index of the oldest crime we are displaying
this.highIndex = 0; //holds the data index of the newest crime we are displaying
this.filters = [];
this.setupProgressBar();
var self = this;
var $animationControlButton = $('#animation-control-button');
$animationControlButton.click(this.togglePause.bind(this));
//handle the filter click events
$('#options input:not(#options-markers)').on('change', this.changeFilters.bind(this));
$('#options-markers').on('change', this.toggleCrimeMarkers.bind(this));
//hookup spacebar pauser/resume
$(window).keypress(this.togglePause.bind(this));
this.$animationControl = $animationControlButton.children('div');
//if the animation is paused then redraw the current frame on drag end
google.maps.event.addListener(map, 'dragend', function() {
if(self.isPaused)
self.drawFrame(self.currentDate);
});
google.maps.event.addListener(map, 'zoom_changed', function() {
heatmap.heatmap.set('radius', radiusFromZoom(map.getZoom()));
if(self.isPaused)
self.drawFrame(self.currentDate);
});
};
CrimeAnimator.prototype.setupProgressBar = function setupProgressBar() {
//setup progress bar slider events
this.$progressBar = $('#progress-bar-container');
var $progressBarPointer = $('#progress-bar-pointer');
var $document = $(document);
this.progressBarStartPosition = Math.ceil($document.width() * 0.05);
this.progressBarEndPosition = $document.width() - this.progressBarStartPosition;
this.$progressBar.css('width', this.progressBarStartPosition + 'px');
this.totalTimeRange = this.dateRange.end - this.dateRange.start;
this.totalPixelRange = this.progressBarEndPosition - this.progressBarStartPosition;
var self = this;
var stopPointerDrag = function(e) {
self.updateCurrentDateToProgressPosition(e.pageX);
//draw the heatmap frame for our current position
self.lowIndex = 0;
self.highIndex = 0;
self.drawFrame(self.currentDate);
self.removeCrimeMarkers();
if(self.showMarkers)
self.addCrimeMarkers();
$document.off('mousemove ontouchmove');
e.preventDefault();
};
//keep track of the top of the progres bar so that we can stop dragging when the mouse leaves the top
var pointerOffsetTop = $progressBarPointer.offset().top;
$(window).resize(function() {
pointerOffsetTop = $progressBarPointer.offset().top;
});
//setup dragability of progress bar pointer
$progressBarPointer.on('mousedown ontouchstart', function(e) {
self.pause.apply(self);
$document.on('mousemove ontouchmove', function(e) {
if(e.pageY < pointerOffsetTop) {
stopPointerDrag(e);
return;
}
//impose start/end limits on progress bar
var x = e.pageX;
if(x > self.progressBarEndPosition)
x = self.progressBarEndPosition;
else if(x < self.progressBarStartPosition)
x = self.progressBarStartPosition;
self.$progressBar.css('width', x + 'px');
//update progress bar text
self.updateCurrentDateToProgressPosition(x);
self.updateProgressBarText();
self.removeCrimeMarkers();
//in chrome we will animate on drag
if(isBrowserFast)
self.drawFrame(self.currentDate);
e.preventDefault();
});
e.preventDefault();
});
//stop dragging
$progressBarPointer.on('mouseup ontouchend', stopPointerDrag);
this.$progressBarPointer = $progressBarPointer;
};
var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
CrimeAnimator.prototype.updateProgressBar = function updateProgressBar() {
var x = (this.progressBarStartPosition + (((this.currentDate - this.dateRange.start) / this.totalTimeRange) * this.totalPixelRange));
if(x > this.progressBarEndPosition)
x = this.progressBarEndPosition;
this.$progressBar.css('width' , x + 'px');
this.updateProgressBarText();
};
CrimeAnimator.prototype.updateCurrentDateToProgressPosition = function updateCurrentDateToProgressPosition(progressPosition) {
//calc the current position of pointer and translate that into an animation position date
var progressBarPercentComplete = (progressPosition - this.progressBarStartPosition) / this.totalPixelRange;
this.currentDate = this.dateRange.start + ((this.dateRange.end - this.dateRange.start) * progressBarPercentComplete);
};
CrimeAnimator.prototype.updateProgressBarText = function updateProgressBarText() {
var now = new Date(this.currentDate);
this.$progressBarPointer.html(
monthNames[now.getMonth()] + '<br>' + now.getDate() +
'<span class=date-prefix>' + getNumberPostfix(now.getDate()) + '</span><br>' +
'<span class=year>- ' + now.getFullYear() + ' -</span><br>'
);
};
function nFormatter(num, digits) {
var si = [
{ value: 1E18, symbol: "E" },
{ value: 1E15, symbol: "P" },
{ value: 1E12, symbol: "T" },
{ value: 1E9, symbol: "B" },
{ value: 1E6, symbol: "M" },
{ value: 1E3, symbol: "k" }
], i;
for (i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return '$' + (num / si[i].value).toFixed(digits) + si[i].symbol;
}
}
return '$' + num.toString();
}
CrimeAnimator.prototype.updateIncidentBurdenText = function updateIncidentBurdenText() {
var f = this.filters, curDate = this.currentDate;
var filteredData = jQuery.grep(this.data, function( n, i ) {
return f.indexOf(n.code) == -1 && n.epoch < curDate;
});
if (filteredData.length > 0) {
$("span#incident_value")[0].textContent = filteredData.length;
$("span#burden_value")[0].textContent = nFormatter(
filteredData.map(function(crime) {
return parseInt(crime.cost)
}).reduce(function (pv, cv) {
return pv + cv
}), 2);
};
};
var numberEndings = ['', 'st', 'nd', 'rd', 'th'];
function getNumberPostfix(number) {
return numberEndings[number >= numberEndings.length ? numberEndings.length - 1 : number];
};
CrimeAnimator.prototype.applyFilters = function setData(filters) {
this.filters = filters;
};
CrimeAnimator.prototype.updateIndexPositions = function updateIndexPositions(visibleThreshold, nextDate) {
this.lowIndex = this.getNewIndexPosition(this.lowIndex, visibleThreshold, 0);
if(this.highIndex < this.lowIndex)
this.highIndex = this.lowIndex;
this.highIndex = this.getNewIndexPosition(this.highIndex, nextDate, this.lowIndex);
},
/**
adjust index position to match the comparitor date and the current data
*/
CrimeAnimator.prototype.getNewIndexPosition = function getNewIndexPosition(index, comparitorDate, indexMinimum) {
//expand the index till it reaches the compairitor date
while(index < this.dataLength) {
if(this.data[index].epoch >= comparitorDate)
break;
index += 1;
}
//contract the index till it reaches the comparitor date
while(index > indexMinimum) {
if(this.data[index].epoch < comparitorDate)
break;
index -= 1;
}
return index;
};
CrimeAnimator.prototype.drawFrame = function drawFrame(nextDate) {
var visibleThreshold = this.currentDate - this.visibleLifespan;
this.updateIndexPositions(visibleThreshold, nextDate);
//if no removals to make then just add the crime points that are between the currentDate and the next Date and aren't filtered
var currentData = this.getCurrentHeatmapData(this.lowIndex, this.highIndex, visibleThreshold);
this.heatmap.setDataSet(currentData);
},
CrimeAnimator.prototype.animate = function animate() {
var now = new Date().getTime();
if(!this.isPaused) {
var nextDate = this.currentDate + ((now - this.lastDrawTime) * this.animationTimeMultiplier);
this.drawFrame(nextDate);
//increment currentDate to next date
this.currentDate = nextDate;
//update our current progress to match the current date
this.updateProgressBar();
this.updateIncidentBurdenText();
}
this.lastDrawTime = now;
if (this.highIndex < this.dataLength)
window.requestAnimationFrame(this.animate.bind(this));
else {
//we are done
this.isAnimating = false;
this.pause();
}
};
CrimeAnimator.prototype.start = function start() {
//set the current date to the first day if we are at the end of the animation
if (this.highIndex >= this.dataLength || !this.currentDate)
this.currentDate = this.dateRange.start;
//reset our indexes
this.lowIndex = 0;
this.highIndex = 0;
this.lastDrawTime = new Date().getTime();
this.isAnimating = true;
//start the animation
this.animate();
}
CrimeAnimator.prototype.pause = function pause() {
this.$animationControl.removeClass('pause');
this.$animationControl.addClass('play');
this.isPaused = true;
//draw markers
if(this.showMarkers)
this.addCrimeMarkers();
};
CrimeAnimator.prototype.resume = function resume() {
this.removeCrimeMarkers();
this.$animationControl.removeClass('play');
this.$animationControl.addClass('pause');
this.isPaused = false;
//if we are at the end of the animation then restart it
if (!this.isAnimating)
this.start();
};
CrimeAnimator.prototype.togglePause = function togglePause() {
if(this.isPaused)
this.resume();
else
this.pause();
};
CrimeAnimator.prototype.changeFilters = function changeFilters(e) {
var checkbox = e.target;
var filterType = checkbox.name;
if(!checkbox.checked) {
this.filters.push(filterType);
} else {
var index = this.filters.indexOf(filterType);
if (index > -1)
// drop the filter
this.filters.splice(index, 1);
}
if(this.isPaused || !this.isAnimating) {
this.drawFrame(this.currentDate);
this.updateIncidentBurdenText();
this.removeCrimeMarkers();
if(this.showMarkers)
this.addCrimeMarkers();
}
};
CrimeAnimator.prototype.toggleCrimeMarkers = function toggleCrimeMarkers() {
this.showMarkers = !this.showMarkers;
if(!this.showMarkers)
this.removeCrimeMarkers();
else if(this.isPaused || !this.isAnimating)
this.addCrimeMarkers();
};
function buildPin(color) {
return new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + color,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
}
CrimeAnimator.prototype.addCrimeMarkers = function addCrimeMarkers() {
var currentData = this.data.slice(this.lowIndex, this.highIndex + 1);
var self = this;
for(var i=currentData.length-1 ; i >= 0 ; i--) {
var crime = currentData[i];
if(this.filters.indexOf(crime.code) > -1)
continue;
var codeColors = [
'e3b5a4',
'acf39d',
'e85f5c',
'9cfffa',
'f2688a'
]
var marker = new google.maps.Marker({
position: new google.maps.LatLng(crime.lat, crime.long),
map: this.map,
icon: buildPin(codeColors[Object.keys(this.codes).indexOf(crime.code) % 5]),
title: this.codes[crime.code]
});
this.markers.push(marker);
//setup the markers onclick event to display the popup window
/*function setupMarkerInfoWindow(marker, crime) {
google.maps.event.addListener(marker, 'click', function() {
self.markerInfoWindow.content = 'type: ' + crime.description + '<br>date: ' + Date.parse(crime.ts);
self.markerInfoWindow.open(self.map, marker);
});
}(marker, crime);*/
}
};
CrimeAnimator.prototype.removeCrimeMarkers = function removeCrimeMarkers() {
for(var i=this.markers.length-1 ; i >= 0 ; i--) {
this.markers.pop().setMap(null);
}
};
CrimeAnimator.prototype.getCurrentHeatmapData = function getCurrentHeatmapData(lowIndex, highIndex, visibleThreshold) {
var currentData = this.data.slice(this.lowIndex, this.highIndex + 1);
var crime, type, count, timeFromHighIndex, heatmapData = [];
var currentTimeRange = this.currentDate - visibleThreshold;
for(var i = currentData.length-1 ; i >= 0 ; i--) {
crime = currentData[i];
if(this.filters.indexOf(crime.code) >= 0) {
continue;
}
timeFromHighIndex = this.currentDate - crime.epoch;
var x = timeFromHighIndex / currentTimeRange;
count = Math.abs(4 * (x - Math.pow(x, 2))); //exponential curve for fade in/out
heatmapData.push({lat : crime.lat, lng : crime.long, count: count});
}
return {max: 3, data: heatmapData};
};
function getBoundsZoomLevel(bounds, mapDim) {
var WORLD_DIM = { height: 256, width: 256 };
var ZOOM_MAX = 21;
function latRad(lat) {
var sin = Math.sin(lat * Math.PI / 180);
var radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
function zoom(mapPx, worldPx, fraction) {
return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
}
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
var latFraction = (latRad(ne.lat()) - latRad(sw.lat())) / Math.PI;
var lngDiff = ne.lng() - sw.lng();
var lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
var latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
var lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
return Math.min(latZoom, lngZoom, ZOOM_MAX);
}
function radiusFromZoom(zoom) {
return zoom * Math.pow(2, zoom - 11);
}
!function($){
$(function(){
var $mapDiv = $('#heatmapArea');
var mapDim = {
height: $mapDiv.height(),
width: $mapDiv.width()
}
var USABounds = new google.maps.LatLngBounds(
new google.maps.LatLng(25.82, -124.39), // Southwest has to come first
new google.maps.LatLng(49.38, -66.94) // Northeast
);
var myOptions = {
zoom: (USABounds) ? getBoundsZoomLevel(USABounds, mapDim) : 5,
center: (USABounds) ? USABounds.getCenter() : new google.maps.LatLng(0, 0),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: true,
draggable: true,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL,
position: google.maps.ControlPosition.RIGHT_CENTER
},
disableDoubleClickZoom: false,
styles: [{ "stylers": [
{ "saturation": -26 },
{ "lightness": 18 },
{ "visibility": "on" }
]}]
};
var map = new google.maps.Map($mapDiv[0], myOptions);
var heatmap = new HeatmapOverlay(map, {
'radius': 0,
'visible': true,
'opacity': 40
});
// Limit map panning
allowedBounds = USABounds
var lastValidCenter = map.getCenter();
google.maps.event.addListener(map, 'center_changed', function() {
if (allowedBounds.contains(map.getCenter())) {
// still within valid bounds, so save the last valid position
lastValidCenter = map.getCenter();
return;
}
// not valid anymore => return to last valid position
map.panTo(lastValidCenter);
});
// limit zoom levels
google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() < 11) map.setZoom(11);
if (map.getZoom() > 14) map.setZoom(14);
});
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame || window.msRequestAnimationFrame ||
function(fn) {return setTimeout(fn, 1000 / 60);};
//handle the filter area drop down on click
$('#options-button').click(function() {
var $options = $('#options li');
fadeEachOption($options.toArray(), $options.css('margin-right') === '0px');
});
// this is important, because if you set the data set too early, the latlng/pixel projection doesn't work
google.maps.event.addListenerOnce(map, 'idle', function() {
// should be in ascending order by date
// should have headers: lat, long, ts, code, description, cost
// script baltimore_cleanup.py cleans the data from
// https://data.baltimorecity.gov/Public-Safety/BPD-Part-1-Victim-Based-Crime-Data/wsfq-mvij
$.ajaxSetup({ cache: false });
$.get("data/bal_crime_firearm.csv",
function( rawData ) {
var items = $.csv.toObjects(rawData);
var max_lat = min_lat = parseFloat(items[0].lat);
var max_long = min_long = parseFloat(items[0].long);
var codes = {}
for (i=0; i<items.length; i++) {
if (parseFloat(items[i].lat) > max_lat) {max_lat = parseFloat(items[i].lat);}
if (parseFloat(items[i].lat) < min_lat) {min_lat = parseFloat(items[i].lat);}
if (parseFloat(items[i].long) > max_long) {max_long = parseFloat(items[i].long);}
if (parseFloat(items[i].long) < min_long) {min_long = parseFloat(items[i].long);}
items[i].epoch = (new Date(items[i].ts)).getTime()
if (!(items[i].code in codes)) {
codes[items[i].code] = items[i].description
};
};
Object.keys(codes).forEach(function( k, i ) {
$("li#filter").after("<li style={background:#FAE07E;}><label>" + this[k] + "</label><input type='checkbox' name='" + k + "' checked>")
}, codes);
allowedBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(min_lat, min_long), // Southwest first
new google.maps.LatLng(max_lat, max_long) // then Northeast
);
map.setCenter(allowedBounds.getCenter());
map.setZoom(getBoundsZoomLevel(allowedBounds, mapDim));
heatmap.heatmap.set('radius', radiusFromZoom(map.getZoom()));
var crimeAnimator = new CrimeAnimator(items, codes, heatmap, map);
// comment out if you don't want city boundaries
var kml_url = "https://data.baltimorecity.gov/api/geospatial/fy7v-tvcr?method=export&format=KML";
var mapBoundaries = new google.maps.KmlLayer({
url: kml_url,
map: map,
preserveViewport: true,
});
crimeAnimator.start()
},
dataType = 'text'
);
});
});
}(window.jQuery);
function fadeEachOption(options, isFadeIn) {
if(options.length <= 0)
return;
options.shift().style.marginRight = isFadeIn ? '-200px' : '0';
//adjust the wait time depending on if we are animating(which slows everything down)
window.setTimeout(fadeEachOption.bind(this, options, isFadeIn), this.isPaused || !this.isAnimating ? 30 : 0);
};
</script>
</body>
</html>