reworked googlemap
[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('Hazelnut');
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("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             return unfold.escape_id(key_value).replace(/\\/g, '');
105         },          
106
107         // return { marker: gmap_marker, ul : <ul DOM> }
108         create_marker_struct: function (object,lat,lon) {
109             // the DOM fragment
110             var dom = $("<p>").addClass("geo").append(object+"(s)");
111             var ul = $("<ul>").addClass("geo");
112             dom.append(ul);
113             // add a gmap marker to the mix
114             var marker = new google.maps.Marker({
115                 position: new google.maps.LatLng(lat, lon),
116                 title: object,
117                 // gmap can deal with a DOM element but not a jquery object
118                 content: dom.get(0),
119             }); 
120             return {marker:marker, ul:ul};
121         },
122
123         // add an entry in the marker <ul> tag for that record
124         // returns { checkbox : <input DOM> }
125         create_record_checkbox: function (record,ul,checked) {
126             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
127             var hrn=this.record_hrn(record);
128             ul.append($("<li>").addClass("geo").append(checkbox).
129                       append($("<span>").addClass("geo").append(hrn)));
130             var googlemap=this;
131             // the callback for when a user clicks
132             // NOTE: this will *not* be called for changes done by program
133             checkbox.change( function (e) {
134                 manifold.raise_event (googlemap.options.query_uuid, 
135                                       this.checked ? SET_ADD : SET_REMOVED, hrn);
136             });
137             return checkbox;
138         },
139             
140         // retrieve DOM checkbox and make sure it is checked/unchecked
141         set_checkbox: function(record, checked) {
142             var hrn=this.record_hrn (record);
143             if (! hrn) { messages.warning ("set_checkbox: record has no hrn"); return; }
144             var checkbox_s = this.by_hrn [ hrn ];
145             if (! checkbox_s ) { messages.warning ("set_checkbox: could not spot checkbox for hrn "+hrn); return; }
146             checkbox_s.checkbox.prop('checked',checked);
147         }, // set_checkbox
148
149         // this record is *in* the slice
150         new_record: function(record) {
151             if (googlemap_debug_detailed) messages.debug ("new_record");
152             if (!(record['latitude'])) return false;
153             
154             // get the coordinates
155             var latitude=get_value(record['latitude']);
156             var longitude=get_value(record['longitude']);
157             var lat_lon = latitude + longitude;
158
159             // check if we've seen anything at that place already
160             // xxx might make sense to allow for some fuzziness, 
161             // i.e. consider 2 places equal if not further away than 300m or so...
162             var marker_s = this.by_lat_lon [lat_lon];
163             if ( marker_s == null ) {
164                 marker_s = this.create_marker_struct (this.object, latitude, longitude);
165                 this.by_lat_lon [ lat_lon ] = marker_s;
166                 this.arm_marker(marker_s.marker, this.map);
167             }
168             
169             // now add a line for this resource in the marker
170             // xxx should compute checked here ?
171             // this is where the checkbox will be appended
172             var ul=marker_s.ul;
173             var checkbox = this.create_record_checkbox (record, ul, false);
174             if ( ! this.key in record ) return;
175             var key_value = record[this.key];
176             var hrn = unfold.escape_id(key_value).replace(/\\/g, '');
177             this.by_hrn[hrn] = {
178                 checkbox: checkbox,
179                 // xxx Thierry sept 2013
180                 // xxx actually we might have just used a domid-based scheme instead of the hash
181                 // since at this point we only need to retrieve the checkbox from an hrn
182                 // but I was not sure enough that extra needs would not show up so I kept this in place
183                 // xxx not sure these are actually useful :
184                 value: key_value,
185                 record: record,
186             }
187         }, // new_record
188
189         arm_marker: function(marker, map) {
190             if (googlemap_debug_detailed) messages.debug ("arm_marker content="+marker.content);
191             var googlemap = this;
192             google.maps.event.addListener(marker, 'click', function () {
193                 googlemap.infowindow.close();
194                 googlemap.infowindow.setContent(marker.content);
195                 googlemap.infowindow.open(map, marker);
196             });
197         }, // arm_marker
198
199         /*************************** QUERY HANDLER ****************************/
200
201         /*************************** RECORD HANDLER ***************************/
202         on_new_record: function(record) {
203             if (googlemap_debug_detailed) messages.debug("on_new_record");
204             if (this.received_all)
205                 // update checkbox for record
206                 this.set_checkbox(record, true);
207             else
208                 // store for later update of checkboxes
209                 this.in_set_backlog.push(record);
210         },
211
212         on_clear_records: function(record) {
213             if (googlemap_debug_detailed) messages.debug("on_clear_records");
214         },
215
216         // Could be the default in parent
217         on_query_in_progress: function() {
218             if (googlemap_debug) messages.debug("on_query_in_progress (spinning)");
219             this.spin();
220         },
221
222         on_query_done: function() {
223             if (googlemap_debug) messages.debug("on_query_done");           
224             if (this.received_all) {
225                 this.unspin();
226             }
227             this.received_set = true;
228         },
229
230         on_field_state_changed: function(data) {
231             if (googlemap_debug_detailed) messages.debug("on_field_state_changed");         
232             switch(data.request) {
233             case FIELD_REQUEST_ADD:
234             case FIELD_REQUEST_ADD_RESET:
235                 this.set_checkbox(data.value, true);
236                 break;
237             case FIELD_REQUEST_REMOVE:
238             case FIELD_REQUEST_REMOVE_RESET:
239                 this.set_checkbox(data.value, false);
240                 break;
241             default:
242                 break;
243             }
244         },
245
246
247         // all : this 
248
249         on_all_new_record: function(record) {
250             if (googlemap_debug_detailed) messages.debug("on_all_new_record");
251             this.new_record(record);
252         },
253
254         on_all_clear_records: function() {
255             if (googlemap_debug) messages.debug("on_all_clear_records");            
256         },
257
258         on_all_query_in_progress: function() {
259             if (googlemap_debug) messages.debug("on_all_query_in_progress (spinning)");
260             // XXX parent
261             this.spin();
262         },
263
264         on_all_query_done: function() {
265             if (googlemap_debug) messages.debug("on_all_query_done");
266
267             // MarkerClusterer
268             var markers = [];
269             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
270             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
271             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
272                 var cluster_markers = cluster.getMarkers();
273                 var bounds  = new google.maps.LatLngBounds();
274                 $.each(cluster_markers, function(i, marker){
275                     bounds.extend(marker.getPosition()); 
276                 });
277                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
278                 this.map.fitBounds(bounds);
279             });
280
281             var googlemap = this;
282             if (this.received_set) {
283                 /* ... and check the ones specified in the resource list */
284                 $.each(this.in_set_backlog, function(i, record) {
285                     googlemap.set_checkbox(record, true);
286                 });
287                 // reset 
288                 googlemap.in_set_backlog = [];
289
290                 if (googlemap_debug) messages.debug("unspinning");
291                 this.unspin();
292             }
293             this.received_all = true;
294
295         } // on_all_query_done
296     });
297         /************************** PRIVATE METHODS ***************************/
298
299     $.plugin('GoogleMap', GoogleMap);
300
301 })(jQuery);