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