fixed merge issue
[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             // id --> { <li>, <input> }
32             this.by_lat_lon = {};
33             this.by_id = {};
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             // xxx temporary hack
48             // as of nov. 28 2013 we have here this.key='urn', but in any place where
49             // the code tries to access record[this.key] the records only have
50             // keys=type,hrn,network_hrn,hostname
51             // so for now we force using hrn instead
52             // as soon as record have their primary key set this line can be removed
53             // see also same hack in querytable
54             this.key= (this.key == 'urn') ? 'hrn' : this.key;
55
56             //// Setup query and record handlers 
57             // this query is the one about the slice itself 
58             // event related to this query will trigger callbacks like on_new_record
59             this.listen_query(options.query_uuid);
60             // this one is the complete list of resources
61             // and will be bound to callbacks like on_all_new_record
62             this.listen_query(options.query_all_uuid, 'all');
63
64             /* GUI setup and event binding */
65             this.initialize_map();
66         }, // init
67
68         /* PLUGIN EVENTS */
69
70         on_show: function(e) {
71             if (googlemap_debug) messages.debug("googlemap.on_show");
72             var googlemap = e.data;
73             google.maps.event.trigger(googlemap.map, 'resize');
74         }, // on_show
75
76         /* GUI EVENTS */
77
78         /* GUI MANIPULATION */
79
80         initialize_map: function() {
81             this.markerCluster = null;
82
83             var center = new google.maps.LatLng(this.options.latitude, this.options.longitude);
84             var myOptions = {
85                 zoom: this.options.zoom,
86                 center: center,
87                 scrollwheel: false,
88                 mapTypeId: google.maps.MapTypeId.ROADMAP,
89             }
90             
91             var domid = this.options.plugin_uuid + '--' + 'googlemap';
92             var elmt = document.getElementById(domid);
93             if (googlemap_debug) messages.debug("gmap.initialize_map based on  domid=" + domid + " elmt=" + elmt);
94             this.map = new google.maps.Map(elmt, myOptions);
95             this.infowindow = new google.maps.InfoWindow();
96         }, // initialize_map
97
98         // The function accepts both records and their id
99         // record.key points to the name of the primary key for this record
100         // typically this is 'urn'
101         record_id : function (input) {
102             var id;
103             switch (manifold.get_type(input)) {
104             case TYPE_VALUE:
105                 id = input;
106                 break;
107             case TYPE_RECORD:
108                 if ( ! this.key in input ) return;
109                 id = input[this.key];
110                 break;
111             default:
112                 throw "googlemap.record_id: not implemented";
113                 break;
114             }
115             return id;
116         },
117
118         // return { marker: gmap_marker, ul : <ul DOM> }
119         create_marker_struct: function (object,lat,lon) {
120             // the DOM fragment
121             var dom = $("<p>").addClass("geo").append(object+"(s)");
122             var ul = $("<ul>").addClass("geo");
123             dom.append(ul);
124             // add a gmap marker to the mix
125             var marker = new google.maps.Marker({
126                 position: new google.maps.LatLng(lat, lon),
127                 title: object,
128                 // gmap can deal with a DOM element but not a jquery object
129                 content: dom.get(0),
130             }); 
131             return {marker:marker, ul:ul};
132         },
133
134         // given an input <ul> element, this method inserts a <li> with embedded checkbox 
135         // for displaying/selecting the resource corresponding to the input record
136         // returns the created <input> element for further checkbox manipulation
137         create_record_checkbox: function (record,ul,checked) {
138             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
139             var id=this.record_id(record);
140             // use hrn as far as possible for displaying
141             var label= ('hrn' in record) ? record.hrn : id;
142             ul.append($("<li>").addClass("geo").append(checkbox).
143                       append($("<span>").addClass("geo").append(label)));
144             var googlemap=this;
145             // the callback for when a user clicks
146             // NOTE: this will *not* be called for changes done by program
147             checkbox.change( function (e) {
148                 manifold.raise_event (googlemap.options.query_uuid, this.checked ? SET_ADD : SET_REMOVED, id);
149             });
150             return checkbox;
151         },
152             
153         warning: function (record,message) {
154             try {messages.warning (message+" -- hostname="+record.hostname); }
155             catch (err) {messages.warning (message); }
156         },
157             
158         // retrieve DOM checkbox and make sure it is checked/unchecked
159         set_checkbox: function(record, checked) {
160             var id=this.record_id (record);
161             if (! id) { 
162                 this.warning (record, "googlemap.set_checkbox: record has no id");
163                 return; 
164             }
165             var checkbox = this.by_id [ id ];
166             if (! checkbox ) { 
167                 this.warning (record, "googlemap.set_checkbox: checkbox not found");
168                 return; 
169             }
170             checkbox.prop('checked',checked);
171         }, // set_checkbox
172
173         // this record is *in* the slice
174         new_record: function(record) {
175                 if (googlemap_debug_detailed) messages.debug ("new_record");
176             if (!(record['latitude'])) return false;
177             
178             // get the coordinates
179             var latitude=unfold.get_value(record['latitude']);
180             var longitude=unfold.get_value(record['longitude']);
181             var lat_lon = latitude + longitude;
182
183             // check if we've seen anything at that place already
184             // xxx might make sense to allow for some fuzziness, 
185             // i.e. consider 2 places equal if not further away than 300m or so...
186             var marker_s = this.by_lat_lon [lat_lon];
187             if ( marker_s == null ) {
188                 marker_s = this.create_marker_struct (this.object, latitude, longitude);
189                 this.by_lat_lon [ lat_lon ] = marker_s;
190                 this.arm_marker(marker_s.marker, this.map);
191             }
192             
193             // now add a line for this resource in the marker
194             // xxx should compute checked here ?
195             // this is where the checkbox will be appended
196             var ul=marker_s.ul;
197             var checkbox = this.create_record_checkbox (record, ul, false);
198             var id=this.record_id(record);
199             // used to keep a dict here, but only checkbox is required
200             this.by_id[id] = checkbox;
201         }, // new_record
202
203         arm_marker: function(marker, map) {
204             if (googlemap_debug_detailed) messages.debug ("arm_marker content="+marker.content);
205             var googlemap = this;
206             google.maps.event.addListener(marker, 'click', function () {
207                 googlemap.infowindow.close();
208                 googlemap.infowindow.setContent(marker.content);
209                 googlemap.infowindow.open(map, marker);
210             });
211         }, // arm_marker
212
213         /*************************** QUERY HANDLER ****************************/
214
215         /*************************** RECORD HANDLER ***************************/
216         on_new_record: function(record) {
217             if (googlemap_debug_detailed) messages.debug("on_new_record");
218             if (this.received_all)
219                 // update checkbox for record
220                 this.set_checkbox(record, true);
221             else
222                 // store for later update of checkboxes
223                 this.in_set_backlog.push(record);
224         },
225
226         on_clear_records: function(record) {
227             if (googlemap_debug_detailed) messages.debug("on_clear_records");
228         },
229
230         // Could be the default in parent
231         on_query_in_progress: function() {
232             if (googlemap_debug) messages.debug("on_query_in_progress (spinning)");
233             this.spin();
234         },
235
236         on_query_done: function() {
237             if (googlemap_debug) messages.debug("on_query_done");           
238             if (this.received_all) {
239                 this.unspin();
240             }
241             this.received_set = true;
242         },
243
244         on_field_state_changed: function(data) {
245             if (googlemap_debug_detailed) messages.debug("on_field_state_changed");         
246             switch(data.request) {
247             case FIELD_REQUEST_ADD:
248             case FIELD_REQUEST_ADD_RESET:
249                 this.set_checkbox(data.value, true);
250                 break;
251             case FIELD_REQUEST_REMOVE:
252             case FIELD_REQUEST_REMOVE_RESET:
253                 this.set_checkbox(data.value, false);
254                 break;
255             default:
256                 break;
257             }
258         },
259
260
261         // all : this 
262
263         on_all_new_record: function(record) {
264             if (googlemap_debug_detailed) messages.debug("on_all_new_record");
265             this.new_record(record);
266         },
267
268         on_all_clear_records: function() {
269             if (googlemap_debug) messages.debug("on_all_clear_records");            
270         },
271
272         on_all_query_in_progress: function() {
273             if (googlemap_debug) messages.debug("on_all_query_in_progress (spinning)");
274             // XXX parent
275             this.spin();
276         },
277
278         on_all_query_done: function() {
279             if (googlemap_debug) messages.debug("on_all_query_done");
280
281             // MarkerClusterer
282             var markers = [];
283             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
284             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
285             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
286                 var cluster_markers = cluster.getMarkers();
287                 var bounds  = new google.maps.LatLngBounds();
288                 $.each(cluster_markers, function(i, marker){
289                     bounds.extend(marker.getPosition()); 
290                 });
291                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
292                 this.map.fitBounds(bounds);
293             });
294
295             var googlemap = this;
296             if (this.received_set) {
297                 /* ... and check the ones specified in the resource list */
298                 $.each(this.in_set_backlog, function(i, record) {
299                     googlemap.set_checkbox(record, true);
300                 });
301                 // reset 
302                 googlemap.in_set_backlog = [];
303
304                 if (googlemap_debug) messages.debug("unspinning");
305                 this.unspin();
306             }
307             this.received_all = true;
308
309         } // on_all_query_done
310     });
311         /************************** PRIVATE METHODS ***************************/
312
313     $.plugin('GoogleMap', GoogleMap);
314
315 })(jQuery);