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