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