googlemap resources now displayed as hrn’s again
[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             //// 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                 scrollwheel: false,
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         // The function accepts both records and their id
90         // record.key points to the name of the primary key for this record
91         // typically this is 'urn'
92         record_id : function (input) {
93             var id;
94             switch (manifold.get_type(input)) {
95             case TYPE_VALUE:
96                 id = input;
97                 break;
98             case TYPE_RECORD:
99                 if ( ! this.key in input ) return;
100                 id = input[this.key];
101                 break;
102             default:
103                 throw "googlemap.record_id: not implemented";
104                 break;
105             }
106             return id;
107         },
108
109         // return { marker: gmap_marker, ul : <ul DOM> }
110         create_marker_struct: function (object,lat,lon) {
111             // the DOM fragment
112             var dom = $("<p>").addClass("geo").append(object+"(s)");
113             var ul = $("<ul>").addClass("geo");
114             dom.append(ul);
115             // add a gmap marker to the mix
116             var marker = new google.maps.Marker({
117                 position: new google.maps.LatLng(lat, lon),
118                 title: object,
119                 // gmap can deal with a DOM element but not a jquery object
120                 content: dom.get(0),
121             }); 
122             return {marker:marker, ul:ul};
123         },
124
125         // given an input <ul> element, this method inserts a <li> with embedded checkbox 
126         // for displaying/selecting the resource corresponding to the input record
127         // returns the created <input> element for further checkbox manipulation
128         create_record_checkbox: function (record,ul,checked) {
129             var checkbox = $("<input>", {type:'checkbox', checked:checked, class:'geo'});
130             var id=this.record_id(record);
131             // use hrn as far as possible for displaying
132             var label= ('hrn' in record) ? record.hrn : id;
133             ul.append($("<li>").addClass("geo").append(checkbox).
134                       append($("<span>").addClass("geo").append(label)));
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                 manifold.raise_event (googlemap.options.query_uuid, this.checked ? SET_ADD : SET_REMOVED, id);
140             });
141             return checkbox;
142         },
143             
144         warning: function (record,message) {
145             try {messages.warning (message+" -- hostname="+record.hostname); }
146             catch (err) {messages.warning (message); }
147         },
148             
149         // retrieve DOM checkbox and make sure it is checked/unchecked
150         set_checkbox: function(record, checked) {
151             var id=this.record_id (record);
152             if (! id) { 
153                 this.warning (record, "googlemap.set_checkbox: record has no id");
154                 return; 
155             }
156             var checkbox = this.by_id [ id ];
157             if (! checkbox ) { 
158                 this.warning (record, "googlemap.set_checkbox: checkbox not found");
159                 return; 
160             }
161             checkbox.prop('checked',checked);
162         }, // set_checkbox
163
164         // this record is *in* the slice
165         new_record: function(record) {
166                 if (googlemap_debug_detailed) messages.debug ("new_record");
167             if (!(record['latitude'])) return false;
168             
169             // get the coordinates
170             var latitude=unfold.get_value(record['latitude']);
171             var longitude=unfold.get_value(record['longitude']);
172             var lat_lon = latitude + longitude;
173
174             // check if we've seen anything at that place already
175             // xxx might make sense to allow for some fuzziness, 
176             // i.e. consider 2 places equal if not further away than 300m or so...
177             var marker_s = this.by_lat_lon [lat_lon];
178             if ( marker_s == null ) {
179                 marker_s = this.create_marker_struct (this.object, latitude, longitude);
180                 this.by_lat_lon [ lat_lon ] = marker_s;
181                 this.arm_marker(marker_s.marker, this.map);
182             }
183             
184             // now add a line for this resource in the marker
185             // xxx should compute checked here ?
186             // this is where the checkbox will be appended
187             var ul=marker_s.ul;
188             var checkbox = this.create_record_checkbox (record, ul, false);
189             var id=this.record_id(record);
190             // used to keep a dict here, but only checkbox is required
191             this.by_id[id] = checkbox;
192         }, // new_record
193
194         arm_marker: function(marker, map) {
195             if (googlemap_debug_detailed) messages.debug ("arm_marker content="+marker.content);
196             var googlemap = this;
197             google.maps.event.addListener(marker, 'click', function () {
198                 googlemap.infowindow.close();
199                 googlemap.infowindow.setContent(marker.content);
200                 googlemap.infowindow.open(map, marker);
201             });
202         }, // arm_marker
203
204         /*************************** QUERY HANDLER ****************************/
205
206         /*************************** RECORD HANDLER ***************************/
207         on_new_record: function(record) {
208             if (googlemap_debug_detailed) messages.debug("on_new_record");
209             if (this.received_all)
210                 // update checkbox for record
211                 this.set_checkbox(record, true);
212             else
213                 // store for later update of checkboxes
214                 this.in_set_backlog.push(record);
215         },
216
217         on_clear_records: function(record) {
218             if (googlemap_debug_detailed) messages.debug("on_clear_records");
219         },
220
221         // Could be the default in parent
222         on_query_in_progress: function() {
223             if (googlemap_debug) messages.debug("on_query_in_progress (spinning)");
224             this.spin();
225         },
226
227         on_query_done: function() {
228             if (googlemap_debug) messages.debug("on_query_done");           
229             if (this.received_all) {
230                 this.unspin();
231             }
232             this.received_set = true;
233         },
234
235         on_field_state_changed: function(data) {
236             if (googlemap_debug_detailed) messages.debug("on_field_state_changed");         
237             switch(data.request) {
238             case FIELD_REQUEST_ADD:
239             case FIELD_REQUEST_ADD_RESET:
240                 this.set_checkbox(data.value, true);
241                 break;
242             case FIELD_REQUEST_REMOVE:
243             case FIELD_REQUEST_REMOVE_RESET:
244                 this.set_checkbox(data.value, false);
245                 break;
246             default:
247                 break;
248             }
249         },
250
251
252         // all : this 
253
254         on_all_new_record: function(record) {
255             if (googlemap_debug_detailed) messages.debug("on_all_new_record");
256             this.new_record(record);
257         },
258
259         on_all_clear_records: function() {
260             if (googlemap_debug) messages.debug("on_all_clear_records");            
261         },
262
263         on_all_query_in_progress: function() {
264             if (googlemap_debug) messages.debug("on_all_query_in_progress (spinning)");
265             // XXX parent
266             this.spin();
267         },
268
269         on_all_query_done: function() {
270             if (googlemap_debug) messages.debug("on_all_query_done");
271
272             // MarkerClusterer
273             var markers = [];
274             $.each(this.by_lat_lon, function (k, s) { markers.push(s.marker); });
275             this.markerCluster = new MarkerClusterer(this.map, markers, {zoomOnClick: false});
276             google.maps.event.addListener(this.markerCluster, "clusterclick", function (cluster) {
277                 var cluster_markers = cluster.getMarkers();
278                 var bounds  = new google.maps.LatLngBounds();
279                 $.each(cluster_markers, function(i, marker){
280                     bounds.extend(marker.getPosition()); 
281                 });
282                 //map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
283                 this.map.fitBounds(bounds);
284             });
285
286             var googlemap = this;
287             if (this.received_set) {
288                 /* ... and check the ones specified in the resource list */
289                 $.each(this.in_set_backlog, function(i, record) {
290                     googlemap.set_checkbox(record, true);
291                 });
292                 // reset 
293                 googlemap.in_set_backlog = [];
294
295                 if (googlemap_debug) messages.debug("unspinning");
296                 this.unspin();
297             }
298             this.received_all = true;
299
300         } // on_all_query_done
301     });
302         /************************** PRIVATE METHODS ***************************/
303
304     $.plugin('GoogleMap', GoogleMap);
305
306 })(jQuery);