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