This repository has been archived by the owner on Apr 28, 2024. It is now read-only.
forked from albertico/crime-spotter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
crime.html
467 lines (424 loc) · 19.4 KB
/
crime.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Crime Spotter (beta) - PR.gov</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/bootstrap-select.js"></script>
<script src="../assets/js/leaflet.js"></script>
<!-- Bootstrap -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/css/crime.css" rel="stylesheet">
<style>
body {
padding-top: 50px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="../assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="../assets/js/html5shiv.js"></script>
<![endif]-->
<!-- Bootstrap-Select -->
<link href="../assets/css/bootstrap-select.css" rel="stylesheet">
<!-- Leaflet -->
<link rel="stylesheet" href="../assets/css/leaflet.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.5/leaflet.ie.css" />
<![endif]-->
<script type="text/javascript">
var map = null;
var crime_layer = null;
var crimes = null; // List of crimes selected in the menu, for filtering
var crimes_total = null; // statistics: { delito_id : [ crimen_desc, total_found ] }
var global_count = 0; // Total crime count - cache
var center = null;
var drawing = false; // Flag that tells us wether we're rendering the map
var asset_path = '../assets/img/icons/'; // Asset path
// initial call for the spotter on onLoad
function setupSpotter() {
// perform any calls that must be done only onLoad
// and call SpotCrime()
spotCrimes();
}
function reloadMap() {
if((center.lng != map.getCenter().lng) && (center.lat != map.getCenter().lat))
{
//console.log("Map moved...")
center = map.getCenter();
clearMap();
spotCrimes();
} else {
//console.log("nothing...")
}
}
function reinitialize() {
clearMap();
crimes = null;
crimes_total = null;
global_count = 0;
center = null;
darwing = false;
//console.log("reinitializing");
}
function spotCrimes() {
// Do not continue if we're currently rendering
if (drawing) {
console.log("cannot redraw, we're currently rendering");
return false;
}
drawing = true;
reinitialize(); // reinitialize all variables
loadFilter(); // Loads list of selected crimes for filtering.
center = map.getCenter();
distance = $("#distance").val();
host = "compass.pr.gov"
//host = "127.0.0.1:9000"
console.log("http://"+host+"/compass/delitos/location?lnglat="+map.getCenter().lng+","+map.getCenter().lat+"&dist="+distance);
compass_request = "http://"+host+"/compass/delitos/location?lnglat="+map.getCenter().lng+","+map.getCenter().lat+"&dist="+distance
if(crime_layer != null) {
map.removeLayer(crime_layer);
}
$.getJSON(compass_request, function(data) {
// Clean up the data by filtering for the selected crime types
data = purgeCrimes(data);
crime_layer = L.geoJson(data, {
pointToLayer: function (feature, latlng) {
drawing = true; // make sure we're not trying to spot crimes while rendering
return L.marker(latlng, {icon: selectMarkerIcon(feature.properties.delito_id)});
},
onEachFeature: function (feature, layer) {
drawing = true; // make sure we're not trying to spot crimes while rendering
var popupContent = "<p><strong>Delito: </strong>"+feature.properties.delito_desc+"<br><strong>Fecha: </strong>"+feature.properties.fecha_delito+"<br><strong>Hora: </strong>"+feature.properties.hora_delito+"</p>";
layer.bindPopup(popupContent);
}
});
map.addLayer(crime_layer);
// Only after we're done, then we allow this method to be called again
drawing = false;
//});
})
.success(function()
{
console.log("connection success");
})
.error(function()
{
console.log("error");
$("#alert").css("display", "inherit");
$("#alert").html("A connection error ocurred.");
})
.complete(function()
{
$("#alert").css("display", "none");
console.log("connection completed");
});
// Set the timer for window refresh
window.setInterval(function() { reloadMap();} , 1000);
}
function generateStatistics() {
html = "";
for(id in crimes_total) {
if( crimes_total[id][1] > 0) {
html += ""+
"<div class='span6'>"+
"<div style='display: block; font-weight: bold;'>"+
" <h3><img class='thumb' src='"+ (asset_path + getIcon(id)) +"'>"+
"<a href='#' class='reglamento' data-toggle='tooltip' title='' data-original-title='"+ getTooltip(id) +"' onclick='updateFilter("+ id +");'>"+ crimes_total[id][0] +"</a>: <span class='crime_total'>"+crimes_total[id][1]+"</span></h3> "+
"</div>"+
"</div>";
}
}
$("#total").html(global_count);
$("#statistics").html(html);
$('.reglamento').tooltip(); // setup tooltips
}
function clearMap() {
for(i in map._layers) {
if(map._layers[i]._path != undefined) {
try {
map.removeLayer(map._layers[i]);
}
catch(e) {
console.log("problem with " + e + map._layers[i]);
}
}
}
}
// This method allows users to click on a type of crime
// from the statistics link and load a list of crimes
// filtered down.
function updateFilter(id) {
$("#crimenes option:selected").each(function()
{
if( id != $(this).val())
{
$(this).removeAttr('selected');
}
});
spotCrimes();
}
// Clean up the server json crime data, by filtering per selected user options
function purgeCrimes(tmp) {
var i = tmp["features"].length;
// we can't use for loop, because as we splice, the length index changes and breaks
// so using while, we can iterate through the original length and splice any
// crimes that do not match our filter
while(i--) {
// if this delito_id isn't in the selected filter list, we splice it off.
if(!filterCrime(tmp["features"][i]["properties"]["delito_id"], tmp["features"][i]["properties"]))
{
tmp["features"].splice(i, 1); // delete this index completely
}
}
generateStatistics(); // generate statistics based on existing data
return tmp;
}
// return true if we should allow this type of crime to be seen
// if it is to be dropped, we return false
function filterCrime(id, prop) {
result = $.inArray(""+id +"", crimes); // check if this crime id is wanted
desc = prop["delito_desc"];
hora = prop["hora_delito"];
if (result == -1) {
//console.log("Crime id "+ id +" is going to get dropped");
return false;
}
else {
//console.log("Crime id "+id+" is allowed ("+ desc+") ("+ hora +")");
// Update the count stats for this type of filtered crime.
crimes_total[""+ id +""][1] += 1;
console.log(id);
global_count += 1;
$("#c"+ id +"").html(crimes_total[id][1]);
$("#total").html(global_count);
return true;
}
}
// load the checked items from the html form that have been selected for filtering
// their numbers correspond to delito_id
function loadFilter() {
crimes = $('#crimenes').val();
crimes_total = {};
$("#crimenes option:selected").each(function()
{
// { delito_id : [ crimen_desc, total_found ] }
crimes_total[$(this).val()] = [$(this).text(), 0]; // initialize total crimes
});
//console.log("Allowing the following crimes to be seen:");
}
// Returns an icon based on an ID
function getIcon(id) {
id = parseInt(id);
markerIcon = 'unknown.png';
switch(id)
{
case 1:
markerIcon = 'asesinato.png';
break;
case 2:
markerIcon = 'violacion.png';
break;
case 3:
markerIcon = 'robo.png';
break;
case 4:
markerIcon = 'agresion.png';
break;
case 5:
markerIcon = 'escalamiento.png';
break;
case 6:
markerIcon = 'apropiacion-ilegal.png';
break;
case 7:
markerIcon = 'vehiculo-hurtado.png';
break;
case 8:
markerIcon = 'incendio.png';
break;
}
return markerIcon;
}
// Returns tooltips data
function getTooltip(id) {
switch(parseInt(id)) {
case 1: // Asesinato
return "Asesinato es dar muerte a un ser humano con intención de causársela.";
case 2: // Violación
return "Ser´ sancionada con pena de reclusión por un término fijo de cincuenta (50) años, toda persona que lleve a cabo, o que provoque que otra persona lleve a cabo, un acto orogenital o una penetración sexual vaginal o anal ya sea ésta genital, digital, o instrumental, en cualquiera de las circunstancias (que se detallan en el articulo 130 del Código Penal 2012).";
case 3: // Robo
return "Toda persona que se apropie ilegalmente de bienes muebles pertenecientes a otra, sustrayéndolos de la persona en su inmediata presencia y contra su voluntad, por medio de violencia o intimidación, o inmediatamente después de cometido el hecho emplee violencia o intimidación sobre una persona para retener la cosa apropiada";
case 4: // Agresión Agravada
return "Toda persona que ilegalmente, por cualquier medio o forma, cause a otra una lesión a su integridad corporal (artículo 108)";
case 5: // Ecalamientos
return "Toda persona que penetre en una casa, edificio u otra construcción o estructura, o sus dependencias o anexos, con el propósito de cometer cualquier delito de apropiación ilegal o cualquier delito grave.";
case 6: // Apropiación Ilegal
return "Toda persona que se apropie sin violencia de bienes muebles pertenecientes a otras personas.";
case 7: // Vehículo Hurtado
return "Hurto de Vehiculo";
case 8: // Incendios
return "Toda persona que maliciosamente pegare fuego a un edificio. Toda persona que incendie montes, sembrados, pastos, bosques o plantaciones ajenos.Toda persona que por negligencia ocasione un incendio de un edificio, montes, sembrados, pastos, bosques o plantaciones, que ponga en peligro la vida, salud o integridad física de las personas.";
}
return "";
}
// Returns a leaflet icon based on an id
function selectMarkerIcon(id) {
markerIcon = getIcon(id);
return L.icon({
iconUrl: (asset_path + markerIcon),
iconSize: [32, 37],
iconAnchor: [16, 37],
popupAnchor: [0, -28]
});
}
$(window).on('load', function () {
$('select').selectpicker('selectAll');
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
osmAttrib = '© <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib});
map = L.map('map').setView([18.428, -66.059], 14).addLayer(osm);
});
// GPS Leaflet method - under review
function locateUser() {
this.map.locate({setView : true});
}
</script>
</head>
<body onload="setupSpotter();">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".navbar-inverse-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#">
<span style="display: inline;"><img id='logo'src='../assets/img/compass.png'></span>
Crime Spotter
<div id="beta">
<span class="label label-info">beta!</span>
</div>
</a>
<div class="nav-collapse collapse navbar-inverse-collapse" style="padding-top: 5px;">
<!--
<ul class="nav">
<li class="active"><a href="#">Mapa</a></li>
<li><a href="#">Tendencias</a></li>
</ul>
-->
<!--
<form class="navbar-search pull-left" action="">
<input type="text" class="search-query span2" placeholder="Calle y pueblo...">
</form>
-->
<ul class="nav pull-right">
<li><button class="btn btn-primary" data-dismiss="modal" onclick="locateUser();">GPS</button></li>
</ul>
</div><!-- /.nav-collapse -->
</div>
</div><!-- /navbar-inner -->
</div><!-- /navbar -->
<div class="container">
<!--
<a href="#myModal" role="button" class="btn btn-danger" data-toggle="modal">Opciones Avanzadas</a>
-->
<div class="span12">
<div id="alert" style="display: none;" class="alert alert-error">hi</div>
</div>
</div>
<div id="map" class="map" style="height: 350px"></div>
<div class="container">
<div class="row">
<form class="form-inline">
<span class="span4">
<label><b>Tipo de Crimen</b> </label>
<select id="crimenes" class="selectpicker span4" multiple data-selected-text-format="count > 4">
<!-- Apropiación ilegal es -->
<!-- Ver código Penal del 2012 para más información -->
<!-- http://www.ramajudicial.pr/leyes/codpenal2012.html -->
<!-- PDF: http://www.ramajudicial.pr/leyes/CODIGO-PENAL-2012-CLASIFICACION-DELITOS-PENAS-APLICABLES.pdf -->
<!-- Ver articulos del código penal -->
<option value=1>Asesinatos</option>
<option value=2>Violación</option>
<!-- Articulo 189 -->
<!-- Robo es donde el sujeto arrebata la propiedad a la victima sin mayor fuerza -->
<option value=3>Robos</option>
<option value=4>Agresión Agravada</option>
<option value=5>Escalamientos</option>
<!-- Articulo 181 -->
<!-- toda persona que se apropie sin violencia de bienes muebes pertenecientes a otras personas -->
<option value=6>Apropiación Ilegal</option>
<option value=7>Vehiculos Hurtados</option>
<option value=8>Incendios</option>
</select>
</span>
<span class="span4">
<label><b>Distancia en Millas</b> </label>
<br/>
<select id="distance">
<option selected="selected">1</option>
<option>3</option>
<option>5</option>
</select>
</span>
<span class="span4">
<br/>
</span>
</form>
<button class="btn" data-dismiss="modal" onclick="spotCrimes(); return false;">Recargar</button>
</div>
<div class="span12">
<hr>
<div style="display: inline; font-weight: bold; font-size: xx-large;">
<span id='loading'></span>
<span>Crimenes</span>
<div style="display: inline;">
<span id="total" class="badge badge-warning" style="font-size: large; padding: 10px; margin-bottom: 10px;">0</span>
</div>
</div>
</div>
<div class="row">
<div id="statistics">
<!-- Aqui se populan las estadisticas mediante JS -->
</div>
</div>
<div class="row" style="padding-top: 20px; padding-bottom: 20px;">
<div class="span12">
<ul class="breadcrumb">
<li><a href="#">API.PR.GOV</a> <span class="divider">/</span></li>
<li><a href="#">Apps</a> <span class="divider">/</span></li>
<li><a href="#">Ley y Orden</a> <span class="divider">/</span></li>
<li><a href="#">Policia</a> <span class="divider">/</span></li>
<li><a href="#">Crimen</a> <span class="divider">/</span></li>
<li><a href="#">Compass</a> <span class="divider">/</span></li>
<li class="active">Crime Spotter</li>
</ul>
</div>
<!-- nota aclaratoria - disclaimer -->
<div class="span12">
<div class="alert alert-info">
Esta aplicación se alimenta de datos provistos a la Oficina de Tecnología de Información Gubernamental (TIG) del <a href="http://cio.pr.gov">Principal Ejecutivo de Informática</a> (CIO) de Puerto Rico. Para uso oficial, toda información debe ser corroborada con la <a href="http://www.policia.pr.gov/">Policia de Puerto Rico</a>.
</div>
</div>
<div class="span4">
Datos en <a href="http://api.pr.gov">api.pr.gov</a>
</div>
<div class="span4">
<a href="https://github.com/albertico/compass-api-crime-spotter">Código en Github</a>
</div>
<div class="span4">
Powered by <a href="https://github.com/albertico/compass-api">Compass</a>
</div>
</div>
</div>
</div>
<!-- Developed by: Alberto Colón - (https://github.com/albertico/) CIO DRNA.pr.gov -->
<!-- Contributor: Andrés Colón Pérez (http://github.com/mindware/) CIO OGP.pr.gov -->
</body>
</html>