blob: defc80758ebbc1279141f4db8c177be2c6ea27a8 [file] [log] [blame]
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -07001$(function() {
2
3 APIqueryTracker = {};
4 drilldown_data_map = {};
5 drilldown_data_map_vals = {};
6 asyncQueryManager = {};
7
8 // Review Mode
9 review_mode_tweetbooks = [];
10 review_mode_handles = [];
11
12 $('#drilldown_modal').modal({ show: false});
13 $('#explore-mode').click( onLaunchExploreMode );
14 $('#review-mode').click( onLaunchReviewMode );
15
16 /** UI **/
17 map_cells = [];
18 map_tweet_markers = [];
19 param_placeholder = {};
20
21 $("#clear-button").button().click(function () {
22 mapWidgetClearMap();
23 param_placeholder = {};
24
25 map.setZoom(4);
26 map.setCenter(new google.maps.LatLng(38.89, -77.03));
27
28 $('#query-preview-window').html('');
29 $("#metatweetzone").html('');
30 });
31
32 $("#selection-button").button('toggle');
33
34 var dialog = $("#dialog").dialog({
35 width: "auto",
36 title: "AQL Query"
37 }).dialog("close");
38 $("#show-query-button")
39 .button()
40 .attr("disabled", true)
41 .click(function (event) {
42 $("#dialog").dialog("open");
43 });
44
45 // setup grid sliders
46 var updateSliderDisplay = function(event, ui) {
47 if (event.target.id == "grid-lat-slider") {
48 $("#gridlat").text(""+ui.value);
49 } else {
50 $("#gridlng").text(""+ui.value);
51 }
52 };
53
54 sliderOptions = {
55 max: 20,
56 min: .1,
57 step: .1,
58 value: 2.0,
59 slidechange: updateSliderDisplay,
60 slide: updateSliderDisplay,
61 start: updateSliderDisplay,
62 stop: updateSliderDisplay
63 };
64
65 $("#gridlat").text(""+sliderOptions.value);
66 $("#gridlng").text(""+sliderOptions.value);
67 $(".grid-slider").slider(sliderOptions);
68
69 // setup datepickers
70 var dateOptions = {
71 dateFormat: "yy-mm-dd",
72 defaultDate: "2012-01-02",
73 navigationAsDateFormat: true,
74 constrainInput: true
75 };
76 var start_dp = $("#start-date").datepicker(dateOptions);
77 start_dp.val(dateOptions.defaultDate);
78 dateOptions['defaultDate'] = "2012-12-31";
79 var end_dp= $("#end-date").datepicker(dateOptions);
80 end_dp.val(dateOptions.defaultDate);
81
82 // This little bit of code manages period checks of the asynchronous query manager,
83 // which holds onto handles asynchornously received. We can set the handle update
84 // frequency using seconds, and it will let us know when it is ready.
85 var intervalID = setInterval(
86 function() {
87 asynchronousQueryIntervalUpdate();
88 },
89 asynchronousQueryGetInterval()
90 );
91
92 // setup map
93 onOpenExploreMap();
94 var mapOptions = {
95 center: new google.maps.LatLng(38.89, -77.03),
96 zoom: 4,
97 mapTypeId: google.maps.MapTypeId.ROADMAP,
98 streetViewControl: false,
99 draggable : false
100 };
101 map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
102
103 // setup location autocomplete
104 var input = document.getElementById('location-text-box');
105 var autocomplete = new google.maps.places.Autocomplete(input);
106 autocomplete.bindTo('bounds', map);
107
108 google.maps.event.addListener(autocomplete, 'place_changed', function() {
109 var place = autocomplete.getPlace();
110 if (place.geometry.viewport) {
111 map.fitBounds(place.geometry.viewport);
112 } else {
113 map.setCenter(place.geometry.location);
114 map.setZoom(17); // Why 17? Because it looks good.
115 }
116 var address = '';
117 if (place.address_components) {
118 address = [(place.address_components[0] && place.address_components[0].short_name || ''),
119 (place.address_components[1] && place.address_components[1].short_name || ''),
120 (place.address_components[2] && place.address_components[2].short_name || '') ].join(' ');
121 }
122 });
123
124 // handle selection rectangle drawing
125 shouldDraw = false;
126 var startLatLng;
127 selectionRect = null;
128 var selectionRadio = $("#selection-button");
129 var firstClick = true;
130
131 google.maps.event.addListener(map, 'mousedown', function (event) {
132 // only allow drawing if selection is selected
133 if (selectionRadio.hasClass("active")) {
134 startLatLng = event.latLng;
135 shouldDraw = true;
136 }
137 });
138
139 triggerUIUpdateOnNewTweetBook({"title" : "Party"});
140
141 google.maps.event.addListener(map, 'mousemove', drawRect);
142 function drawRect (event) {
143 if (shouldDraw) {
144 if (!selectionRect) {
145 var selectionRectOpts = {
146 bounds: new google.maps.LatLngBounds(startLatLng, event.latLng),
147 map: map,
148 strokeWeight: 1,
149 strokeColor: "2b3f8c",
150 fillColor: "2b3f8c"
151 };
152 selectionRect = new google.maps.Rectangle(selectionRectOpts);
153 google.maps.event.addListener(selectionRect, 'mouseup', function () {
154 shouldDraw = false;
155 //submitQuery();
156 });
157 } else {
158 if (startLatLng.lng() < event.latLng.lng()) {
159 selectionRect.setBounds(new google.maps.LatLngBounds(startLatLng, event.latLng));
160 } else {
161 selectionRect.setBounds(new google.maps.LatLngBounds(event.latLng, startLatLng));
162 }
163 }
164 }
165 };
166
167 // toggle location search style: by location or by map selection
168 $('#selection-button').on('click', function (e) {
169 $("#location-text-box").attr("disabled", "disabled");
170 if (selectionRect) {
171 selectionRect.setMap(map);
172 }
173 });
174 $('#location-button').on('click', function (e) {
175 $("#location-text-box").removeAttr("disabled");
176 if (selectionRect) {
177 selectionRect.setMap(null);
178 }
179 });
180
181 $('.dropdown-menu a.holdmenu').click(function(e) {
182 e.stopPropagation();
183 });
184
185 $('#new-tweetbook-button').on('click', function (e) {
186 onCreateNewTweetBook($('#new-tweetbook-entry').val());
187
188 $('#new-tweetbook-entry').val($('#new-tweetbook-entry').attr('placeholder'));
189 });
190
191 // handle ajax calls
192 $("#submit-button").button().click(function () {
193 // Clear current map on trigger
194 mapWidgetClearMap();
195
196 // gather all of the data from the inputs
197 var kwterm = $("#keyword-textbox").val();
198 var startdp = $("#start-date").datepicker("getDate");
199 var enddp = $("#end-date").datepicker("getDate");
200 var startdt = $.datepicker.formatDate("yy-mm-dd", startdp)+"T00:00:00Z";
201 var enddt = $.datepicker.formatDate("yy-mm-dd", enddp)+"T23:59:59Z";
202
203 var formData = {
204 "keyword": kwterm,
205 "startdt": startdt,
206 "enddt": enddt,
207 "gridlat": $("#grid-lat-slider").slider("value"),
208 "gridlng": $("#grid-lng-slider").slider("value")
209 };
210
211 // Get Map Bounds
212 var bounds;
213 if ($('#selection-button').hasClass("active") && selectionRect) {
214 bounds = selectionRect.getBounds();
215 } else {
216 bounds = map.getBounds();
217 }
218
219 formData["swLat"] = Math.abs(bounds.getSouthWest().lat());
220 formData["swLng"] = Math.abs(bounds.getSouthWest().lng());
221 formData["neLat"] = Math.abs(bounds.getNorthEast().lat());
222 formData["neLng"] = Math.abs(bounds.getNorthEast().lng());
223
224 var build_cherry_mode = "synchronous";
225 if ($('#asbox').is(":checked")) {
226 build_cherry_mode = "asynchronous";
227 }
228
229 // You don't need to run a query to use the API!
230 // It can also be used to generate queries, which can
231 // then be passed into another API call or stored
232 // for a different application purpose.
233 var buildCherryQuery = new AsterixCoreAPI()
234 .aql_for({ "t" : "TwitterData"})
235 .aql_let({
236 "keyword" : '"' + formData["keyword"] + '"',
237 "region" : new AsterixCoreAPI()
238 .api_helper_polygon_to_statement({
239 "ne" : { "lat" : formData["neLat"], "lng" : formData["neLng"]},
240 "sw" : { "lat" : formData["swLat"], "lng" : formData["swLng"]} })
241 })
242 .aql_where([
243 'spatial-intersect($t.loc, $region)',
244 '$t.time > datetime("' + formData["startdt"] + '")',
245 '$t.time < datetime("' + formData["enddt"] + '")',
246 'contains($t.text, $keyword)'
247 ])
248 .aql_groupby({
249 "groupby" : "$c := spatial-cell($t.loc, create-point(24.5,-125.5), " + formData["gridlat"].toFixed(1) + ", " + formData["gridlng"].toFixed(1) + ")",
250 "with" : "$t"
251 })
252 .aql_return({ "cell" : "$c", "count" : "count($t)" });
253
254 // Here is an actual API call.
255 var asterixAPICall = new AsterixCoreAPI()
256 .dataverse("twitter")
257 .statements(buildCherryQuery.parameters["statements"])
258 .mode(build_cherry_mode)
259 .success(cherryQuerySyncCallback, true)
260 .success(cherryQueryAsyncCallback, false)
261 .add_extra("payload", formData) // Legacy
262 .add_extra("query_string", buildCherryQuery.parameters["statements"].join(" ")) // Legacy
263 .api_core_query();
264
265 APIqueryTracker = {
266 "query" : buildCherryQuery.parameters["statements"].join("\n"),
267 "data" : formData
268 };
269
270 $('#dialog').html(APIqueryTracker["query"]);//.replace("\n", '<br />'));
271
272 if (!$('#asbox').is(":checked")) {
273 $('#show-query-button').attr("disabled", false);
274 } else {
275 $('#show-query-button').attr("disabled", true);
276 }
277 });
278
279});
280
281/** Asynchronous Query Management - Handles & Such **/
282
283/**
284* Checks through each asynchronous query to see if they are ready yet
285*/
286function asynchronousQueryIntervalUpdate() {
287 for (var handle_key in asyncQueryManager) {
288 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
289 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
290 }
291 }
292}
293
294/**
295* Returns current time interval to check for asynchronous query readiness
296* @returns {number} milliseconds between asychronous query checks
297*/
298function asynchronousQueryGetInterval() {
299 var seconds = 10;
300 return seconds * 1000;
301}
302
303/**
304* Updates UI when an API Query's status is marked ready
305* @param {Object} res, a result object from the Asterix API
306* @param {object} extra_info, containing the asynchronous handle's id
307*/
308function asynchronousQueryAPIStatusReceived (res, extra_info) {
309 var handle_outcome = $.parseJSON(res[0]);
310 var handle_id = extra_info["handle_id"];
311 if (handle_outcome["status"] == "SUCCESS") {
312
313 // We don't need to check if this one is ready again, it's not going anywhere...
314 // Unless the life cycle of handles has changed drastically
315 asyncQueryManager[handle_id]["ready"] = true;
316
317 // Make this handle's result look retrievable
318 $('#handle_' + handle_id).addClass("label-success");
319 }
320}
321
322/**
323* Retrieves status of an asynchronous query, using an opaque result handle from API
324* @param {Object} handle, an object previously returned from an async call
325* @param {number} handle_id, the integer ID parsed from the handle object
326*/
327function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
328 var apiQueryStatus = new AsterixCoreAPI()
329 .dataverse("twitter")
330 .handle(handle)
331 .success(asynchronousQueryAPIStatusReceived, true)
332 .add_extra("handle_id", handle_id)
333 .api_core_query_status();
334}
335
336/**
337* On-success callback after async API query
338* @param {object} res, a result object containing an opaque result handle to Asterix
339* @param {object} extra, a result object containing a query string and query parameters
340*/
341function cherryQueryAsyncCallback(res, extra) {
342
343 // Parse handle, handle id and query from async call result
344 var handle = res[0];
345 var handle_query = extra["query_string"];
346 var handle_id = $.parseJSON(handle)["handle"].toString().split(',')[0];
347
348 // Add to stored map of existing handles
349 asyncQueryManager[handle_id] = {
350 "handle" : handle,
351 "query" : handle_query,
352 "data" : extra["payload"]
353 };
354
355 $('#review-handles-dropdown').append('<a href="#" class="holdmenu"><span class="label" id="handle_' + handle_id + '">Handle ' + handle_id + '</span></a>');
356
357 $('#handle_' + handle_id).hover(
358 function(){
359 $('#query-preview-window').html('');
360 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
361 },
362 function() {
363 $('#query-preview-window').html('');
364 }
365 );
366
367 $('#handle_' + handle_id).on('click', function (e) {
368
369 // make sure query is ready to be run
370 if (asyncQueryManager[handle_id]["ready"]) {
371
372 // Update API Query Tracker and view to reflect this query
373 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
374 APIqueryTracker = {
375 "query" : asyncQueryManager[handle_id]["query"],
376 "data" : asyncQueryManager[handle_id]["data"]
377 };
378 $('#dialog').html(APIqueryTracker["query"]);
379
380 // Generate new Asterix Core API Query
381 var asyncResultQuery = new AsterixCoreAPI()
382 .dataverse("twitter")
383 .handle(asyncQueryManager[handle_id]["handle"])
384 .success(cherryQuerySyncCallback, true)
385 .add_extra("payload", asyncQueryManager[handle_id]["data"]) // Legacy
386 .add_extra("query_string", asyncQueryManager[handle_id]["query"]) // Legacy
387 .api_core_query_result();
388 }
389 });
390}
391
392
393/** Core Query Management and Drilldown
394
395/**
396* A spatial data cleaning and mapping call
397* @param {Object} res, a result object from a cherry geospatial query
398* @param {Object} extra, extra data passed from the API call - legacy stuff
399*/
400function cherryQuerySyncCallback(res, extra) {
401
402 var response = $.parseJSON(res[0])
403 records = response["results"];
404
405 var coordinates = [];
406 var coordinate = [];
407 var weights = [];
408
409 for (var subr = 0; subr < records.length; subr++) {
410 for (var record in records[subr]) {
411
412 var cell = records[subr][record].split(")")[0].split("(")[1];
413 var count = records[subr][record].split("count")[1].split(":")[1].split(' ')[1];
414 coordinate = {
415 "weight" : parseInt(count),
416
417 // x is actually up-down, y is left-right
418 "latSW" : parseFloat(cell.split("|")[0].split(",")[0].split('"')[1]),
419 "lngSW" : -1*parseFloat(cell.split("|")[0].split(",")[1]),
420 "latNE" : parseFloat(cell.split("|")[1].split(",")[0]),
421 "lngNE" : -1*parseFloat(cell.split("|")[1].split(",")[1].split('"')[0]),
422 };
423 weights.push(parseInt(count));
424 coordinates.push(coordinate);
425 }
426 }
427
428 triggerUIUpdate(coordinates, extra["payload"], weights);
429}
430
431/**
432* Triggers a map update based on a set of spatial query result cells
433* @param [Array] mapPlotData, an array of coordinate and weight objects
434* @param [Array] params, an object containing original query parameters [LEGACY]
435* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
436*/
437function triggerUIUpdate(mapPlotData, params, plotWeights) {
438 /** Clear anything currently on the map **/
439 mapWidgetClearMap();
440 param_placeholder = params;
441
442 // Compute data point spread
443 var dataBreakpoints = mapWidgetLegendComputeNaturalBreaks(plotWeights);
444
445 $.each(mapPlotData, function (m, val) {
446
447 // Only map points in data range of top 4 natural breaks
448 if (mapPlotData[m].weight > dataBreakpoints[0]) {
449
450 // Get color value of legend
451 var mapColor = mapWidgetLegendGetHeatValue(mapPlotData[m].weight, dataBreakpoints);
452 var markerRadius = mapWidgetComputeCircleRadius(mapPlotData[m], dataBreakpoints);
453 var point_opacity = 1.0; // TODO
454
455 var point_center = new google.maps.LatLng(
456 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
457 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
458
459 // Create and plot marker
460 var map_circle_options = {
461 center: point_center,
462 radius: markerRadius,
463 map: map,
464 fillOpacity: point_opacity,
465 fillColor: mapColor,
466 clickable: true
467 };
468 var map_circle = new google.maps.Circle(map_circle_options);
469 map_circle.val = mapPlotData[m];
470
471 // Clicking on a circle drills down map to that value
472 google.maps.event.addListener(map_circle, 'click', function (event) {
473 onMapPointDrillDown(map_circle.val);
474 });
475
476 // Add this marker to global marker cells
477 map_cells.push(map_circle);
478 }
479 });
480
481 // Add a legend to the map
482 mapControlWidgetAddLegend(dataBreakpoints);
483}
484
485/**
486* prepares an Asterix API query to drill down in a rectangular spatial zone
487*
488* @params {object} marker_borders [LEGACY] a set of bounds for a region from a previous api result
489*/
490function onMapPointDrillDown(marker_borders) {
491 var zoneData = APIqueryTracker["data"]; // TODO: Change how this is managed
492
493 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngNE);
494 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngSW);
495
496 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
497 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
498 zoneData["swLng"] = -1*zoneBounds.getSouthWest().lng();
499 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
500 zoneData["neLng"] = -1*zoneBounds.getNorthEast().lng();
501
502 mapWidgetClearMap();
503
504 var customBounds = new google.maps.LatLngBounds();
505 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], -1*zoneData["swLng"]);
506 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], -1*zoneData["neLng"]);
507 customBounds.extend(zoomSWBounds);
508 customBounds.extend(zoomNEBounds);
509 map.fitBounds(customBounds);
510
511 var drilldown_string = ["use dataverse " + "twitter" + ";",
512 "for $t in dataset('" + "TwitterData" + "')",
513 "let $keyword := \"" +zoneData["keyword"] + "\"",
514 "let $region := polygon(\"",
515 zoneData["neLat"] + "," + zoneData["swLng"] + " ",
516 zoneData["swLat"] + "," + zoneData["swLng"] + " ",
517 zoneData["swLat"] + "," + zoneData["neLng"] + " ",
518 zoneData["neLat"] + "," + zoneData["neLng"] + "\")",
519 "where spatial-intersect($t.loc, $region) and",
520 "$t.time > datetime(\"" + zoneData["startdt"] + "\") and $t.time < datetime(\"" + zoneData["enddt"] + "\") and",
521 "contains($t.text, $keyword)",
522 "return { \"tweetId\": $t.tweetid, \"tweetText\": $t.text, \"tweetLoc\": $t.loc}"];
523
524 var zQ = new AsterixCoreAPI()
525 .dataverse("twitter")
526 .statements(drilldown_string)
527 .add_extra("payload", zoneData) // Legacy
528 .mode("synchronous")
529 .success(onTweetbookQuerySuccessPlot, true)
530 .add_extra("query_string", drilldown_string.join(" "))
531 .add_extra("marker_path", "../img/mobile2.png")
532 .add_extra("on_click_marker", onClickTweetbookMapMarker)
533 .add_extra("on_clean_result", onCleanTweetbookDrilldown)
534 .api_core_query();
535}
536
537function triggerUIUpdateOnDropTweetBook(extra_info) {
538 // TODO Remove menu entry
539 // review-tweetbook-titles.html('')
540 // Append each in review_mode_tweetbooks if not same as extra_info["title"]
541 // $('#review-tweetbook-titles').append('<li><a href="#">' + extra_info["title"] + '</a></li>');
542}
543
544function onDrillDownAtLocation(tO) {
545
546 $('#drilldown_modal_body').append('<div id="drilltweetobj' + tO["tweetEntryId"] + '"></div>');
547
548 $('#drilltweetobj' + tO["tweetEntryId"]).append('<p>' + tO["tweetText"] + '</p>');
549
550 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="metacomment' + tO["tweetEntryId"] + '">');
551
552 if (tO.hasOwnProperty("tweetbookComment")) {
553 $('#metacomment' + tO["tweetEntryId"]).val(tO["tweetbookComment"]);
554 }
555
556 $('#drilltweetobj' + tO["tweetEntryId"]).append('<button title="' + tO["tweetEntryId"] + '" id="meta' + tO["tweetEntryId"] + '">Add Comment to...</button>');
557
558 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="tweetbooktarget' + tO["tweetEntryId"] + '">');
559
560 $('#meta' + tO["tweetEntryId"])
561 .button()
562 .click( function () {
563
564 var valid = $('#meta' + tO["tweetEntryId"]).attr('title');
565 var valcomment = $("#metacomment" + valid).val();
566 var valtext = drilldown_data_map_vals[valid.toString()]["tweetText"];
567 var tweetbookname = $("#tweetbooktarget" + valid).val();
568
569 //Try to add the tweetbook, if it does not already exist
570 onCreateNewTweetBook(tweetbookname);
571
572 var apiCall = new AsterixCoreAPI()
573 .dataverse("twitter")
574 .statements([
575 'delete $l from dataset ' + tweetbookname + ' where $l.id = "' + valid + '";',
576 'insert into dataset ' + tweetbookname + '({ "id" : "' + valid + '", "metacomment" : "' + valcomment + '"});'
577 ])
578 .api_core_update();
579 });
580
581}
582
583function onCreateNewTweetBook(tweetbook_title) {
584
585 var newTweetbookAPICall = new AsterixCoreAPI()
586 .dataverse("twitter")
587 .create_dataset({
588 "dataset" : tweetbook_title,
589 "type" : "MetaTweet",
590 "primary_key" : "id"
591 })
592 .add_extra("title", tweetbook_title)
593 .success(triggerUIUpdateOnNewTweetBook, true)
594 .api_core_update();
595 // Possible bug...ERROR 1: Invalid statement: Non-DDL statement DATASET_DECL to the DDL API.
596
597 /*var removeTest = new AsterixCoreAPI()
598 .dataverse("twitter")
599 .drop_dataset("blah")
600 .api_core_update(); */
601}
602
603function onDropTweetBook(tweetbook_title) {
604 var removeTest = new AsterixCoreAPI()
605 .dataverse("twitter")
606 .drop_dataset(tweetbook_title)
607 .success(triggerUIUpdateOnDropTweetBook, true)
608 .api_core_update();
609}
610
611function onTweetbookQuerySuccessPlot (res, extra) {
612 var response = $.parseJSON(res[0]);
613 var records = response["results"];
614 var coordinates = [];
615 map_tweet_markers = [];
616 map_tweet_overlays = [];
617 drilldown_data_map = {};
618 drilldown_data_map_vals = {};
619
620 var micon = extra["marker_path"];
621 var marker_click_function = extra["on_click_marker"];
622 var clean_result_function = extra["on_clean_result"];
623
624 coordinates = clean_result_function(records);
625
626 for (var dm in coordinates) {
627 var keyLat = coordinates[dm].tweetLat.toString();
628 var keyLng = coordinates[dm].tweetLng.toString();
629 if (!drilldown_data_map.hasOwnProperty(keyLat)) {
630 drilldown_data_map[keyLat] = {};
631 }
632 if (!drilldown_data_map[keyLat].hasOwnProperty(keyLng)) {
633 drilldown_data_map[keyLat][keyLng] = [];
634 }
635 drilldown_data_map[keyLat][keyLng].push(coordinates[dm]);
636 drilldown_data_map_vals[coordinates[dm].tweetEntryId.toString()] = coordinates[dm];
637 }
638
639 $.each(drilldown_data_map, function(drillKeyLat, valuesAtLat) {
640 $.each(drilldown_data_map[drillKeyLat], function (drillKeyLng, valueAtLng) {
641
642 // Get subset of drilldown position on map
643 var cposition = new google.maps.LatLng(parseFloat(drillKeyLat), parseFloat(drillKeyLng));
644
645 // Create a marker using the snazzy phone icon
646 var map_tweet_m = new google.maps.Marker({
647 position: cposition,
648 map: map,
649 icon: micon,
650 clickable: true,
651 });
652
653 // Open Tweet exploration window on click
654 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
655 marker_click_function(drilldown_data_map[drillKeyLat][drillKeyLng]);
656 });
657
658 // Add marker to index of tweets
659 map_tweet_markers.push(map_tweet_m);
660
661 });
662 });
663}
664
665function triggerUIUpdateOnNewTweetBook(extra_info) {
666 // Add tweetbook to log
667 if (parseInt($.inArray(extra_info["title"], review_mode_tweetbooks)) == -1) {
668 review_mode_tweetbooks.push(extra_info["title"]);
669
670 // Add menu entry
671 $('#review-tweetbook-titles').append('<li><a href="#"><span id="tbook_' + extra_info["title"] + '">' + extra_info["title"] + '</span></a></li>');
672
673 // Add on-click behavior
674 $("#tbook_" + extra_info["title"]).on('click', function(e) {
675 var plotTweetbookQuery = new AsterixCoreAPI()
676 .dataverse("twitter")
677 .success(onTweetbookQuerySuccessPlot, true)
678 .aql_for({"mt": extra_info["title"]})
679 .aql_where(["int64($mt.id)%1500 = 0"])
680 .aql_return({ "id" : "$mt.id", "location" : "$mt.loc", "comment" : "$mt.metacomment", "tweet" : "$mt.tweet" })
681 .add_extra("tweetbook_title", extra_info["title"])
682 .add_extra("marker_path", "../img/mobile_green2.png")
683 .add_extra("on_click_marker", onClickTweetbookMapMarker)
684 .add_extra("on_clean_result", onCleanPlotTweetbook)
685 .api_core_query();
686
687 });
688 }
689}
690
691function onCleanPlotTweetbook(records) {
692 var toPlot = [];
693 for (var subrecords = 0; subrecords < records.length; subrecords++) {
694 for (var record in records[subrecords]) {
695 var tweetbook_element = {
696 "tweetEntryId" : parseInt(records[subrecords][record].split(",")[0].split(":")[1].split('"')[1]),
697 "tweetLat" : parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[0]),
698 "tweetLng" : -1*parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[1].split("\"")[0]),
699 "tweetText" : records[subrecords][record].split("tweet\": \"")[1].split("\"")[0],
700 "tweetbookComment" : records[subrecords][record].split("comment\": \"")[1].split("\", \"tweet\":")[0]
701 };
702 toPlot.push(tweetbook_element);
703 }
704 }
705 return toPlot;
706}
707
708function onCleanTweetbookDrilldown (rec) {
709 var drilldown_cleaned = [];
710 for (var subresult = 0; subresult < rec.length; subresult++) {
711 for (var entry in rec[subresult]) {
712
713 var drill_element = {
714 "tweetEntryId" : parseInt(rec[subresult][entry].split(",")[0].split(":")[1].split('"')[1]),
715 "tweetText" : rec[subresult][entry].split("tweetText\": \"")[1].split("\", \"tweetLoc\":")[0],
716 "tweetLat" : parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[0]),
717 "tweetLng" : -1*parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[1].split("\"")[0])
718 };
719 drilldown_cleaned.push(drill_element);
720
721 }
722 }
723 return drilldown_cleaned;
724}
725
726function onClickTweetbookMapMarker(tweet_arr) {
727 $('#drilldown_modal_body').html('');
728
729 // Clear existing display
730 $.each(tweet_arr, function (t, valueT) {
731 var tweet_obj = tweet_arr[t];
732 onDrillDownAtLocation(tweet_obj);
733 });
734
735 $('#drilldown_modal').modal('show');
736}
737
738/** Toggling Review and Explore Modes **/
739
740/**
741* Explore mode: Initial map creation and screen alignment
742*/
743function onOpenExploreMap () {
744 var explore_column_height = $('#explore-well').height();
745 $('#map_canvas').height(explore_column_height + "px");
746 $('#review-well').height(explore_column_height + "px");
747 $('#review-well').css('max-height', explore_column_height + "px");
748 var pad = $('#review-well').innerHeight() - $('#review-well').height();
749 var prev_window_target = $('#review-well').height() - 20 - $('#group-tweetbooks').innerHeight() - $('#group-background-query').innerHeight() - 2*pad;
750 $('#query-preview-window').height(prev_window_target +'px');
751}
752
753/**
754* Launching explore mode: clear windows/variables, show correct sidebar
755*/
756function onLaunchExploreMode() {
757 $('#review-active').removeClass('active');
758 $('#review-well').hide();
759
760 $('#explore-active').addClass('active');
761 $('#explore-well').show();
762
763 $("#clear-button").trigger("click");
764}
765
766/**
767* Launching review mode: clear windows/variables, show correct sidebar
768*/
769function onLaunchReviewMode() {
770 $('#explore-active').removeClass('active');
771 $('#explore-well').hide();
772 $('#review-active').addClass('active');
773 $('#review-well').show();
774
775 $("#clear-button").trigger("click");
776}
777
778/** Map Widget Utility Methods **/
779
780/**
781* Plots a legend onto the map, with values in progress bars
782* @param {number Array} breakpoints, an array of numbers representing natural breakpoints
783*/
784function mapControlWidgetAddLegend(breakpoints) {
785
786 // Retriever colors, lightest to darkest
787 var colors = mapWidgetGetColorPalette();
788
789 // Initial div structure
790 $("#map_canvas_legend").html('<div id="legend-holder"><div id="legend-progress-bar" class="progress"></div><span id="legend-label"></span></div>');
791
792 // Add color scale to legend
793 $('#legend-progress-bar').css("width", "200px").html('');
794
795 // Add a progress bar for each color
796 for (var color in colors) {
797
798 // Bar values
799 var upperBound = breakpoints[parseInt(color) + 1];
800
801 // Create Progress Bar
802 $('<div/>')
803 .attr("class", "bar")
804 .attr("id", "pbar" + color)
805 .css("width" , '25.0%')
806 .html("< " + upperBound)
807 .appendTo('#legend-progress-bar');
808
809 $('#pbar' + color).css({
810 "background-image" : 'none',
811 "background-color" : colors[parseInt(color)]
812 });
813
814 // Attach a message showing minimum bounds
815 $('#legend-label').html('Regions with at least ' + breakpoints[0] + ' tweets');
816 $('#legend-label').css({
817 "color" : "black"
818 });
819 }
820
821 // Add legend to map
822 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legend-holder'));
823 $('#map_canvas_legend').show();
824}
825
826/**
827* Clears map elements - legend, plotted items, overlays
828*/
829function mapWidgetClearMap() {
830
831 if (selectionRect) {
832 selectionRect.setMap(null);
833 selectionRect = null;
834 }
835 for (c in map_cells) {
836 map_cells[c].setMap(null);
837 }
838 map_cells = [];
839 for (m in map_tweet_markers) {
840 map_tweet_markers[m].setMap(null);
841 }
842 map_tweet_markers = [];
843
844 // Remove legend from map
845 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].clear();
846}
847
848/**
849* Uses jenks algorithm in geostats library to find natural breaks in numeric data
850* @param {number Array} weights of points to plot
851* @returns {number Array} array of natural breakpoints, of which the top 4 subsets will be plotted
852*/
853function mapWidgetLegendComputeNaturalBreaks(weights) {
854 var plotDataWeights = new geostats(weights.sort());
855 return plotDataWeights.getJenks(6).slice(2, 7);
856}
857
858/**
859* Computes values for map legend given a value and an array of jenks breakpoints
860* @param {number} weight of point to plot on map
861* @param {number Array} breakpoints, an array of 5 points corresponding to bounds of 4 natural ranges
862* @returns {String} an RGB value corresponding to a subset of data
863*/
864function mapWidgetLegendGetHeatValue(weight, breakpoints) {
865
866 // Determine into which range the weight falls
867 var weightColor = 0;
868 if (weight >= breakpoints[3]) {
869 weightColor = 3;
870 } else if (weight >= breakpoints[2]) {
871 weightColor = 2;
872 } else if (weight >= breakpoints[1]) {
873 weightColor = 1;
874 }
875
876 // Get default map color palette
877 var colorValues = mapWidgetGetColorPalette();
878 return colorValues[weightColor];
879}
880
881/**
882* Returns an array containing a 4-color palette, lightest to darkest
883* External palette source: http://www.colourlovers.com/palette/2763366/s_i_l_e_n_c_e_r
884* @returns {Array} [colors]
885*/
886function mapWidgetGetColorPalette() {
887 return [
888 "rgb(115,189,158)",
889 "rgb(74,142,145)",
890 "rgb(19,93,96)",
891 "rgb(7,51,46)"
892 ];
893}
894
895/**
896* Computes radius for a given data point from a spatial cell
897* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
898* @returns {number} radius between 2 points in metres
899*/
900function mapWidgetComputeCircleRadius(spatialCell, breakpoints) {
901
902 var weight = spatialCell.weight;
903 // Compute weight color
904 var weightColor = 0.25;
905 if (weight >= breakpoints[3]) {
906 weightColor = 1.0;
907 } else if (weight >= breakpoints[2]) {
908 weightColor = 0.75;
909 } else if (weight >= breakpoints[1]) {
910 weightColor = 0.5;
911 }
912
913 // Define Boundary Points
914 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
915 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
916 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
917
918 // TODO not actually a weight color :)
919 return weightColor * 1000 * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
920}
921
922/** External Utility Methods **/
923
924/**
925 * Calculates the distance between two latlng locations in km.
926 * @see http://www.movable-type.co.uk/scripts/latlong.html
927 *
928 * @param {google.maps.LatLng} p1 The first lat lng point.
929 * @param {google.maps.LatLng} p2 The second lat lng point.
930 * @return {number} The distance between the two points in km.
931 * @private
932*/
933function distanceBetweenPoints_(p1, p2) {
934 if (!p1 || !p2) {
935 return 0;
936 }
937
938 var R = 6371; // Radius of the Earth in km
939 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
940 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
941 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
942 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
943 Math.sin(dLon / 2) * Math.sin(dLon / 2);
944 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
945 var d = R * c;
946 return d;
947};