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