764f1b4959de59704fdf7a5e0a73628ff982b3df
[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_init_id [ init_id ];
155             if (checkbox) checkbox.prop('checked',checked);
156             else this.warning(record, "googlemap.set_checkbox_from_record - not found "+init_id);
157         }, 
158
159         set_checkbox_from_data: function(id, checked) {
160             var checkbox = this.by_id [ id ];
161             if (checkbox) checkbox.prop('checked',checked);
162             else messages.warning("googlemap.set_checkbox_from_data - id not found "+id);
163         }, 
164
165         // this record is *in* the slice
166         new_record: function(record) {
167             if (debug_deep) messages.debug ("googlemap.new_record");
168             if (!(record['latitude'])) return false;
169             
170             // get the coordinates
171             var latitude=unfold.get_value(record['latitude']);
172             var longitude=unfold.get_value(record['longitude']);
173             var lat_lon = latitude + longitude;
174
175             // check if we've seen anything at that place already
176             // xxx might make sense to allow for some fuzziness, 
177             // i.e. consider 2 places equal if not further away than 300m or so...
178             var marker_s = this.by_lat_lon [lat_lon];
179             if ( marker_s == null ) {
180                 marker_s = this.create_marker_struct (this.object, latitude, longitude);
181                 this.by_lat_lon [ lat_lon ] = marker_s;
182                 this.arm_marker(marker_s.marker, this.map);
183             }
184             
185             // now add a line for this resource in the marker
186             // xxx should compute checked here ?
187             // this is where the checkbox will be appended
188             var ul=marker_s.ul;
189             var checkbox = this.create_record_checkbox (record, ul, false);
190         }, // new_record
191
192         arm_marker: function(marker, map) {
193             if (debug_deep) messages.debug ("arm_marker content="+marker.content);
194             var googlemap = this;
195             google.maps.event.addListener(marker, 'click', function () {
196                 googlemap.infowindow.close();
197                 googlemap.infowindow.setContent(marker.content);
198                 googlemap.infowindow.open(map, marker);
199             });
200         }, // arm_marker
201
202         /*************************** QUERY HANDLER ****************************/
203
204         /*************************** RECORD HANDLER ***************************/
205         on_new_record: function(record) {
206             if (debug_deep) messages.debug("on_new_record");
207             if (this.received_all)
208                 // update checkbox for record
209                 this.set_checkbox_from_record(record, true);
210             else
211                 // store for later update of checkboxes
212                 this.in_set_backlog.push(record);
213         },
214
215         on_clear_records: function(record) {
216             if (debug_deep) messages.debug("on_clear_records");
217         },
218
219         // Could be the default in parent
220         on_query_in_progress: function() {
221             if (debug) messages.debug("on_query_in_progress (spinning)");
222             this.spin();
223         },
224
225         on_query_done: function() {
226                 if (debug) messages.debug("on_query_done");         
227             if (this.received_all) {
228                 this.unspin();
229                 }
230             this.received_set = true;
231         },
232
233         on_field_state_changed: function(data) {
234             if (debug_deep) messages.debug("on_field_state_changed");       
235             switch(data.request) {
236             case FIELD_REQUEST_ADD:
237             case FIELD_REQUEST_ADD_RESET:
238                 this.set_checkbox_from_data(data.value, true);
239                 break;
240             case FIELD_REQUEST_REMOVE:
241             case FIELD_REQUEST_REMOVE_RESET:
242                 this.set_checkbox_from_data(data.value, false);
243                 break;
244             default:
245                 break;
246             }
247         },
248
249
250         // all : this 
251
252         on_all_new_record: function(record) {
253             if (debug_deep) messages.debug("on_all_new_record");
254             this.new_record(record);
255         },
256
257         on_all_clear_records: function() {
258             if (debug) messages.debug("on_all_clear_records");      
259         },
260
261         on_all_query_in_progress: function() {
262             if (debug) messages.debug("on_all_query_in_progress (spinning)");
263             // XXX parent
264             this.spin();
265         },
266
267         on_all_query_done: function() {
268             if (debug) messages.debug("on_all_query_done");
269
270             // MarkerClusterer
271             var markers = [];
272             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
273             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
274             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
275                 var cluster_markers = cluster.getMarkers();
276                 var bounds  = new google.maps.LatLngBounds();
277                 $.each(cluster_markers, function(i, marker){
278                     bounds.extend(marker.getPosition()); 
279                 });
280                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
281                 this.map.fitBounds(bounds);
282             });
283             //now fit the map to the bounds
284             this.map.fitBounds(this.bounds);
285             // Fix the zoom of fitBounds function, it's too close when there is only 1 marker
286             if(markers.length==1){
287                 this.map.setZoom(this.map.getZoom()-4);
288             }
289             var googlemap = this;
290             if (this.received_set) {
291                 /* ... and check the ones specified in the resource list */
292                 $.each(this.in_set_backlog, function(i, record) {
293                     googlemap.set_checkbox_from_record(record, true);
294                 });
295                 // reset 
296                 googlemap.in_set_backlog = [];
297
298                 if (debug) messages.debug("unspinning");
299                 this.unspin();
300             }
301             this.received_all = true;
302
303         } // on_all_query_done
304     });
305         /************************** PRIVATE METHODS ***************************/
306
307     $.plugin('GoogleMap', GoogleMap);
308
309 })(jQuery);