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