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