Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
[unfold.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 (function($){
12
13     // events that happen in the once-per-view range
14     var debug=false;
15     debug=true;
16
17     // this now should be obsolete, rather use plugin_debug in plugin.js
18     // more on a on-per-record basis
19     var debug_deep=false;
20     // debug_deep=true;
21
22     var GoogleMap = Plugin.extend({
23
24         init: function(options, element) {
25             this.classname="googlemap";
26             this._super(options, element);
27
28             /* Member variables */
29             // query status
30             this.received_all = false;
31             this.received_set = false;
32             this.in_set_backlog = [];
33
34             // we keep a couple of global hashes
35             // lat_lon --> { marker, <ul> }
36             // id --> { <li>, <input> }
37             this.by_lat_lon = {};
38             // locating checkboxes by DOM selectors might be abstruse, as we cannot safely assume 
39             // all the items will belong under the toplevel <div>
40             this.by_id = {};
41             this.by_init_id = {};
42
43             /* Events */
44             // xx somehow non of these triggers at all for now
45             this.elmt().on('show', this, this.on_show);
46             this.elmt().on('shown.bs.tab', this, this.on_show);
47             this.elmt().on('resize', this, this.on_resize);
48
49             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
50             this.object = query.object;
51
52             // see querytable.js for an explanation
53             var keys = manifold.metadata.get_key(this.object);
54             this.canonical_key = (keys && keys.length == 1) ? keys[0] : undefined;
55             // 
56             this.init_key = this.options.init_key;
57             // have init_key default to canonical_key
58             this.init_key = this.init_key || this.canonical_key;
59             // sanity check
60             if ( ! this.init_key ) messages.warning ("QueryTable : cannot find init_key");
61             if ( ! this.canonical_key ) messages.warning ("QueryTable : cannot find canonical_key");
62             if (debug) messages.debug("googlemap: canonical_key="+this.canonical_key+" init_key="+this.init_key);
63
64             //// Setup query and record handlers 
65             // this query is the one about the slice itself 
66             // event related to this query will trigger callbacks like on_new_record
67             this.listen_query(options.query_uuid);
68             // this one is the complete list of resources
69             // and will be bound to callbacks like on_all_new_record
70             this.listen_query(options.query_all_uuid, 'all');
71
72             /* GUI setup and event binding */
73             this.initialize_map();
74         }, // init
75
76         /* PLUGIN EVENTS */
77
78         on_show: function(e) {
79                 if (debug) messages.debug("googlemap.on_show");
80             var googlemap = e.data;
81             google.maps.event.trigger(googlemap.map, 'resize');
82         }, 
83         // dummy to see if this triggers at all
84         on_resize: function(e) {
85             if (debug) messages.debug("googlemap.on_resize ...");
86         }, 
87
88         /* GUI EVENTS */
89
90         /* GUI MANIPULATION */
91
92         initialize_map: function() {
93             this.markerCluster = null;
94             //create empty LatLngBounds object in order to automatically center the map on the displayed objects
95             this.bounds = new google.maps.LatLngBounds();
96             var center = new google.maps.LatLng(this.options.latitude, this.options.longitude);
97
98             console.log("GoogleMap zoom = "+this.options.zoom);
99             var myOptions = {
100                 zoom: this.options.zoom,
101                 center: center,
102                         scrollwheel: false,
103                 mapTypeId: google.maps.MapTypeId.ROADMAP,
104             }
105             
106             var domid = this.options.plugin_uuid + '--' + 'googlemap';
107             var elmt = document.getElementById(domid);
108             this.map = new google.maps.Map(elmt, myOptions);
109             this.infowindow = new google.maps.InfoWindow();
110         }, // initialize_map
111
112         // return { marker: gmap_marker, ul : <ul DOM> }
113         create_marker_struct: function (object,lat,lon) {
114             // the DOM fragment
115             var dom = $("<p>").addClass("geo").append(object+"(s)");
116             var ul = $("<ul>").addClass("geo");
117             dom.append(ul);
118             // add a gmap marker to the mix
119             var marker = new google.maps.Marker({
120                 position: new google.maps.LatLng(lat, lon),
121                 title: object,
122                 // gmap can deal with a DOM element but not a jquery object
123                 content: dom.get(0),
124         }); 
125         //extend the bounds to include each marker's position
126         this.bounds.extend(marker.position);
127             return {marker:marker, ul:ul};
128         },
129
130         // given an input <ul> element, this method inserts a <li> with embedded checkbox 
131         // for displaying/selecting the resource corresponding to the input record
132         // returns the created <input> element for further checkbox manipulation
133         create_record_checkbox: function (record,ul,checked) {
134             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
135             var id=record[this.canonical_key];
136             var init_id=record[this.init_key];
137             // xxx use init_key to find out label - or should we explicitly accept an incoming label_key ?
138             var label=init_id;
139             ul.append($("<li>").addClass("geo").append(checkbox).
140                       append($("<span>").addClass("geo").append(label)));
141             // hash by id and by init_id 
142             this.by_id[id]=checkbox;
143             this.by_init_id[init_id] = checkbox;
144             //
145             // the callback for when a user clicks
146             // NOTE: this will *not* be called for changes done by program
147             var self=this;
148             checkbox.change( function (e) {
149                 manifold.raise_event (self.options.query_uuid, this.checked ? SET_ADD : SET_REMOVED, id);
150             });
151             return checkbox;
152         },
153             
154         warning: function (record,message) {
155             try {messages.warning (message+" -- "+this.key+"="+record[this.key]); }
156             catch (err) {messages.warning (message); }
157         },
158             
159         // retrieve DOM checkbox and make sure it is checked/unchecked
160         set_checkbox_from_record: function(record, checked) {
161             var init_id=record[this.init_key];
162             var checkbox = this.by_init_id [ init_id ];
163             if (checkbox) checkbox.prop('checked',checked);
164             else this.warning(record, "googlemap.set_checkbox_from_record - not found "+init_id);
165         }, 
166
167         set_checkbox_from_data: function(id, checked) {
168             var checkbox = this.by_id [ id ];
169             if (checkbox) checkbox.prop('checked',checked);
170             else messages.warning("googlemap.set_checkbox_from_data - id not found "+id);
171         }, 
172
173         // this record is *in* the slice
174         new_record: function(record) {
175             if (debug_deep) messages.debug ("googlemap.new_record");
176             if (!(record['latitude'])) return false;
177             
178             // get the coordinates
179             var latitude=unfold.get_value(record['latitude']);
180             var longitude=unfold.get_value(record['longitude']);
181             var lat_lon = latitude + longitude;
182
183             // check if we've seen anything at that place already
184             // xxx might make sense to allow for some fuzziness, 
185             // i.e. consider 2 places equal if not further away than 300m or so...
186             var marker_s = this.by_lat_lon [lat_lon];
187             if ( marker_s == null ) {
188                 marker_s = this.create_marker_struct (this.object, latitude, longitude);
189                 this.by_lat_lon [ lat_lon ] = marker_s;
190                 this.arm_marker(marker_s.marker, this.map);
191             }
192             
193             // now add a line for this resource in the marker
194             // xxx should compute checked here ?
195             // this is where the checkbox will be appended
196             var ul=marker_s.ul;
197             var checkbox = this.create_record_checkbox (record, ul, false);
198         }, // new_record
199
200         arm_marker: function(marker, map) {
201             if (debug_deep) messages.debug ("arm_marker content="+marker.content);
202             var googlemap = this;
203             google.maps.event.addListener(marker, 'click', function () {
204                 googlemap.infowindow.close();
205                 googlemap.infowindow.setContent(marker.content);
206                 googlemap.infowindow.open(map, marker);
207             });
208         }, // arm_marker
209
210         /*************************** QUERY HANDLER ****************************/
211
212         /*************************** RECORD HANDLER ***************************/
213         on_new_record: function(record) {
214             if (debug_deep) messages.debug("googlemap.on_new_record");
215             if (this.received_all)
216                 // update checkbox for record
217                 this.set_checkbox_from_record(record, true);
218             else
219                 // store for later update of checkboxes
220                 this.in_set_backlog.push(record);
221         },
222
223         on_clear_records: function(record) {
224             if (debug_deep) messages.debug("googlemap.on_clear_records");
225         },
226
227         // Could be the default in parent
228         on_query_in_progress: function() {
229             if (debug) messages.debug("googlemap.on_query_in_progress (spinning)");
230             this.spin();
231         },
232
233         on_query_done: function() {
234                 if (debug) messages.debug("googlemap.on_query_done");       
235             if (this.received_all) {
236                 this.unspin();
237                 }
238             this.received_set = true;
239         },
240
241         on_field_state_changed: function(data) {
242             if (debug_deep) messages.debug("googlemap.on_field_state_changed");     
243             switch(data.request) {
244             case FIELD_REQUEST_ADD:
245             case FIELD_REQUEST_ADD_RESET:
246                 this.set_checkbox_from_data(data.value, true);
247                 break;
248             case FIELD_REQUEST_REMOVE:
249             case FIELD_REQUEST_REMOVE_RESET:
250                 this.set_checkbox_from_data(data.value, false);
251                 break;
252             default:
253                 break;
254             }
255         },
256
257
258         // all : this 
259
260         on_all_new_record: function(record) {
261             if (debug_deep) messages.debug("googlemap.on_all_new_record");
262             this.new_record(record);
263         },
264
265         on_all_clear_records: function() {
266             if (debug) messages.debug("googlemap.on_all_clear_records");            
267         },
268
269         on_all_query_in_progress: function() {
270             if (debug) messages.debug("googlemap.on_all_query_in_progress (spinning)");
271             // XXX parent
272             this.spin();
273         },
274
275         on_all_query_done: function() {
276             if (debug) messages.debug("googlemap.on_all_query_done");
277
278             // MarkerClusterer
279             var markers = [];
280             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
281             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
282             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
283                 var cluster_markers = cluster.getMarkers();
284                 var bounds  = new google.maps.LatLngBounds();
285                 $.each(cluster_markers, function(i, marker){
286                     bounds.extend(marker.getPosition()); 
287                 });
288                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
289                 this.map.fitBounds(bounds);
290             });
291             //now fit the map to the bounds
292             this.map.fitBounds(this.bounds);
293             // Fix the zoom of fitBounds function, it's too close when there is only 1 marker
294             if(markers.length==1){
295                 this.map.setZoom(this.map.getZoom()-4);
296             }
297             var googlemap = this;
298             if (this.received_set) {
299                 /* ... and check the ones specified in the resource list */
300                 $.each(this.in_set_backlog, function(i, record) {
301                     googlemap.set_checkbox_from_record(record, true);
302                 });
303                 // reset 
304                 googlemap.in_set_backlog = [];
305                 this.unspin();
306             }
307             this.received_all = true;
308
309         } // on_all_query_done
310     });
311         /************************** PRIVATE METHODS ***************************/
312
313     $.plugin('GoogleMap', GoogleMap);
314
315 })(jQuery);