5a15a3d8e605471ab4eada8d8335e37902916a06
[myslice.git] / plugins / googlemap / static / js / googlemap.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 GOOGLEMAP_BGCOLOR_RESET   = 0;
12 GOOGLEMAP_BGCOLOR_ADDED   = 1;
13 GOOGLEMAP_BGCOLOR_REMOVED = 2;
14
15 (function($){
16
17     // events that happen in the once-per-view range
18     var debug=false;
19     debug=true;
20
21     // this now should be obsolete, rather use plugin_debug in plugin.js
22     // more on a on-per-record basis
23     var debug_deep=false;
24     // debug_deep=true;
25
26     var GoogleMap = Plugin.extend({
27
28         /**************************************************************************
29          *                          CONSTRUCTOR
30          **************************************************************************/
31
32         init: function(options, element) 
33         {
34             this._super(options, element);
35
36             /* Member variables */
37
38             /* we keep a couple of global hashes
39              * lat_lon --> { marker, <ul> }
40              * id --> { <li>, <input> }
41              */
42             this.by_lat_lon = {};
43             /* locating checkboxes by DOM selectors might be abstruse, as we cannot safely assume 
44              * all the items will belong under the toplevel <div>
45              */
46             this.by_id = {};
47             this.by_init_id = {};
48
49             this.markers = Array();
50
51             /* Events */
52             this.elmt().on('show', this, this.on_show);
53             this.elmt().on('shown.bs.tab', this, this.on_show);
54             this.elmt().on('resize', this, this.on_resize);
55
56             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
57             this.object = query.object;
58
59             /* see querytable.js for an explanation */
60             var keys = manifold.metadata.get_key(this.object);
61             this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
62             this.init_key = this.options.init_key;
63             this.init_key = this.init_key || this.canonical_key;
64
65             /* sanity check */
66             if ( ! this.init_key ) 
67                 messages.warning ("QueryTable : cannot find init_key");
68             if ( ! this.canonical_key )
69                 messages.warning ("QueryTable : cannot find canonical_key");
70             if (debug)
71                 messages.debug("googlemap: canonical_key="+this.canonical_key+" init_key="+this.init_key);
72
73             this.listen_query(options.query_uuid);
74
75             /* GUI setup and event binding */
76             this.initialize_map();
77
78         }, // init
79
80         /**************************************************************************
81          *                         PLUGIN EVENTS
82          **************************************************************************/
83
84         on_show: function(e) {
85                 if (debug) messages.debug("googlemap.on_show");
86             var googlemap = e.data;
87             google.maps.event.trigger(googlemap.map, 'resize');
88         }, 
89
90         /**************************************************************************
91          *                        GUI MANIPULATION
92          **************************************************************************/
93
94         initialize_map: function() 
95         {
96             this.markerCluster = null;
97             //create empty LatLngBounds object in order to automatically center the map on the displayed objects
98             this.bounds = new google.maps.LatLngBounds();
99             var center = new google.maps.LatLng(this.options.latitude, this.options.longitude);
100
101             var myOptions = {
102                 zoom: this.options.zoom,
103                 center: center,
104                         scrollwheel: false,
105                 mapTypeId: google.maps.MapTypeId.ROADMAP,
106             }
107             
108             var domid = this.id('googlemap');
109                 var elmt = document.getElementById(domid);
110             this.map = new google.maps.Map(elmt, myOptions);
111             this.infowindow = new google.maps.InfoWindow();
112
113         }, // initialize_map
114
115         // return { marker: gmap_marker, ul : <ul DOM> }
116         create_marker_struct: function(object, lat, lon) 
117         {
118             /* the DOM fragment */
119             var dom = $("<p>").addClass("geo").append(object+"(s)");
120             var ul = $("<ul>").addClass("geo");
121             dom.append(ul);
122             /* add a gmap marker to the mix */
123             var marker = new google.maps.Marker({
124                 position: new google.maps.LatLng(lat, lon),
125                 title: object,
126                 /* gmap can deal with a DOM element but not a jquery object */
127                 content: dom.get(0),
128                 keys: Array(),
129             }); 
130             //extend the bounds to include each marker's position
131             this.bounds.extend(marker.position);
132             return { marker: marker, ul: ul };
133         },
134
135         /* given an input <ul> element, this method inserts a <li> with embedded checkbox 
136          * for displaying/selecting the resource corresponding to the input record
137          * returns the created <input> element for further checkbox manipulation
138          */
139         create_record_checkbox: function (record, ul, checked)
140         {
141             var key, key_value, data;
142
143             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
144             var id = record[this.canonical_key];
145             var init_id = record[this.init_key];
146
147             // xxx use init_key to find out label - or should we explicitly accept an incoming label_key ?
148             var label = init_id;
149
150             key = this.canonical_key;
151             key_value = manifold.record_get_value(record, key);
152
153             ul.append($("<li>").addClass("geo")
154               .append($('<div>') // .addId(this.id_from_key(key, key_value))
155                 .append(checkbox)
156                 .append($("<span>").addClass("geo")
157                   .append(label)
158                 )
159               )
160             );
161
162             // XXX STATE / BACKGROUND
163
164             // hash by id and by init_id 
165             this.by_id[id]=checkbox;
166             this.by_init_id[init_id] = checkbox;
167
168             /* the callback for when a user clicks
169              * NOTE: this will *not* be called for changes done by program
170              */
171             var self=this;
172             checkbox.change( function (e) {
173                 data = {
174                     state: STATE_SET,
175                     key  : null,
176                     op   : this.checked ? SET_ADD : SET_REMOVED,
177                     value: id
178                 }
179                 manifold.raise_event(self.options.query_uuid, FIELD_STATE_CHANGED, data);
180             });
181             return checkbox;
182         },
183             
184         set_checkbox_from_record_key: function (record_key, checked) 
185         {
186             if (checked === undefined) checked = true;
187
188             var checkbox = this.by_init_id [record_key];
189             if (!checkbox) {
190                 console.log("googlemap.set_checkbox_from_record - not found " + record_key);
191                 return;
192             }
193
194             checkbox.attr('checked', checked);
195         },
196
197
198         set_checkbox_from_data: function(id, checked) 
199         {
200             var checkbox = this.by_id[id];
201             if (!checkbox) {
202                 console.log("googlemap.set_checkbox_from_data - id not found " + id);
203                 return;
204             }
205             checkbox.attr('checked', checked);
206         }, 
207
208         set_bgcolor: function(key_value, class_name)
209         {
210             var elt = $(document.getElementById(this.id_from_key(this.canonical_key, key_value)))
211             if (class_name == GOOGLEMAP_BGCOLOR_RESET)
212                 elt.removeClass('added removed');
213             else
214                 elt.addClass((class_name == GOOGLEMAP_BGCOLOR_ADDED ? 'added' : 'removed'));
215         },
216
217
218         /**
219          * Populates both this.by_lat_lon and this.arm_marker arrays
220          */
221         new_record: function(record) 
222         {
223             var record_key;
224
225             if (!(record['latitude'])) 
226                 return;
227
228             /* get the coordinates*/
229             var latitude  = unfold.get_value(record['latitude']);
230             var longitude = unfold.get_value(record['longitude']);
231             var lat_lon = latitude + longitude;
232
233             // check if we've seen anything at that place already
234             // xxx might make sense to allow for some fuzziness, 
235             // i.e. consider 2 places equal if not further away than 300m or so...
236             var marker_s = this.by_lat_lon[lat_lon];
237             if ( marker_s == null ) {
238                     marker_s = this.create_marker_struct(this.object, latitude, longitude);
239                     this.by_lat_lon[lat_lon] = marker_s;
240                     this.arm_marker(marker_s.marker, this.map);
241                 }
242
243             /* Add key to the marker */
244             record_key = manifold.record_get_value(record, this.canonical_key);
245             marker_s.marker.keys.push(record_key);
246             
247             // now add a line for this resource in the marker
248             // xxx should compute checked here ?
249             // this is where the checkbox will be appended
250             var ul = marker_s.ul;
251             var checkbox = this.create_record_checkbox(record, ul, false);
252         }, // new_record
253
254         arm_marker: function(marker, map)
255         {
256             var self = this;
257             google.maps.event.addListener(marker, 'click', function () {
258                 self.infowindow.close();
259                 self.infowindow.setContent(marker.content);
260                 self.infowindow.open(map, marker);
261             });
262         }, // arm_marker
263
264         clear_map: function()
265         {
266             /* XXX */
267         },
268
269         filter_map: function()
270         {
271             var self = this;
272             var visible;
273
274             /* Loop on every marker and sets it visible */
275             $.each(this.markers, function(i, marker) {
276                 /* For a marker to be visible, at least one of its keys has to
277                  * be visible */
278                 visible = false;
279                 $.each(marker.keys, function(j, key) {
280                     visible = visible || manifold.query_store.get_record_state(self.options.query_uuid, key, STATE_VISIBLE);
281                 });
282                 marker.setVisible(visible);
283             });
284
285             this.do_clustering();
286         },
287
288         do_clustering: function()
289         {
290             this.markerCluster = new MarkerClusterer(this.map, this.markers, {zoomOnClick: false});
291             this.markerCluster.setIgnoreHidden(true);
292             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
293                 var cluster_markers = cluster.getMarkers();
294                 var bounds  = new google.maps.LatLngBounds();
295                 $.each(cluster_markers, function(i, marker){
296                     bounds.extend(marker.getPosition()); 
297                 });
298                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
299                 this.map.fitBounds(bounds);
300             });
301             //now fit the map to the bounds
302             this.map.fitBounds(this.bounds);
303             // Fix the zoom of fitBounds function, it's too close when there is only 1 marker
304             if (this.markers.length==1) {
305                 this.map.setZoom(this.map.getZoom()-4);
306             }
307         },
308
309         redraw_map: function()
310         {
311             // Let's clear the table and only add lines that are visible
312             var self = this;
313             this.clear_map();
314
315             /* Add records to internal hash structure */
316             var record_keys = [];
317             manifold.query_store.iter_records(this.options.query_uuid, function (record_key, record) {
318                 self.new_record(record);
319                 record_keys.push(record_key);
320             });
321
322             /* Add markers to cluster */
323             this.markers = Array();
324             $.each(this.by_lat_lon, function (k, s) {
325                 self.markers.push(s.marker); 
326             });
327
328             this.do_clustering();
329
330
331             /* Set checkbox and background color */
332             $.each(record_keys, function(i, record_key) {
333                 var state = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_SET);
334                 var warnings = manifold.query_store.get_record_state(self.options.query_uuid, record_key, STATE_WARNINGS);
335                 switch(state) {
336                     // XXX The row and checkbox still does not exists !!!!
337                     case STATE_SET_IN:
338                     case STATE_SET_IN_SUCCESS:
339                     case STATE_SET_OUT_FAILURE:
340                         self.set_checkbox_from_record_key(record_key, true);
341                         break;
342                     case STATE_SET_OUT:
343                     case STATE_SET_OUT_SUCCESS:
344                     case STATE_SET_IN_FAILURE:
345                         break;
346                     case STATE_SET_IN_PENDING:
347                         self.set_checkbox_from_record_key(record_key, true);
348                         self.set_bgcolor(record_key, GOOGLEMAP_BGCOLOR_ADDED);
349                         break;
350                     case STATE_SET_OUT_PENDING:
351                         self.set_bgcolor(record_key, GOOGLEMAP_BGCOLOR_REMOVED);
352                         break;
353                 }
354                 //self.change_status(record_key, warnings); // XXX will retrieve status again
355             });
356         },
357
358        /**************************************************************************
359         *                           QUERY HANDLERS
360         **************************************************************************/ 
361
362         on_filter_added: function(filter)
363         {
364             this.filter_map();
365         },
366
367         on_filter_removed: function(filter)
368         {
369             this.filter_map();
370         },
371         
372         on_filter_clear: function()
373         {
374             this.filter_map();
375         },
376
377         on_query_in_progress: function() 
378         {
379             this.spin();
380         },
381
382         on_query_done: function()
383         {
384             this.redraw_map();
385             this.unspin();
386         },
387
388         on_field_state_changed: function(data)
389         {
390             switch(data.state) {
391                 case STATE_SET:
392                     switch(data.value) {
393                         case STATE_SET_IN:
394                         case STATE_SET_IN_SUCCESS:
395                         case STATE_SET_OUT_FAILURE:
396                             this.set_checkbox_from_data(data.key, true);
397                             this.set_bgcolor(data.key, QUERYTABLE_BGCOLOR_RESET);
398                             break;  
399                         case STATE_SET_OUT:
400                         case STATE_SET_OUT_SUCCESS:
401                         case STATE_SET_IN_FAILURE:
402                             this.set_checkbox_from_data(data.key, false);
403                             this.set_bgcolor(data.key, QUERYTABLE_BGCOLOR_RESET);
404                             break;
405                         case STATE_SET_IN_PENDING:
406                             this.set_checkbox_from_data(data.key, true);
407                             this.set_bgcolor(data.key, QUERYTABLE_BGCOLOR_ADDED);
408                             break;  
409                         case STATE_SET_OUT_PENDING:
410                             this.set_checkbox_from_data(data.key, false);
411                             this.set_bgcolor(data.key, QUERYTABLE_BGCOLOR_REMOVED);
412                             break;
413                     }
414                     break;
415
416                 case STATE_WARNINGS:
417                     //this.change_status(data.key, data.value);
418                     break;
419             }
420         },
421
422     });
423
424     $.plugin('GoogleMap', GoogleMap);
425
426 })(jQuery);