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