blob: 532e259fdb345c8d07e6b2507c558025dbd97dc6 [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,
252 "query_string" : "use dataverse twitter;\n"
253 };
254
255 var a = new AsterixSDK()
256 .callback(cherryQuerySyncCallback, "sync")
257 .callback(cherryQueryAsyncCallback, "async")
258 .send(
259 "http://localhost:19002/query",
260 {
261 "query" : "use dataverse twitter;\n" + f.val(),
262 "mode" : build_cherry_mode
263 },
264 extra
265 );
genia.likes.science@gmail.com20928902013-05-10 10:39:27 -0700266
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700267 APIqueryTracker = {
genia.likes.science@gmail.comc8e540d2013-05-10 14:02:30 -0700268 "query" : "use dataverse twitter;",// buildCherryQuery.parameters["statements"].join("\n"),
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700269 "data" : formData
270 };
271
272 $('#dialog').html(APIqueryTracker["query"]);//.replace("\n", '<br />'));
273
274 if (!$('#asbox').is(":checked")) {
275 $('#show-query-button').attr("disabled", false);
276 } else {
277 $('#show-query-button').attr("disabled", true);
278 }
279 });
280
281});
282
genia.likes.science@gmail.com2c678ea2013-06-05 19:49:24 -0700283function temporary_rectangle(bounds) {
284 var lower_left = 'create-point(' + bounds["sw"]["lat"] + ',' + bounds["sw"]["lng"] + ')';
285 var upper_right = 'create-point(' + bounds["ne"]["lat"] + ',' + bounds["ne"]["lng"] + ')';
286 return 'create-rectangle(' + lower_left + ', ' + upper_right + ')';
287}
288
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700289/** Asynchronous Query Management - Handles & Such **/
290
291/**
292* Checks through each asynchronous query to see if they are ready yet
293*/
294function asynchronousQueryIntervalUpdate() {
295 for (var handle_key in asyncQueryManager) {
296 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
297 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
298 }
299 }
300}
301
302/**
303* Returns current time interval to check for asynchronous query readiness
304* @returns {number} milliseconds between asychronous query checks
305*/
306function asynchronousQueryGetInterval() {
307 var seconds = 10;
308 return seconds * 1000;
309}
310
311/**
312* Updates UI when an API Query's status is marked ready
313* @param {Object} res, a result object from the Asterix API
314* @param {object} extra_info, containing the asynchronous handle's id
315*/
316function asynchronousQueryAPIStatusReceived (res, extra_info) {
317 var handle_outcome = $.parseJSON(res[0]);
318 var handle_id = extra_info["handle_id"];
319 if (handle_outcome["status"] == "SUCCESS") {
320
321 // We don't need to check if this one is ready again, it's not going anywhere...
322 // Unless the life cycle of handles has changed drastically
323 asyncQueryManager[handle_id]["ready"] = true;
324
325 // Make this handle's result look retrievable
326 $('#handle_' + handle_id).addClass("label-success");
327 }
328}
329
330/**
331* Retrieves status of an asynchronous query, using an opaque result handle from API
332* @param {Object} handle, an object previously returned from an async call
333* @param {number} handle_id, the integer ID parsed from the handle object
334*/
335function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
336 var apiQueryStatus = new AsterixCoreAPI()
337 .dataverse("twitter")
338 .handle(handle)
339 .success(asynchronousQueryAPIStatusReceived, true)
340 .add_extra("handle_id", handle_id)
341 .api_core_query_status();
342}
343
344/**
345* On-success callback after async API query
346* @param {object} res, a result object containing an opaque result handle to Asterix
347* @param {object} extra, a result object containing a query string and query parameters
348*/
349function cherryQueryAsyncCallback(res, extra) {
350
351 // Parse handle, handle id and query from async call result
352 var handle = res[0];
353 var handle_query = extra["query_string"];
354 var handle_id = $.parseJSON(handle)["handle"].toString().split(',')[0];
355
356 // Add to stored map of existing handles
357 asyncQueryManager[handle_id] = {
358 "handle" : handle,
359 "query" : handle_query,
360 "data" : extra["payload"]
361 };
362
363 $('#review-handles-dropdown').append('<a href="#" class="holdmenu"><span class="label" id="handle_' + handle_id + '">Handle ' + handle_id + '</span></a>');
364
365 $('#handle_' + handle_id).hover(
366 function(){
367 $('#query-preview-window').html('');
368 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
369 },
370 function() {
371 $('#query-preview-window').html('');
372 }
373 );
374
375 $('#handle_' + handle_id).on('click', function (e) {
376
377 // make sure query is ready to be run
378 if (asyncQueryManager[handle_id]["ready"]) {
379
380 // Update API Query Tracker and view to reflect this query
381 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
382 APIqueryTracker = {
383 "query" : asyncQueryManager[handle_id]["query"],
384 "data" : asyncQueryManager[handle_id]["data"]
385 };
386 $('#dialog').html(APIqueryTracker["query"]);
387
388 // Generate new Asterix Core API Query
389 var asyncResultQuery = new AsterixCoreAPI()
390 .dataverse("twitter")
391 .handle(asyncQueryManager[handle_id]["handle"])
392 .success(cherryQuerySyncCallback, true)
393 .add_extra("payload", asyncQueryManager[handle_id]["data"]) // Legacy
394 .add_extra("query_string", asyncQueryManager[handle_id]["query"]) // Legacy
395 .api_core_query_result();
396 }
397 });
398}
399
400
401/** Core Query Management and Drilldown
402
403/**
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700404* Utility Method for parsing a record of this form:
405* { "cell": rectangle("22.5,64.5 24.5,66.5"), "count": 5 }
406* returns a json object with keys: weight, latSW, lngSW, latNE, lngNE
407*/
408function getRecord(cell_count_record) {
409 var record_representation = {};
410
411 var rectangle = cell_count_record.split('")')[0].split('("')[1];
412 record_representation["latSW"] = parseFloat(rectangle.split(" ")[0].split(',')[0]);
413 record_representation["lngSW"] = parseFloat(rectangle.split(" ")[0].split(',')[1]);
414 record_representation["latNE"] = parseFloat(rectangle.split(" ")[1].split(',')[0]);
415 record_representation["lngNE"] = parseFloat(rectangle.split(" ")[1].split(',')[1]);
416 record_representation["weight"] = parseInt(cell_count_record.split('count": ')[1].split(" ")[0]);
417
418 return record_representation;
419}
420
421/**
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700422* A spatial data cleaning and mapping call
423* @param {Object} res, a result object from a cherry geospatial query
424* @param {Object} extra, extra data passed from the API call - legacy stuff
425*/
426function cherryQuerySyncCallback(res, extra) {
genia.likes.science@gmail.combdfa27a2013-05-08 10:44:34 -0700427 records = res["results"];
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700428
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700429 var coordinates = [];
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700430 var weights = [];
431
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700432 for (var subrecord in records) {
genia.likes.science@gmail.com30f57fb2013-06-05 19:56:45 -0700433 var coordinate = getRecord(records[subrecord]);
434 weights.push(coordinate["weight"]);
435 coordinates.push(coordinate);
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700436 }
genia.likes.science@gmail.comb5af4042013-06-05 20:15:37 -0700437
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700438 triggerUIUpdate(coordinates, extra["payload"], weights);
439}
440
441/**
442* Triggers a map update based on a set of spatial query result cells
443* @param [Array] mapPlotData, an array of coordinate and weight objects
444* @param [Array] params, an object containing original query parameters [LEGACY]
445* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
446*/
447function triggerUIUpdate(mapPlotData, params, plotWeights) {
448 /** Clear anything currently on the map **/
449 mapWidgetClearMap();
450 param_placeholder = params;
451
452 // Compute data point spread
453 var dataBreakpoints = mapWidgetLegendComputeNaturalBreaks(plotWeights);
454
455 $.each(mapPlotData, function (m, val) {
456
457 // Only map points in data range of top 4 natural breaks
458 if (mapPlotData[m].weight > dataBreakpoints[0]) {
459
460 // Get color value of legend
461 var mapColor = mapWidgetLegendGetHeatValue(mapPlotData[m].weight, dataBreakpoints);
462 var markerRadius = mapWidgetComputeCircleRadius(mapPlotData[m], dataBreakpoints);
463 var point_opacity = 1.0; // TODO
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700464
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700465 var point_center = new google.maps.LatLng(
466 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
467 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
468
469 // Create and plot marker
470 var map_circle_options = {
471 center: point_center,
472 radius: markerRadius,
473 map: map,
474 fillOpacity: point_opacity,
475 fillColor: mapColor,
476 clickable: true
477 };
478 var map_circle = new google.maps.Circle(map_circle_options);
479 map_circle.val = mapPlotData[m];
genia.likes.science@gmail.comb5af4042013-06-05 20:15:37 -0700480 map_circle.info = new google.maps.InfoWindow({
481 content: mapPlotData[m].weight.toString()
482 });
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700483
484 // Clicking on a circle drills down map to that value
485 google.maps.event.addListener(map_circle, 'click', function (event) {
genia.likes.science@gmail.comb5af4042013-06-05 20:15:37 -0700486 // DEMO Stability Placeholder
487 // onMapPointDrillDown(map_circle.val);
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700488 });
489
490 // Add this marker to global marker cells
491 map_cells.push(map_circle);
492 }
493 });
494
495 // Add a legend to the map
496 mapControlWidgetAddLegend(dataBreakpoints);
497}
498
499/**
500* prepares an Asterix API query to drill down in a rectangular spatial zone
501*
502* @params {object} marker_borders [LEGACY] a set of bounds for a region from a previous api result
503*/
504function onMapPointDrillDown(marker_borders) {
505 var zoneData = APIqueryTracker["data"]; // TODO: Change how this is managed
506
507 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngNE);
508 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngSW);
509
510 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
511 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
512 zoneData["swLng"] = -1*zoneBounds.getSouthWest().lng();
513 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
514 zoneData["neLng"] = -1*zoneBounds.getNorthEast().lng();
515
516 mapWidgetClearMap();
517
518 var customBounds = new google.maps.LatLngBounds();
519 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], -1*zoneData["swLng"]);
520 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], -1*zoneData["neLng"]);
521 customBounds.extend(zoomSWBounds);
522 customBounds.extend(zoomNEBounds);
523 map.fitBounds(customBounds);
524
525 var drilldown_string = ["use dataverse " + "twitter" + ";",
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700526 "for $t in dataset('" + "TweetMessages" + "')",
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700527 "let $keyword := \"" +zoneData["keyword"] + "\"",
528 "let $region := polygon(\"",
529 zoneData["neLat"] + "," + zoneData["swLng"] + " ",
530 zoneData["swLat"] + "," + zoneData["swLng"] + " ",
531 zoneData["swLat"] + "," + zoneData["neLng"] + " ",
532 zoneData["neLat"] + "," + zoneData["neLng"] + "\")",
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700533 "where spatial-intersect($t.sender-location, $region) and",
534 "$t.send-time > datetime(\"" + zoneData["startdt"] + "\") and $t.send-time < datetime(\"" + zoneData["enddt"] + "\") and",
535 "contains($t.message-text, $keyword)",
536 "return { \"tweetId\": $t.tweetid, \"tweetText\": $t.message-text, \"tweetLoc\": $t.sender-location}"];
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700537
538 var zQ = new AsterixCoreAPI()
539 .dataverse("twitter")
540 .statements(drilldown_string)
541 .add_extra("payload", zoneData) // Legacy
542 .mode("synchronous")
543 .success(onTweetbookQuerySuccessPlot, true)
544 .add_extra("query_string", drilldown_string.join(" "))
545 .add_extra("marker_path", "../img/mobile2.png")
546 .add_extra("on_click_marker", onClickTweetbookMapMarker)
547 .add_extra("on_clean_result", onCleanTweetbookDrilldown)
548 .api_core_query();
549}
550
551function triggerUIUpdateOnDropTweetBook(extra_info) {
552 // TODO Remove menu entry
553 // review-tweetbook-titles.html('')
554 // Append each in review_mode_tweetbooks if not same as extra_info["title"]
555 // $('#review-tweetbook-titles').append('<li><a href="#">' + extra_info["title"] + '</a></li>');
556}
557
558function onDrillDownAtLocation(tO) {
559
560 $('#drilldown_modal_body').append('<div id="drilltweetobj' + tO["tweetEntryId"] + '"></div>');
561
562 $('#drilltweetobj' + tO["tweetEntryId"]).append('<p>' + tO["tweetText"] + '</p>');
563
564 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="metacomment' + tO["tweetEntryId"] + '">');
565
566 if (tO.hasOwnProperty("tweetbookComment")) {
567 $('#metacomment' + tO["tweetEntryId"]).val(tO["tweetbookComment"]);
568 }
569
570 $('#drilltweetobj' + tO["tweetEntryId"]).append('<button title="' + tO["tweetEntryId"] + '" id="meta' + tO["tweetEntryId"] + '">Add Comment to...</button>');
571
572 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="tweetbooktarget' + tO["tweetEntryId"] + '">');
573
574 $('#meta' + tO["tweetEntryId"])
575 .button()
576 .click( function () {
577
578 var valid = $('#meta' + tO["tweetEntryId"]).attr('title');
579 var valcomment = $("#metacomment" + valid).val();
580 var valtext = drilldown_data_map_vals[valid.toString()]["tweetText"];
581 var tweetbookname = $("#tweetbooktarget" + valid).val();
582
583 //Try to add the tweetbook, if it does not already exist
584 onCreateNewTweetBook(tweetbookname);
585
586 var apiCall = new AsterixCoreAPI()
587 .dataverse("twitter")
588 .statements([
589 'delete $l from dataset ' + tweetbookname + ' where $l.id = "' + valid + '";',
590 'insert into dataset ' + tweetbookname + '({ "id" : "' + valid + '", "metacomment" : "' + valcomment + '"});'
591 ])
592 .api_core_update();
593 });
594
595}
596
597function onCreateNewTweetBook(tweetbook_title) {
598
599 var newTweetbookAPICall = new AsterixCoreAPI()
600 .dataverse("twitter")
601 .create_dataset({
602 "dataset" : tweetbook_title,
603 "type" : "MetaTweet",
604 "primary_key" : "id"
605 })
606 .add_extra("title", tweetbook_title)
607 .success(triggerUIUpdateOnNewTweetBook, true)
608 .api_core_update();
609 // Possible bug...ERROR 1: Invalid statement: Non-DDL statement DATASET_DECL to the DDL API.
610
611 /*var removeTest = new AsterixCoreAPI()
612 .dataverse("twitter")
613 .drop_dataset("blah")
614 .api_core_update(); */
615}
616
617function onDropTweetBook(tweetbook_title) {
618 var removeTest = new AsterixCoreAPI()
619 .dataverse("twitter")
620 .drop_dataset(tweetbook_title)
621 .success(triggerUIUpdateOnDropTweetBook, true)
622 .api_core_update();
623}
624
625function onTweetbookQuerySuccessPlot (res, extra) {
626 var response = $.parseJSON(res[0]);
627 var records = response["results"];
628 var coordinates = [];
629 map_tweet_markers = [];
630 map_tweet_overlays = [];
631 drilldown_data_map = {};
632 drilldown_data_map_vals = {};
633
634 var micon = extra["marker_path"];
635 var marker_click_function = extra["on_click_marker"];
636 var clean_result_function = extra["on_clean_result"];
637
638 coordinates = clean_result_function(records);
639
640 for (var dm in coordinates) {
641 var keyLat = coordinates[dm].tweetLat.toString();
642 var keyLng = coordinates[dm].tweetLng.toString();
643 if (!drilldown_data_map.hasOwnProperty(keyLat)) {
644 drilldown_data_map[keyLat] = {};
645 }
646 if (!drilldown_data_map[keyLat].hasOwnProperty(keyLng)) {
647 drilldown_data_map[keyLat][keyLng] = [];
648 }
649 drilldown_data_map[keyLat][keyLng].push(coordinates[dm]);
650 drilldown_data_map_vals[coordinates[dm].tweetEntryId.toString()] = coordinates[dm];
651 }
652
653 $.each(drilldown_data_map, function(drillKeyLat, valuesAtLat) {
654 $.each(drilldown_data_map[drillKeyLat], function (drillKeyLng, valueAtLng) {
655
656 // Get subset of drilldown position on map
657 var cposition = new google.maps.LatLng(parseFloat(drillKeyLat), parseFloat(drillKeyLng));
658
659 // Create a marker using the snazzy phone icon
660 var map_tweet_m = new google.maps.Marker({
661 position: cposition,
662 map: map,
663 icon: micon,
664 clickable: true,
665 });
666
667 // Open Tweet exploration window on click
668 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
669 marker_click_function(drilldown_data_map[drillKeyLat][drillKeyLng]);
670 });
671
672 // Add marker to index of tweets
673 map_tweet_markers.push(map_tweet_m);
674
675 });
676 });
677}
678
679function triggerUIUpdateOnNewTweetBook(extra_info) {
680 // Add tweetbook to log
681 if (parseInt($.inArray(extra_info["title"], review_mode_tweetbooks)) == -1) {
682 review_mode_tweetbooks.push(extra_info["title"]);
683
684 // Add menu entry
685 $('#review-tweetbook-titles').append('<li><a href="#"><span id="tbook_' + extra_info["title"] + '">' + extra_info["title"] + '</span></a></li>');
686
687 // Add on-click behavior
688 $("#tbook_" + extra_info["title"]).on('click', function(e) {
689 var plotTweetbookQuery = new AsterixCoreAPI()
690 .dataverse("twitter")
691 .success(onTweetbookQuerySuccessPlot, true)
692 .aql_for({"mt": extra_info["title"]})
693 .aql_where(["int64($mt.id)%1500 = 0"])
694 .aql_return({ "id" : "$mt.id", "location" : "$mt.loc", "comment" : "$mt.metacomment", "tweet" : "$mt.tweet" })
695 .add_extra("tweetbook_title", extra_info["title"])
696 .add_extra("marker_path", "../img/mobile_green2.png")
697 .add_extra("on_click_marker", onClickTweetbookMapMarker)
698 .add_extra("on_clean_result", onCleanPlotTweetbook)
699 .api_core_query();
700
701 });
702 }
703}
704
705function onCleanPlotTweetbook(records) {
706 var toPlot = [];
707 for (var subrecords = 0; subrecords < records.length; subrecords++) {
708 for (var record in records[subrecords]) {
709 var tweetbook_element = {
710 "tweetEntryId" : parseInt(records[subrecords][record].split(",")[0].split(":")[1].split('"')[1]),
711 "tweetLat" : parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[0]),
712 "tweetLng" : -1*parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[1].split("\"")[0]),
713 "tweetText" : records[subrecords][record].split("tweet\": \"")[1].split("\"")[0],
714 "tweetbookComment" : records[subrecords][record].split("comment\": \"")[1].split("\", \"tweet\":")[0]
715 };
716 toPlot.push(tweetbook_element);
717 }
718 }
719 return toPlot;
720}
721
722function onCleanTweetbookDrilldown (rec) {
723 var drilldown_cleaned = [];
724 for (var subresult = 0; subresult < rec.length; subresult++) {
725 for (var entry in rec[subresult]) {
726
727 var drill_element = {
728 "tweetEntryId" : parseInt(rec[subresult][entry].split(",")[0].split(":")[1].split('"')[1]),
729 "tweetText" : rec[subresult][entry].split("tweetText\": \"")[1].split("\", \"tweetLoc\":")[0],
730 "tweetLat" : parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[0]),
731 "tweetLng" : -1*parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[1].split("\"")[0])
732 };
733 drilldown_cleaned.push(drill_element);
734
735 }
736 }
737 return drilldown_cleaned;
738}
739
740function onClickTweetbookMapMarker(tweet_arr) {
741 $('#drilldown_modal_body').html('');
742
743 // Clear existing display
744 $.each(tweet_arr, function (t, valueT) {
745 var tweet_obj = tweet_arr[t];
746 onDrillDownAtLocation(tweet_obj);
747 });
748
749 $('#drilldown_modal').modal('show');
750}
751
752/** Toggling Review and Explore Modes **/
753
754/**
755* Explore mode: Initial map creation and screen alignment
756*/
757function onOpenExploreMap () {
758 var explore_column_height = $('#explore-well').height();
759 $('#map_canvas').height(explore_column_height + "px");
760 $('#review-well').height(explore_column_height + "px");
761 $('#review-well').css('max-height', explore_column_height + "px");
762 var pad = $('#review-well').innerHeight() - $('#review-well').height();
763 var prev_window_target = $('#review-well').height() - 20 - $('#group-tweetbooks').innerHeight() - $('#group-background-query').innerHeight() - 2*pad;
764 $('#query-preview-window').height(prev_window_target +'px');
765}
766
767/**
768* Launching explore mode: clear windows/variables, show correct sidebar
769*/
770function onLaunchExploreMode() {
771 $('#review-active').removeClass('active');
772 $('#review-well').hide();
773
774 $('#explore-active').addClass('active');
775 $('#explore-well').show();
776
777 $("#clear-button").trigger("click");
778}
779
780/**
781* Launching review mode: clear windows/variables, show correct sidebar
782*/
783function onLaunchReviewMode() {
784 $('#explore-active').removeClass('active');
785 $('#explore-well').hide();
786 $('#review-active').addClass('active');
787 $('#review-well').show();
788
789 $("#clear-button").trigger("click");
790}
791
792/** Map Widget Utility Methods **/
793
794/**
795* Plots a legend onto the map, with values in progress bars
796* @param {number Array} breakpoints, an array of numbers representing natural breakpoints
797*/
798function mapControlWidgetAddLegend(breakpoints) {
799
800 // Retriever colors, lightest to darkest
801 var colors = mapWidgetGetColorPalette();
802
803 // Initial div structure
804 $("#map_canvas_legend").html('<div id="legend-holder"><div id="legend-progress-bar" class="progress"></div><span id="legend-label"></span></div>');
805
806 // Add color scale to legend
807 $('#legend-progress-bar').css("width", "200px").html('');
808
809 // Add a progress bar for each color
810 for (var color in colors) {
811
812 // Bar values
813 var upperBound = breakpoints[parseInt(color) + 1];
814
815 // Create Progress Bar
816 $('<div/>')
817 .attr("class", "bar")
818 .attr("id", "pbar" + color)
819 .css("width" , '25.0%')
820 .html("< " + upperBound)
821 .appendTo('#legend-progress-bar');
822
823 $('#pbar' + color).css({
824 "background-image" : 'none',
825 "background-color" : colors[parseInt(color)]
826 });
827
828 // Attach a message showing minimum bounds
829 $('#legend-label').html('Regions with at least ' + breakpoints[0] + ' tweets');
830 $('#legend-label').css({
831 "color" : "black"
832 });
833 }
834
835 // Add legend to map
836 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legend-holder'));
837 $('#map_canvas_legend').show();
838}
839
840/**
841* Clears map elements - legend, plotted items, overlays
842*/
843function mapWidgetClearMap() {
844
845 if (selectionRect) {
846 selectionRect.setMap(null);
847 selectionRect = null;
848 }
849 for (c in map_cells) {
850 map_cells[c].setMap(null);
851 }
852 map_cells = [];
853 for (m in map_tweet_markers) {
854 map_tweet_markers[m].setMap(null);
855 }
856 map_tweet_markers = [];
857
858 // Remove legend from map
859 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].clear();
860}
861
862/**
863* Uses jenks algorithm in geostats library to find natural breaks in numeric data
864* @param {number Array} weights of points to plot
865* @returns {number Array} array of natural breakpoints, of which the top 4 subsets will be plotted
866*/
867function mapWidgetLegendComputeNaturalBreaks(weights) {
868 var plotDataWeights = new geostats(weights.sort());
869 return plotDataWeights.getJenks(6).slice(2, 7);
870}
871
872/**
873* Computes values for map legend given a value and an array of jenks breakpoints
874* @param {number} weight of point to plot on map
875* @param {number Array} breakpoints, an array of 5 points corresponding to bounds of 4 natural ranges
876* @returns {String} an RGB value corresponding to a subset of data
877*/
878function mapWidgetLegendGetHeatValue(weight, breakpoints) {
879
880 // Determine into which range the weight falls
881 var weightColor = 0;
882 if (weight >= breakpoints[3]) {
883 weightColor = 3;
884 } else if (weight >= breakpoints[2]) {
885 weightColor = 2;
886 } else if (weight >= breakpoints[1]) {
887 weightColor = 1;
888 }
889
890 // Get default map color palette
891 var colorValues = mapWidgetGetColorPalette();
892 return colorValues[weightColor];
893}
894
895/**
896* Returns an array containing a 4-color palette, lightest to darkest
897* External palette source: http://www.colourlovers.com/palette/2763366/s_i_l_e_n_c_e_r
898* @returns {Array} [colors]
899*/
900function mapWidgetGetColorPalette() {
901 return [
902 "rgb(115,189,158)",
903 "rgb(74,142,145)",
904 "rgb(19,93,96)",
905 "rgb(7,51,46)"
906 ];
907}
908
909/**
910* Computes radius for a given data point from a spatial cell
911* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
912* @returns {number} radius between 2 points in metres
913*/
914function mapWidgetComputeCircleRadius(spatialCell, breakpoints) {
915
916 var weight = spatialCell.weight;
917 // Compute weight color
918 var weightColor = 0.25;
919 if (weight >= breakpoints[3]) {
920 weightColor = 1.0;
921 } else if (weight >= breakpoints[2]) {
922 weightColor = 0.75;
923 } else if (weight >= breakpoints[1]) {
924 weightColor = 0.5;
925 }
926
927 // Define Boundary Points
928 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
929 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
930 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
931
932 // TODO not actually a weight color :)
933 return weightColor * 1000 * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
934}
935
936/** External Utility Methods **/
937
938/**
939 * Calculates the distance between two latlng locations in km.
940 * @see http://www.movable-type.co.uk/scripts/latlong.html
941 *
942 * @param {google.maps.LatLng} p1 The first lat lng point.
943 * @param {google.maps.LatLng} p2 The second lat lng point.
944 * @return {number} The distance between the two points in km.
945 * @private
946*/
947function distanceBetweenPoints_(p1, p2) {
948 if (!p1 || !p2) {
949 return 0;
950 }
951
952 var R = 6371; // Radius of the Earth in km
953 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
954 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
955 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
956 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
957 Math.sin(dLon / 2) * Math.sin(dLon / 2);
958 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
959 var d = R * c;
960 return d;
961};