4cfb3d356c7873bccb0d8f8cb0d4097d36d3fbec
[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=" + domid + " 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             // Thierry - this code seems to cause the googlmap area to go all grayed out 
117             // once all the quesries have come back
118             // BEG turning off temporarily
119             //            // Update opened infowindow
120             //            // XXX Factor this code
121             //            this.infowindow.close();
122             //            this.infowindow.open(this.map, dict_info.marker);
123             //            this.infowindow.setContent(dict_info.marker.content);
124             //            this.els('map-button').unbind('click').click(this, this._button_click);
125             // END turning off temporarily
126             //var button = this.checkbox(record, checked);
127             //this.el('checkbox', this.id_from_record(method, record)).html(button);
128         }, 
129
130         checkbox: function(record, checked) {
131             if (googlemaps_debug_detailed) messages.debug ("checkbox");
132             if (typeof checked === 'undefined')
133                 checked = false;
134
135             var method  = manifold.query_store.find_analyzed_query(this.options.query_uuid).object;
136             var action = checked ? 'checked' : 'del';
137             var ctx = {
138                 action_class  : checked ? 'ui-icon-circle-minus' : 'ui-icon-circle-plus',
139                 action_message: checked ? 'Remove from slice' : 'Add to slice',
140             };
141             var button = this.load_template('template', ctx);
142
143             var id_record = this.id_from_record(method, record);
144             if (!id_record)
145                 return 'ERROR';
146             var id = this.id('checkbox', this.id_from_record(method, record));
147             return "<div id='" + id + "'>" + button + "</div>";
148         },
149         
150         get_marker_content: function(record, checked) {
151             if (googlemaps_debug_detailed) messages.debug ("get_marker_content");
152             return '<p><b>' + this.method + '</b>: ' + get_value(record['resource_hrn']) + '<br/><b>network</b>: ' + get_value(record['network'])+'</p>' + this.checkbox(record, checked);
153         },
154
155         /**
156          */
157         new_record: function(record) {
158             if (googlemaps_debug_detailed) messages.debug ("new_record");
159             // get the coordinates
160             var latitude=get_value(record['latitude']);
161             var longitude=get_value(record['longitude']);
162             var hash = latitude + longitude;
163
164             // check to see if we've seen this hash before
165             if(this.coords[hash] == null) {
166                 // get coordinate object
167                 var myLatlng = new google.maps.LatLng(latitude, longitude);
168                 // store an indicator that we've seen this point before
169                 this.coords[hash] = 1;
170             } else {
171                 // add some randomness to this point 1500 = 100 meters, 15000 = 10 meters
172                 var lat = latitude + (Math.random() -.5) / 1500; 
173                 var lng = longitude + (Math.random() -.5) / 1500; 
174
175                 // get the coordinate object
176                 var myLatlng = new google.maps.LatLng(lat, lng);
177             }
178             // XXX not working
179             if (!(record['latitude'])) {
180                 return true;
181             }
182
183             //jQuery(".map-button").click(button_click);
184             //if(jQuery.inArray(record, rows)>-1){
185             var marker = new google.maps.Marker({
186                 position: myLatlng,
187                 title: get_value(record['hostname']),
188                 // This should be done by the rendering
189                 content: this.get_marker_content(record, false),
190             }); 
191
192             this.addInfoWindow(marker, this.map);
193             var key_value = (this.key in record) ? record[this.key] : null;
194             if (!key_value)
195                 return;
196             this.map_markers[unfold.escape_id(key_value).replace(/\\/g, '')] = {
197                 marker: marker,
198                 in_set: false,
199                 record: record,
200                 value: key_value
201             }
202             //}
203
204         }, // new_record
205
206         addInfoWindow: function(marker, map) {
207             if (googlemaps_debug_detailed) messages.debug ("addInfoWindow");
208             var self = this;
209             google.maps.event.addListener(marker, 'click', function () {     
210                 if(self.infowindow){
211                     self.infowindow.close();
212                 }
213                 self.infowindow.setContent(marker.content);// = new google.maps.InfoWindow({ content: marker.content });
214                 self.infowindow.open(map, marker);
215                 // onload of the infowindow on the map, bind a click on a button
216                 google.maps.event.addListener(self.infowindow, 'domready', function() {
217                     self.els('map-button').unbind('click').click(self, self._button_click);
218                     //                    jQuery(".map-button").click({instance: instance_, infoWindow: object.infowindow}, button_click);                     
219                 });
220             });
221         }, // addInfoWindow
222
223
224         /*************************** QUERY HANDLER ****************************/
225
226         /*************************** RECORD HANDLER ***************************/
227
228         on_new_record: function(record) {
229             if (googlemaps_debug_detailed) messages.debug("on_new_record");
230             if (this.received_all)
231                 // update checkbox for record
232                 this.set_checkbox(record);
233             else
234                 // store for later update of checkboxes
235                 this.in_set_buffer.push(record);
236         },
237
238         on_clear_records: function(record) {
239             if (googlemaps_debug_detailed) messages.debug("on_clear_records");
240         },
241
242         // Could be the default in parent
243         on_query_in_progress: function() {
244             if (googlemaps_debug) messages.debug("on_query_in_progress");
245             this.spin();
246         },
247
248         on_query_done: function() {
249             if (googlemaps_debug) messages.debug("on_query_done");          
250             if (this.received_all)
251                 this.unspin();
252             this.received_set = true;
253         },
254
255         on_field_state_changed: function(data) {
256             if (googlemaps_debug) messages.debug("on_field_state_changed");         
257             switch(data.request) {
258             case FIELD_REQUEST_ADD:
259             case FIELD_REQUEST_ADD_RESET:
260                 this.set_checkbox(data.value, true);
261                 break;
262             case FIELD_REQUEST_REMOVE:
263             case FIELD_REQUEST_REMOVE_RESET:
264                 this.set_checkbox(data.value, false);
265                 break;
266             default:
267                 break;
268             }
269         },
270
271
272         // all
273
274         on_all_new_record: function(record) {
275             if (googlemaps_debug_detailed) messages.debug("on_all_new_record");
276             this.new_record(record);
277         },
278
279         on_all_clear_records: function() {
280             if (googlemaps_debug) messages.debug("on_all_clear_records");           
281         },
282
283         on_all_query_in_progress: function() {
284             if (googlemaps_debug) messages.debug("on_all_query_in_progress");
285             // XXX parent
286             this.spin();
287         },
288
289         on_all_query_done: function() {
290             if (googlemaps_debug) messages.debug("on_all_query_done");
291             // MarkerClusterer
292             var markers = [];
293             $.each(this.map_markers, function (k, v) { markers.push(v.marker); });
294
295             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
296             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
297                 var cluster_markers = cluster.getMarkers();
298                 var bounds  = new google.maps.LatLngBounds();
299                 /* 
300                  * date: 24/05/2012
301                  * author: lbaron
302                  * Firefox JS Error - replaced $.each by JQuery.each
303                  */                  
304                 jQuery.each(cluster_markers, function(i, marker){
305                     bounds.extend(marker.getPosition()); 
306                 });
307
308                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
309                 this.map.fitBounds(bounds);
310             });
311
312             var self = this;
313             if (this.received_set) {
314                 /* XXX needed ? XXX We uncheck all checkboxes ... */
315                 //$("[id^='datatables-checkbox-" + this.options.plugin_uuid +"']").attr('checked', false);
316
317                 /* ... and check the ones specified in the resource list */
318                 $.each(this.in_set_buffer, function(i, record) {
319                     self.set_checkbox(record, true);
320                 });
321
322                 this.unspin();
323             }
324             this.received_all = true;
325
326         }, // on_all_query_done
327
328         /************************** PRIVATE METHODS ***************************/
329
330         _button_click: function(e) {
331             if (googlemaps_debug) messages.debug("_button_click");
332             var self   = e.data;
333
334             var escaped_key = self.key_from_id($(this).parent().attr('id'), 'checkbox');
335             var info_dict = self.map_markers[escaped_key];
336             var in_set = info_dict.in_set;
337             var value = info_dict.value;
338
339             var escaped_key = self.map_markers[self.key_from_id($(this).parent().attr('id'), 'checkbox')]
340             manifold.raise_event(self.options.query_uuid, (in_set) ? SET_REMOVED : SET_ADD, value);
341         } // _button_click
342
343     });
344
345     $.plugin('GoogleMaps', GoogleMaps);
346
347 })(jQuery);