adding some tracability into the plugins code
[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 (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             var myOptions = {
98                 zoom: this.options.zoom,
99                 center: center,
100                         scrollwheel: false,
101                 mapTypeId: google.maps.MapTypeId.ROADMAP,
102             }
103             
104             var domid = this.options.plugin_uuid + '--' + 'googlemap';
105             var elmt = document.getElementById(domid);
106             this.map = new google.maps.Map(elmt, myOptions);
107             this.infowindow = new google.maps.InfoWindow();
108         }, // initialize_map
109
110         // return { marker: gmap_marker, ul : <ul DOM> }
111         create_marker_struct: function (object,lat,lon) {
112             // the DOM fragment
113             var dom = $("<p>").addClass("geo").append(object+"(s)");
114             var ul = $("<ul>").addClass("geo");
115             dom.append(ul);
116             // add a gmap marker to the mix
117             var marker = new google.maps.Marker({
118                 position: new google.maps.LatLng(lat, lon),
119                 title: object,
120                 // gmap can deal with a DOM element but not a jquery object
121                 content: dom.get(0),
122         }); 
123         //extend the bounds to include each marker's position
124         this.bounds.extend(marker.position);
125             return {marker:marker, ul:ul};
126         },
127
128         // given an input <ul> element, this method inserts a <li> with embedded checkbox 
129         // for displaying/selecting the resource corresponding to the input record
130         // returns the created <input> element for further checkbox manipulation
131         create_record_checkbox: function (record,ul,checked) {
132             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
133             var id=record[this.canonical_key];
134             var init_id=record[this.init_key];
135             // xxx use init_key to find out label - or should we explicitly accept an incoming label_key ?
136             var label=init_id;
137             ul.append($("<li>").addClass("geo").append(checkbox).
138                       append($("<span>").addClass("geo").append(label)));
139             // hash by id and by init_id 
140             this.by_id[id]=checkbox;
141             this.by_init_id[init_id] = checkbox;
142             //
143             // the callback for when a user clicks
144             // NOTE: this will *not* be called for changes done by program
145             var self=this;
146             checkbox.change( function (e) {
147                 manifold.raise_event (self.options.query_uuid, this.checked ? SET_ADD : SET_REMOVED, id);
148             });
149             return checkbox;
150         },
151             
152         warning: function (record,message) {
153             try {messages.warning (message+" -- "+this.key+"="+record[this.key]); }
154             catch (err) {messages.warning (message); }
155         },
156             
157         // retrieve DOM checkbox and make sure it is checked/unchecked
158         set_checkbox_from_record: function(record, checked) {
159             var init_id=record[this.init_key];
160             var checkbox = this.by_init_id [ init_id ];
161             if (checkbox) checkbox.prop('checked',checked);
162             else this.warning(record, "googlemap.set_checkbox_from_record - not found "+init_id);
163         }, 
164
165         set_checkbox_from_data: function(id, checked) {
166             var checkbox = this.by_id [ id ];
167             if (checkbox) checkbox.prop('checked',checked);
168             else messages.warning("googlemap.set_checkbox_from_data - id not found "+id);
169         }, 
170
171         // this record is *in* the slice
172         new_record: function(record) {
173             if (debug_deep) messages.debug ("googlemap.new_record");
174             if (!(record['latitude'])) return false;
175             
176             // get the coordinates
177             var latitude=unfold.get_value(record['latitude']);
178             var longitude=unfold.get_value(record['longitude']);
179             var lat_lon = latitude + longitude;
180
181             // check if we've seen anything at that place already
182             // xxx might make sense to allow for some fuzziness, 
183             // i.e. consider 2 places equal if not further away than 300m or so...
184             var marker_s = this.by_lat_lon [lat_lon];
185             if ( marker_s == null ) {
186                 marker_s = this.create_marker_struct (this.object, latitude, longitude);
187                 this.by_lat_lon [ lat_lon ] = marker_s;
188                 this.arm_marker(marker_s.marker, this.map);
189             }
190             
191             // now add a line for this resource in the marker
192             // xxx should compute checked here ?
193             // this is where the checkbox will be appended
194             var ul=marker_s.ul;
195             var checkbox = this.create_record_checkbox (record, ul, false);
196         }, // new_record
197
198         arm_marker: function(marker, map) {
199             if (debug_deep) messages.debug ("arm_marker content="+marker.content);
200             var googlemap = this;
201             google.maps.event.addListener(marker, 'click', function () {
202                 googlemap.infowindow.close();
203                 googlemap.infowindow.setContent(marker.content);
204                 googlemap.infowindow.open(map, marker);
205             });
206         }, // arm_marker
207
208         /*************************** QUERY HANDLER ****************************/
209
210         /*************************** RECORD HANDLER ***************************/
211         on_new_record: function(record) {
212             if (debug_deep) messages.debug("googlemap.on_new_record");
213             if (this.received_all)
214                 // update checkbox for record
215                 this.set_checkbox_from_record(record, true);
216             else
217                 // store for later update of checkboxes
218                 this.in_set_backlog.push(record);
219         },
220
221         on_clear_records: function(record) {
222             if (debug_deep) messages.debug("googlemap.on_clear_records");
223         },
224
225         // Could be the default in parent
226         on_query_in_progress: function() {
227             if (debug) messages.debug("googlemap.on_query_in_progress (spinning)");
228             this.spin();
229         },
230
231         on_query_done: function() {
232                 if (debug) messages.debug("googlemap.on_query_done");       
233             if (this.received_all) {
234                 this.unspin();
235                 }
236             this.received_set = true;
237         },
238
239         on_field_state_changed: function(data) {
240             if (debug_deep) messages.debug("googlemap.on_field_state_changed");     
241             switch(data.request) {
242             case FIELD_REQUEST_ADD:
243             case FIELD_REQUEST_ADD_RESET:
244                 this.set_checkbox_from_data(data.value, true);
245                 break;
246             case FIELD_REQUEST_REMOVE:
247             case FIELD_REQUEST_REMOVE_RESET:
248                 this.set_checkbox_from_data(data.value, false);
249                 break;
250             default:
251                 break;
252             }
253         },
254
255
256         // all : this 
257
258         on_all_new_record: function(record) {
259             if (debug_deep) messages.debug("googlemap.on_all_new_record");
260             this.new_record(record);
261         },
262
263         on_all_clear_records: function() {
264             if (debug) messages.debug("googlemap.on_all_clear_records");            
265         },
266
267         on_all_query_in_progress: function() {
268             if (debug) messages.debug("googlemap.on_all_query_in_progress (spinning)");
269             // XXX parent
270             this.spin();
271         },
272
273         on_all_query_done: function() {
274             if (debug) messages.debug("googlemap.on_all_query_done");
275
276             // MarkerClusterer
277             var markers = [];
278             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
279             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
280             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
281                 var cluster_markers = cluster.getMarkers();
282                 var bounds  = new google.maps.LatLngBounds();
283                 $.each(cluster_markers, function(i, marker){
284                     bounds.extend(marker.getPosition()); 
285                 });
286                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
287                 this.map.fitBounds(bounds);
288             });
289             //now fit the map to the bounds
290             this.map.fitBounds(this.bounds);
291             // Fix the zoom of fitBounds function, it's too close when there is only 1 marker
292             if(markers.length==1){
293                 this.map.setZoom(this.map.getZoom()-4);
294             }
295             var googlemap = this;
296             if (this.received_set) {
297                 /* ... and check the ones specified in the resource list */
298                 $.each(this.in_set_backlog, function(i, record) {
299                     googlemap.set_checkbox_from_record(record, true);
300                 });
301                 // reset 
302                 googlemap.in_set_backlog = [];
303                 this.unspin();
304             }
305             this.received_all = true;
306
307         } // on_all_query_done
308     });
309         /************************** PRIVATE METHODS ***************************/
310
311     $.plugin('GoogleMap', GoogleMap);
312
313 })(jQuery);