8501c7410b8fe1ba9811863c14b442da71718fd3
[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                 mapTypeId: google.maps.MapTypeId.ROADMAP,
79             }
80             
81             var domid = this.options.plugin_uuid + '--' + 'googlemap';
82             var elmt = document.getElementById(domid);
83             if (googlemap_debug) messages.debug("gmap.initialize_map based on  domid=" + domid + " elmt=" + elmt);
84             this.map = new google.maps.Map(elmt, myOptions);
85             this.infowindow = new google.maps.InfoWindow();
86         }, // initialize_map
87
88         // xxx probably not the right place
89         // The function accepts both records and their key 
90         record_hrn : function (record) {
91             var key_value;
92             switch (manifold.get_type(record)) {
93             case TYPE_VALUE:
94                 key_value = record;
95                 break;
96             case TYPE_RECORD:
97                 if ( ! this.key in record ) return;
98                 key_value = record[this.key];
99                 break;
100             default:
101                 throw "Not implemented";
102                 break;
103             }
104             // XXX BACKSLASHES original code was reading like this
105             //return this.escape_id(key_value).replace(/\\/g, '');
106             //  however this sequence removes backslashes from hrn's and as a result
107             // queryupdater was getting all mixed up
108             // querytable does publish hrn's with backslashes and that seems like the thing to do
109             return key_value;
110         },          
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             return {marker:marker, ul:ul};
126         },
127
128         // add an entry in the marker <ul> tag for that record
129         // returns { checkbox : <input DOM> }
130         create_record_checkbox: function (record,ul,checked) {
131             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
132             var hrn=this.record_hrn(record);
133             ul.append($("<li>").addClass("geo").append(checkbox).
134                       append($("<span>").addClass("geo").append(hrn)));
135             var googlemap=this;
136             // the callback for when a user clicks
137             // NOTE: this will *not* be called for changes done by program
138             checkbox.change( function (e) {
139                 if (googlemap_debug) messages.debug("googlemap click handler checked= " + this.checked + " hrn=" + hrn);
140                 manifold.raise_event (googlemap.options.query_uuid, 
141                                       this.checked ? SET_ADD : SET_REMOVED, hrn);
142             });
143             return checkbox;
144         },
145             
146         // retrieve DOM checkbox and make sure it is checked/unchecked
147         set_checkbox: function(record, checked) {
148             var hrn=this.record_hrn (record);
149             if (! hrn) { 
150                 try {messages.warning ("googlemap.set_checkbox: record has no hrn -- hostname="+record.hostname); }
151                 catch (err) {messages.warning ("googlemap.set_checkbox: record has no hrn"); }
152                 return; 
153             }
154             var checkbox_s = this.by_hrn [ hrn ];
155             if (! checkbox_s ) { messages.warning ("googlemap.set_checkbox: could not spot checkbox for hrn "+hrn); return; }
156             checkbox_s.checkbox.prop('checked',checked);
157         }, // set_checkbox
158
159         // this record is *in* the slice
160         new_record: function(record) {
161                 if (googlemap_debug_detailed) messages.debug ("new_record");
162             if (!(record['latitude'])) return false;
163             
164             // get the coordinates
165             var latitude=unfold.get_value(record['latitude']);
166             var longitude=unfold.get_value(record['longitude']);
167             var lat_lon = latitude + longitude;
168
169             // check if we've seen anything at that place already
170             // xxx might make sense to allow for some fuzziness, 
171             // i.e. consider 2 places equal if not further away than 300m or so...
172             var marker_s = this.by_lat_lon [lat_lon];
173             if ( marker_s == null ) {
174                         marker_s = this.create_marker_struct (this.object, latitude, longitude);
175                         this.by_lat_lon [ lat_lon ] = marker_s;
176                         this.arm_marker(marker_s.marker, this.map);
177                 }
178             
179             // now add a line for this resource in the marker
180             // xxx should compute checked here ?
181             // this is where the checkbox will be appended
182             var ul=marker_s.ul;
183             var checkbox = this.create_record_checkbox (record, ul, false);
184             if ( ! this.key in record ) return;
185             var key_value = record[this.key];
186             // see XXX BACKSLASHES 
187             //var hrn = this.escape_id(key_value).replace(/\\/g, '');
188             var hrn = key_value;
189             this.by_hrn[hrn] = {
190                     checkbox: checkbox,
191                         // xxx Thierry sept 2013
192                         // xxx actually we might have just used a domid-based scheme instead of the hash
193                         // since at this point we only need to retrieve the checkbox from an hrn
194                         // but I was not sure enough that extra needs would not show up so I kept this in place
195                         // xxx not sure these are actually useful :
196                 value: key_value,
197                 record: record,
198             }
199         }, // new_record
200
201         arm_marker: function(marker, map) {
202             if (googlemap_debug_detailed) messages.debug ("arm_marker content="+marker.content);
203             var googlemap = this;
204             google.maps.event.addListener(marker, 'click', function () {
205                 googlemap.infowindow.close();
206                 googlemap.infowindow.setContent(marker.content);
207                 googlemap.infowindow.open(map, marker);
208             });
209         }, // arm_marker
210
211         /*************************** QUERY HANDLER ****************************/
212
213         /*************************** RECORD HANDLER ***************************/
214         on_new_record: function(record) {
215             if (googlemap_debug_detailed) messages.debug("on_new_record");
216             if (this.received_all)
217                 // update checkbox for record
218                 this.set_checkbox(record, true);
219             else
220                 // store for later update of checkboxes
221                 this.in_set_backlog.push(record);
222         },
223
224         on_clear_records: function(record) {
225             if (googlemap_debug_detailed) messages.debug("on_clear_records");
226         },
227
228         // Could be the default in parent
229         on_query_in_progress: function() {
230             if (googlemap_debug) messages.debug("on_query_in_progress (spinning)");
231             this.spin();
232         },
233
234         on_query_done: function() {
235             if (googlemap_debug) messages.debug("on_query_done");           
236             if (this.received_all) {
237                 this.unspin();
238             }
239             this.received_set = true;
240         },
241
242         on_field_state_changed: function(data) {
243             if (googlemap_debug_detailed) messages.debug("on_field_state_changed");         
244             switch(data.request) {
245             case FIELD_REQUEST_ADD:
246             case FIELD_REQUEST_ADD_RESET:
247                 this.set_checkbox(data.value, true);
248                 break;
249             case FIELD_REQUEST_REMOVE:
250             case FIELD_REQUEST_REMOVE_RESET:
251                 this.set_checkbox(data.value, false);
252                 break;
253             default:
254                 break;
255             }
256         },
257
258
259         // all : this 
260
261         on_all_new_record: function(record) {
262             if (googlemap_debug_detailed) messages.debug("on_all_new_record");
263             this.new_record(record);
264         },
265
266         on_all_clear_records: function() {
267             if (googlemap_debug) messages.debug("on_all_clear_records");            
268         },
269
270         on_all_query_in_progress: function() {
271             if (googlemap_debug) messages.debug("on_all_query_in_progress (spinning)");
272             // XXX parent
273             this.spin();
274         },
275
276         on_all_query_done: function() {
277             if (googlemap_debug) messages.debug("on_all_query_done");
278
279             // MarkerClusterer
280             var markers = [];
281             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
282             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
283             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
284                 var cluster_markers = cluster.getMarkers();
285                 var bounds  = new google.maps.LatLngBounds();
286                 $.each(cluster_markers, function(i, marker){
287                     bounds.extend(marker.getPosition()); 
288                 });
289                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
290                 this.map.fitBounds(bounds);
291             });
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(record, true);
298                 });
299                 // reset 
300                 googlemap.in_set_backlog = [];
301
302                 if (googlemap_debug) messages.debug("unspinning");
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);