(wip)
[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 // events that happen in the once-per-view range
12 googlemap_debug=false;
13 // more on a on-per-record basis
14 googlemap_debug_detailed=false;
15
16 (function($){
17
18     var GoogleMap = Plugin.extend({
19
20         init: function(options, element) {
21             this._super(options, element);
22
23             /* Member variables */
24             // query status
25             this.received_all = false;
26             this.received_set = false;
27             this.in_set_backlog = [];
28
29             // we keep a couple of global hashes
30             // lat_lon --> { marker, <ul> }
31             // hrn --> { <li>, <input> }
32             this.by_lat_lon = {};
33             this.by_hrn = {};
34
35             /* XXX Events */
36             this.elmt().on('show', this, this.on_show);
37             // TODO in destructor
38             // $(window).unbind('QueryTable');
39
40             var query = manifold.query_store.find_analyzed_query(this.options.query_uuid);
41             this.object = query.object;
42
43             var keys = manifold.metadata.get_key(this.object);
44             // 
45             this.key = (keys && keys.length == 1) ? keys[0] : null;
46
47             //// Setup query and record handlers 
48             // this query is the one about the slice itself 
49             // event related to this query will trigger callbacks like on_new_record
50             this.listen_query(options.query_uuid);
51             // this one is the complete list of resources
52             // and will be bound to callbacks like on_all_new_record
53             this.listen_query(options.query_all_uuid, 'all');
54
55             /* GUI setup and event binding */
56             this.initialize_map();
57         }, // init
58
59         /* PLUGIN EVENTS */
60
61         on_show: function(e) {
62             if (googlemap_debug) messages.debug("googlemap.on_show");
63             var googlemap = e.data;
64             google.maps.event.trigger(googlemap.map, 'resize');
65         }, // on_show
66
67         /* GUI EVENTS */
68
69         /* GUI MANIPULATION */
70
71         initialize_map: function() {
72             this.markerCluster = null;
73
74             var center = new google.maps.LatLng(this.options.latitude, this.options.longitude);
75             var myOptions = {
76                 zoom: this.options.zoom,
77                 center: center,
78                 scrollwheel: false,
79                 mapTypeId: google.maps.MapTypeId.ROADMAP,
80             }
81             
82             var domid = this.options.plugin_uuid + '--' + 'googlemap';
83             var elmt = document.getElementById(domid);
84             if (googlemap_debug) messages.debug("gmap.initialize_map based on  domid=" + domid + " elmt=" + elmt);
85             this.map = new google.maps.Map(elmt, myOptions);
86             this.infowindow = new google.maps.InfoWindow();
87         }, // initialize_map
88
89         // xxx probably not the right place
90         // The function accepts both records and their key 
91         record_hrn : function (record) {
92             var key_value;
93             switch (manifold.get_type(record)) {
94             case TYPE_VALUE:
95                 key_value = record;
96                 break;
97             case TYPE_RECORD:
98                 if ( ! this.key in record ) return;
99                 key_value = record[this.key];
100                 break;
101             default:
102                 throw "Not implemented";
103                 break;
104             }
105             // XXX BACKSLASHES original code was reading like this
106             //return this.escape_id(key_value).replace(/\\/g, '');
107             //  however this sequence removes backslashes from hrn's and as a result
108             // queryupdater was getting all mixed up
109             // querytable does publish hrn's with backslashes and that seems like the thing to do
110             return key_value;
111         },            
112
113         // return { marker: gmap_marker, ul : <ul DOM> }
114         create_marker_struct: function (object,lat,lon) {
115             // the DOM fragment
116             var dom = $("<p>").addClass("geo").append(object+"(s)");
117             var ul = $("<ul>").addClass("geo");
118             dom.append(ul);
119             // add a gmap marker to the mix
120             var marker = new google.maps.Marker({
121                 position: new google.maps.LatLng(lat, lon),
122                 title: object,
123                 // gmap can deal with a DOM element but not a jquery object
124                 content: dom.get(0),
125             }); 
126             return {marker:marker, ul:ul};
127         },
128
129         // add an entry in the marker <ul> tag for that record
130         // returns { checkbox : <input DOM> }
131         create_record_checkbox: function (record,ul,checked) {
132             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
133             var hrn=this.record_hrn(record);
134             ul.append($("<li>").addClass("geo").append(checkbox).
135                       append($("<span>").addClass("geo").append(hrn)));
136             var googlemap=this;
137             // the callback for when a user clicks
138             // NOTE: this will *not* be called for changes done by program
139             checkbox.change( function (e) {
140                 if (googlemap_debug) messages.debug("googlemap click handler checked= " + this.checked + " hrn=" + hrn);
141                 manifold.raise_event (googlemap.options.query_uuid, 
142                                       this.checked ? SET_ADD : SET_REMOVED, hrn);
143             });
144             return checkbox;
145         },
146             
147         // retrieve DOM checkbox and make sure it is checked/unchecked
148         set_checkbox: function(record, checked) {
149             var hrn=this.record_hrn (record);
150             if (! hrn) { 
151                 try {messages.warning ("googlemap.set_checkbox: record has no hrn -- hostname="+record.hostname); }
152                 catch (err) {messages.warning ("googlemap.set_checkbox: record has no hrn"); }
153                 return; 
154             }
155             var checkbox_s = this.by_hrn [ hrn ];
156             if (! checkbox_s ) { messages.warning ("googlemap.set_checkbox: could not spot checkbox for hrn "+hrn); return; }
157             checkbox_s.checkbox.prop('checked',checked);
158         }, // set_checkbox
159
160         // this record is *in* the slice
161         new_record: function(record) {
162                 if (googlemap_debug_detailed) messages.debug ("new_record");
163             if (!(record['latitude'])) return false;
164             
165             // get the coordinates
166             var latitude=unfold.get_value(record['latitude']);
167             var longitude=unfold.get_value(record['longitude']);
168             var lat_lon = latitude + longitude;
169
170                 // check if we've seen anything at that place already
171                 // xxx might make sense to allow for some fuzziness, 
172                 // i.e. consider 2 places equal if not further away than 300m or so...
173                 var marker_s = this.by_lat_lon [lat_lon];
174                 if ( marker_s == null ) {
175                         marker_s = this.create_marker_struct (this.object, latitude, longitude);
176                         this.by_lat_lon [ lat_lon ] = marker_s;
177                         this.arm_marker(marker_s.marker, this.map);
178                 }
179             
180                 // now add a line for this resource in the marker
181                 // xxx should compute checked here ?
182                 // this is where the checkbox will be appended
183                 var ul=marker_s.ul;
184                 var checkbox = this.create_record_checkbox (record, ul, false);
185                 if ( ! this.key in record ) return;
186             var key_value = record[this.key];
187                 // see XXX BACKSLASHES 
188                 //var hrn = this.escape_id(key_value).replace(/\\/g, '');
189                 var hrn = key_value;
190             this.by_hrn[hrn] = {
191                         checkbox: checkbox,
192                         // xxx Thierry sept 2013
193                         // xxx actually we might have just used a domid-based scheme instead of the hash
194                         // since at this point we only need to retrieve the checkbox from an hrn
195                         // but I was not sure enough that extra needs would not show up so I kept this in place
196                         // xxx not sure these are actually useful :
197                 value: key_value,
198                 record: record,
199             }
200         }, // new_record
201
202         arm_marker: function(marker, map) {
203             if (googlemap_debug_detailed) messages.debug ("arm_marker content="+marker.content);
204             var googlemap = this;
205             google.maps.event.addListener(marker, 'click', function () {
206                 googlemap.infowindow.close();
207                 googlemap.infowindow.setContent(marker.content);
208                 googlemap.infowindow.open(map, marker);
209             });
210         }, // arm_marker
211
212         /*************************** QUERY HANDLER ****************************/
213
214         /*************************** RECORD HANDLER ***************************/
215         on_new_record: function(record) {
216             if (googlemap_debug_detailed) messages.debug("on_new_record");
217             if (this.received_all)
218                 // update checkbox for record
219                 this.set_checkbox(record, true);
220             else
221                 // store for later update of checkboxes
222                 this.in_set_backlog.push(record);
223         },
224
225         on_clear_records: function(record) {
226             if (googlemap_debug_detailed) messages.debug("on_clear_records");
227         },
228
229         // Could be the default in parent
230         on_query_in_progress: function() {
231             if (googlemap_debug) messages.debug("on_query_in_progress (spinning)");
232             this.spin();
233         },
234
235         on_query_done: function() {
236             if (googlemap_debug) messages.debug("on_query_done");            
237             if (this.received_all) {
238                 this.unspin();
239             }
240             this.received_set = true;
241         },
242
243         on_field_state_changed: function(data) {
244             if (googlemap_debug_detailed) messages.debug("on_field_state_changed");            
245             switch(data.request) {
246             case FIELD_REQUEST_ADD:
247             case FIELD_REQUEST_ADD_RESET:
248                 this.set_checkbox(data.value, true);
249                 break;
250             case FIELD_REQUEST_REMOVE:
251             case FIELD_REQUEST_REMOVE_RESET:
252                 this.set_checkbox(data.value, false);
253                 break;
254             default:
255                 break;
256             }
257         },
258
259
260         // all : this 
261
262         on_all_new_record: function(record) {
263             if (googlemap_debug_detailed) messages.debug("on_all_new_record");
264             this.new_record(record);
265         },
266
267         on_all_clear_records: function() {
268             if (googlemap_debug) messages.debug("on_all_clear_records");            
269         },
270
271         on_all_query_in_progress: function() {
272             if (googlemap_debug) messages.debug("on_all_query_in_progress (spinning)");
273             // XXX parent
274             this.spin();
275         },
276
277         on_all_query_done: function() {
278             if (googlemap_debug) messages.debug("on_all_query_done");
279
280             // MarkerClusterer
281             var markers = [];
282             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
283             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
284             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
285                 var cluster_markers = cluster.getMarkers();
286                 var bounds  = new google.maps.LatLngBounds();
287                 $.each(cluster_markers, function(i, marker){
288                     bounds.extend(marker.getPosition()); 
289                 });
290                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
291                 this.map.fitBounds(bounds);
292             });
293
294             var googlemap = this;
295             if (this.received_set) {
296                 /* ... and check the ones specified in the resource list */
297                 $.each(this.in_set_backlog, function(i, record) {
298                     googlemap.set_checkbox(record, true);
299                 });
300                 // reset 
301                 googlemap.in_set_backlog = [];
302
303                 if (googlemap_debug) messages.debug("unspinning");
304                 this.unspin();
305             }
306             this.received_all = true;
307
308         } // on_all_query_done
309     });
310         /************************** PRIVATE METHODS ***************************/
311
312     $.plugin('GoogleMap', GoogleMap);
313
314 })(jQuery);