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