plugins: updated js framework + googlemaps and hazelnut to better handle sets and...
[myslice.git] / plugins / googlemaps / static / js / googlemaps.js
1 /**
2  * Description: display a query result in a Google map
3  * Copyright (c) 2012-2013 UPMC Sorbonne Universite - INRIA
4  * License: GPLv3
5  */
6
7 (function($){
8
9    var GoogleMaps = Plugin.extend({
10
11         init: function(options, element)
12         {
13             this._super(options, element);
14
15             /* Member variables */
16             // query status
17             this.received_all = false;
18             this.received_set = false;
19             this.in_set_buffer = Array();
20
21             // key -> { marker, checked }
22             this.map_markers = {}
23
24             /* XXX Events XXX */
25             this.el().on('show', this, this.on_show);
26             // TODO in destructor
27             // $(window).unbind('Hazelnut');
28
29             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
30             this.method = query.object;
31
32             var keys = manifold.metadata.get_key(this.method);
33             this.key = (keys && keys.length == 1) ? keys[0] : null;
34
35             /* Setup query and record handlers */
36             this.listen_query(options.query_uuid);
37             this.listen_query(options.query_all_uuid, 'all');
38
39             /* GUI setup and event binding */
40             this.initialize_map();
41         }, // init
42
43         /* PLUGIN EVENTS */
44
45         on_show: function(e)
46         {
47             var self = e.data;
48             google.maps.event.trigger(self.map, 'resize');
49         }, // on_show
50
51         /* GUI EVENTS */
52
53         /* GUI MANIPULATION */
54
55         /**
56          */
57         initialize_map: function()
58         {
59             this.markerCluster = null;
60             this.coords = new Array();
61
62             var myLatlng = new google.maps.LatLng(this.options.latitude, this.options.longitude);
63             var myOptions = {
64                 zoom: this.options.zoom,
65                 center: myLatlng,
66                 mapTypeId: google.maps.MapTypeId.ROADMAP
67             }
68       
69             var id = this.options.plugin_uuid + manifold.separator + 'map';
70             this.map = new google.maps.Map(document.getElementById(id), myOptions);
71             this.infowindow = new google.maps.InfoWindow();
72         }, // initialize_map
73
74         set_checkbox: function(record, checked)
75         {
76             var key_value;
77             /* The function accepts both records and their key */
78             switch (manifold.get_type(record)) {
79                 case TYPE_VALUE:
80                     key_value = record;
81                     break;
82                 case TYPE_RECORD:
83                     /* XXX Test the key before ? */
84                     key_value = record[this.key];
85                     break;
86                 default:
87                     throw "Not implemented";
88                     break;
89             }
90
91             // we cannot directly edit html, since nothing but marker is displayed
92             //var checkbox_id = this.id('checkbox', this.id_from_key(this.key, key_value));
93             //checkbox_id = '#' + checkbox_id.replace(/\./g, '\\.');
94             //$(checkbox_id, this.table.fnGetNodes()).attr('checked', checked);
95
96             var dict_info = this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')];
97
98             /* Default: swap check status */
99             if (typeof checked === 'undefined')
100                 dict_info.in_set = !dict_info.in_set;
101             else
102                 dict_info.in_set = checked;
103
104             // Update the marker content
105             dict_info.marker.content = this.get_marker_content(dict_info.record, checked);
106
107             // Update opened infowindow
108             // XXX Factor this code
109             this.infowindow.close();
110             this.infowindow.setContent(dict_info.marker.content);
111             this.infowindow.open(this.map, dict_info.marker);
112             this.els('map-button').unbind('click').click(this, this._button_click);
113
114             //var button = this.checkbox(record, checked);
115             //this.el('checkbox', this.id_from_record(method, record)).html(button);
116         }, 
117
118         checkbox: function(record, checked) 
119         {
120             if (typeof checked === 'undefined')
121                 checked = false;
122
123             var method  = manifold.query_store.find_analyzed_query(this.options.query_uuid).object;
124             var action = checked ? 'checked' : 'del';
125             var ctx = {
126                 action_class  : checked ? 'ui-icon-circle-minus' : 'ui-icon-circle-plus',
127                 action_message: checked ? 'Remove from slice' : 'Add to slice',
128             };
129             var button = this.load_template('template', ctx);
130
131             var id_record = this.id_from_record(method, record);
132             if (!id_record)
133                 return 'ERROR';
134             var id = this.id('checkbox', this.id_from_record(method, record));
135             return "<div id='" + id + "'>" + button + "</div>";
136         },
137         
138         get_marker_content: function(record, checked)
139         {
140             return '<p><b>' + this.method + '</b>: ' + get_value(record['resource_hrn']) + '<br/><b>network</b>: ' + get_value(record['network'])+'</p>' + this.checkbox(record, checked);
141         },
142
143         /**
144          */
145         new_record: function(record)
146         {
147             // get the coordinates
148             var latitude=get_value(record['latitude']);
149             var longitude=get_value(record['longitude']);
150             var hash = latitude + longitude;
151
152             // check to see if we've seen this hash before
153             if(this.coords[hash] == null) {
154                 // get coordinate object
155                 var myLatlng = new google.maps.LatLng(latitude, longitude);
156                 // store an indicator that we've seen this point before
157                 this.coords[hash] = 1;
158             } else {
159                 // add some randomness to this point 1500 = 100 meters, 15000 = 10 meters
160                 var lat = latitude + (Math.random() -.5) / 1500; 
161                 var lng = longitude + (Math.random() -.5) / 1500; 
162
163                 // get the coordinate object
164                 var myLatlng = new google.maps.LatLng(lat, lng);
165             }
166             // XXX not working
167             if (!(record['latitude'])) {
168                 return true;
169             }
170
171             //jQuery(".map-button").click(button_click);
172             //if(jQuery.inArray(record, rows)>-1){
173                 var marker = new google.maps.Marker({
174                     position: myLatlng,
175                     title: get_value(record['hostname']),
176                     // This should be done by the rendering
177                     content: this.get_marker_content(record, false),
178                 }); 
179
180                 this.addInfoWindow(marker, this.map);
181                 var key_value = (this.key in record) ? record[this.key] : null;
182                 if (!key_value)
183                     return;
184                 this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')] = {
185                     marker: marker,
186                     in_set: false,
187                     record: record,
188                     value: key_value
189                 }
190             //}
191
192         }, // new_record
193
194         addInfoWindow: function(marker, map)
195         {
196             var self = this;
197             google.maps.event.addListener(marker, 'click', function () {     
198                 if(self.infowindow){
199                     self.infowindow.close();
200                 }
201                 self.infowindow.setContent(marker.content);// = new google.maps.InfoWindow({ content: marker.content });
202                 self.infowindow.open(map, marker);
203                 // onload of the infowindow on the map, bind a click on a button
204                 google.maps.event.addListener(self.infowindow, 'domready', function() {
205                     self.els('map-button').unbind('click').click(self, self._button_click);
206 //                    jQuery(".map-button").click({instance: instance_, infoWindow: object.infowindow}, button_click);                     
207                 });
208             });
209         }, // addInfoWindow
210
211
212         /*************************** QUERY HANDLER ****************************/
213
214         /*************************** RECORD HANDLER ***************************/
215
216         on_new_record: function(record)
217         {
218             if (this.received_all)
219                 // update checkbox for record
220                 this.set_checkbox(record);
221             else
222                 // store for later update of checkboxes
223                 this.in_set_buffer.push(record);
224         },
225
226         on_clear_records: function(record)
227         {
228
229         },
230
231         // Could be the default in parent
232         on_query_in_progress: function()
233         {
234             this.spin();
235         },
236
237         on_query_done: function()
238         {
239             if (this.received_all)
240                 this.unspin();
241             this.received_set = true;
242         },
243
244         on_field_state_changed: function(data)
245         {
246             switch(data.request) {
247                 case FIELD_REQUEST_ADD:
248                     this.set_checkbox(data.value, true);
249                     break;
250                 case FIELD_REQUEST_REMOVE:
251                     this.set_checkbox(data.value, false);
252                     break;
253                 case FIELD_REQUEST_RESET:
254                     this.set_checkbox(data.value); // swap
255                     break;
256                 default:
257                     break;
258             }
259         },
260
261
262         // all
263
264         on_all_new_record: function(record)
265         {
266             this.new_record(record);
267         },
268
269         on_all_clear_records: function()
270         {
271         },
272
273         on_all_query_in_progress: function()
274         {
275             // XXX parent
276             this.spin();
277         },
278
279         on_all_query_done: function()
280         {
281
282             // MarkerClusterer
283             var markers = [];
284             $.each(this.map_markers, function (k, v) { markers.push(v.marker); });
285
286             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
287             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
288                 var cluster_markers = cluster.getMarkers();
289                 var bounds  = new google.maps.LatLngBounds();
290                 /* 
291                 * date: 24/05/2012
292                 * author: lbaron
293                 * Firefox JS Error - replaced $.each by JQuery.each
294                 */                  
295                 jQuery.each(cluster_markers, function(i, marker){
296                     bounds.extend(marker.getPosition()); 
297                 });
298
299                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
300                 this.map.fitBounds(bounds);
301             });
302
303             var self = this;
304             if (this.received_set) {
305                 /* XXX needed ? XXX We uncheck all checkboxes ... */
306                 //$("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
307
308                 /* ... and check the ones specified in the resource list */
309                 $.each(this.in_set_buffer, function(i, record) {
310                     self.set_checkbox(record, true);
311                 });
312
313                 this.unspin();
314             }
315             this.received_all = true;
316
317         }, // on_all_query_done
318
319         /************************** PRIVATE METHODS ***************************/
320
321         _button_click: function(e)
322         {
323             var self   = e.data;
324
325             var escaped_key = self.key_from_id($(this).parent().attr('id'), 'checkbox');
326             var info_dict = self.map_markers[escaped_key];
327             var in_set = info_dict.in_set;
328             var value = info_dict.value;
329
330             var escaped_key = self.map_markers[self.key_from_id($(this).parent().attr('id'), 'checkbox')]
331             manifold.raise_event(self.options.query_uuid, (in_set) ? SET_REMOVED : SET_ADD, value);
332         } // _button_click
333
334     });
335
336     $.plugin('GoogleMaps', GoogleMaps);
337
338 })(jQuery);