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