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