when selecting a cluster, zoom until features are detached
[syp.git] / js / syp.js
1 /* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD
2  * license. */
3
4 /*
5  * With canvas rendering engine, externalgraphics are drawn by loading and
6  * Image javascript object and drawing it with drawImage once it has been
7  * loaded. If matching feature is deleted while image is loading, redraw
8  * function will be called before drawImage and therefore, feature is removed,
9  * but image is still drawn on the screen. We fix it with locks: when an image is
10  * loading, we defer redraw method.
11  */
12 OpenLayers.Renderer.Canvas.prototype = OpenLayers.Util.extend({
13     needsRedraw: false,
14     imagesLoading: 0
15 }, OpenLayers.Renderer.Canvas.prototype);
16 OpenLayers.Renderer.Canvas.prototype.oldRedraw = OpenLayers.Renderer.Canvas.prototype.redraw;
17 OpenLayers.Renderer.Canvas.prototype.redraw = function() {
18     if (this.imagesLoading > 0) {
19         this.needsRedraw = true;
20         return;
21     }
22     OpenLayers.Renderer.Canvas.prototype.oldRedraw.apply(this, arguments);
23 }
24 OpenLayers.Renderer.Canvas.prototype.drawExternalGraphic = function(pt, style) {
25     var img = new Image();
26     img.src = style.externalGraphic;
27
28     if(style.graphicTitle) {
29         img.title=style.graphicTitle;           
30     }
31
32     var width = style.graphicWidth || style.graphicHeight;
33     var height = style.graphicHeight || style.graphicWidth;
34     width = width ? width : style.pointRadius*2;
35     height = height ? height : style.pointRadius*2;
36     var xOffset = (style.graphicXOffset != undefined) ?
37         style.graphicXOffset : -(0.5 * width);
38    var yOffset = (style.graphicYOffset != undefined) ?
39        style.graphicYOffset : -(0.5 * height);
40    var opacity = style.graphicOpacity || style.fillOpacity;
41
42    var context = { img: img, 
43                    x: (pt[0]+xOffset), 
44                    y: (pt[1]+yOffset), 
45                    width: width, 
46                    height: height, 
47                    canvas: this.canvas };
48
49    var self = this;
50    this.imagesLoading++;
51    img.onerror = function() {
52        self.imagesLoading--;
53        if ((self.imagesLoading == 0) && (self.needsRedraw)) {
54            self.needsRedraw = false;
55            self.redraw();
56        }
57    }
58    img.onload = OpenLayers.Function.bind( function() {
59        self.imagesLoading--;
60        if ((self.imagesLoading == 0) && (self.needsRedraw)) {
61            self.needsRedraw = false;
62            self.redraw();
63        } else {
64             this.canvas.drawImage(this.img, this.x, 
65                              this.y, this.width, this.height);
66        }
67    }, context);   
68 }
69
70
71 OpenLayers.Control.SypAttribution = OpenLayers.Class (OpenLayers.Control.Attribution, {
72     updateAttribution: function() {
73         var attributions = [SypStrings.poweredByLink];
74         if (this.map && this.map.layers) {
75             for(var i=0, len=this.map.layers.length; i<len; i++) {
76                 var layer = this.map.layers[i];
77                 if (layer.attribution && layer.getVisibility()) {
78                     attributions.push( layer.attribution );
79                 }
80             }  
81             this.div.innerHTML = attributions.join(this.separator);
82         }
83     }
84 });
85
86 var SYP = {
87     Markers: {
88         ICON: "media/marker-normal.png",
89         SELECT_ICON: "media/marker-selected.png",
90         HEIGHT: 25
91     },
92
93     map: null,
94     baseLayer: null,
95     dataLayer: null,
96     selectControl: null,
97
98     init: function() {
99         this.map = new OpenLayers.Map("map", {
100             controls:[
101                 new OpenLayers.Control.SypAttribution(),
102                 new OpenLayers.Control.Navigation(),
103                 new OpenLayers.Control.PanZoom(),
104                 new OpenLayers.Control.Permalink()
105             ],
106             projection: new OpenLayers.Projection("EPSG:900913"),
107             displayProjection: new OpenLayers.Projection("EPSG:4326")
108         } );
109
110         this.baseLayer = this.createBaseLayer();
111         this.dataLayer = this.createDataLayer();
112         this.map.addLayers([this.baseLayer, this.dataLayer]);
113
114         this.selectControl = this.createSelectControl();
115         this.map.addControl(this.selectControl);
116         this.selectControl.activate();
117
118         if (!this.map.getCenter()) {
119             this.map.setCenter(new OpenLayers.LonLat(0, 0), 0);
120         }
121     },
122
123     createBaseLayer: function() {
124         return new OpenLayers.Layer.OSM("OSM");
125     },
126
127     createDataLayer: function(map) {
128         var defaultStyle = new OpenLayers.Style({
129             externalGraphic: this.Markers.ICON,
130             graphicHeight: "${height}",
131             label: "${label}",
132             fontColor: "white",
133             fontWeight: "bold"
134         }, {
135             context: {
136                 height: function(feature) {
137                     var defaultHeight = SYP.Markers.HEIGHT || 32;
138                     var increase = 4 * (feature.attributes.count - 1);
139                     return Math.min(defaultHeight + increase, 50);
140                 },
141                 label: function(feature) {
142                     var renderer = feature.layer.renderer;
143                     if (renderer.CLASS_NAME == "OpenLayers.Renderer.Canvas") {
144                         return ""; // canvas backend cannot draw text above an external Image
145                     }
146                     return (feature.attributes.count > 1) ? feature.attributes.count: "";
147                 }
148             }
149         });
150         var selectStyle = new OpenLayers.Style({
151             externalGraphic: this.Markers.SELECT_ICON,
152             graphicHeight: this.Markers.HEIGHT || 32 
153         });
154         var styleMap = new OpenLayers.StyleMap (
155                         {"default": defaultStyle,
156                          "select": selectStyle});
157
158         var layer = new OpenLayers.Layer.GML("KML", "items.php", 
159            {
160                strategies: [
161                 new OpenLayers.Strategy.Cluster()
162                 ],
163             styleMap: styleMap,
164             format: OpenLayers.Format.KML, 
165             projection: this.map.displayProjection,
166             eventListeners: { scope: this,
167                               loadend: this.dataLayerEndLoad
168                             }
169            });
170
171         return layer;
172     },
173
174     createSelectControl: function() {
175         var control = new OpenLayers.Control.SelectFeature(
176                                             this.dataLayer, {
177                                                onSelect: this.onFeatureSelect,
178                                                onUnselect: this.onFeatureUnselect,
179                                                toggle: true,
180                                                clickout: false
181                                                             });
182         return control;
183     },
184
185     dataLayerEndLoad: function() {
186         if (!this.checkForFeatures()) {
187             return;
188         }
189
190         var map = this.map;
191         if (map.getControlsByClass("OpenLayers.Control.ArgParser")[0].center
192             == null) { // map center was not set in ArgParser control.
193             var orig = this.Utils.mbr (this.dataLayer);
194             var centerBounds = new OpenLayers.Bounds();
195
196             var mapProj = map.getProjectionObject();
197             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
198
199             var bottomLeft = new OpenLayers.LonLat(orig[0],orig[1]);
200             bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
201             var topRight = new OpenLayers.LonLat(orig[2],orig[3])
202             topRight = topRight.transform(sypOrigProj, mapProj);
203
204             centerBounds.extend(bottomLeft);
205             centerBounds.extend(topRight);
206             map.zoomToExtent(centerBounds);
207         }
208     },
209
210     checkForFeatures: function() {
211         var features = this.dataLayer.features;
212         if (features.length == 0) {
213             var message = SypStrings.noImageRegistered;
214             this.Utils.displayUserMessage(message, "warn");
215         }
216         return !!features.length;
217     },
218
219     createPopup: function(position, contentHTML) {
220         var popup = new OpenLayers.Popup.Anchored("popup",
221                                                   position,
222                                                   null,
223                                                   contentHTML,
224                                                   null,
225                                                   true);
226         popup.autoSize = true;
227         popup.backgroundColor = ""; // deal with it in css
228         popup.border = ""; // deal with it in css
229         popup.closeOnMove = true;
230         return popup;
231     },
232
233     onFeatureUnselect: function (feature) {
234         var map = feature.layer.map;
235         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
236         if (permaControl[0]) {
237             permaControl[0].div.style.display = "";
238         }
239         if (!feature.popup) {
240             this.map.events.unregister("movestart", this, this._unselect);
241             return;
242         }
243         var popup = feature.popup;
244         if (popup.visible()) {
245             popup.hide();
246         }
247     },
248
249     onZoomClusterEnd: function(arg) {
250         var map = arg.object;
251         var point = new OpenLayers.Geometry.Point(this.lonlat.lon, this.lonlat.lat);
252         var center = map.getCenter();
253         for (var i = this.layer.features.length; i-->0;) {
254             var feature = this.layer.features[i];
255             if (feature.geometry.equals(point) && 
256                 (feature.attributes.count == this.count)) {
257                    var self = this;
258                    window.setTimeout(function() { map.setCenter(self.lonlat, map.zoom + 1)}, 500);
259                    return;
260             }
261         }
262         SYP.selectControl.activate();
263         map.events.unregister("zoomend", this, SYP.onZoomClusterEnd);
264     },
265
266     onFeatureSelect: function(feature) {
267         var map = feature.layer.map;
268
269         if (feature.attributes.count > 1) {
270             this.unselect(feature);
271             var lonlat = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
272             var args = {
273                 lonlat: lonlat,
274                 layer: feature.layer,
275                 count: feature.attributes.count
276             }
277             map.events.register("zoomend", args, SYP.onZoomClusterEnd);
278             SYP.selectControl.deactivate();
279             map.setCenter(lonlat, map.zoom + 1);
280             return;
281         }
282         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
283         if (permaControl[0]) {
284             permaControl[0].div.style.display = "none";
285         }
286         var popup = feature.popup;
287
288         var popupPos = null;
289         switch (sypSettings.popupPos) {
290             case 0:
291                 popupPos = feature.geometry.getBounds().getCenterLonLat();
292             break;
293             case 1:
294                 popupPos = SYP.Utils.tlCorner(map, 8);
295             break;
296             case 2:
297                 popupPos = SYP.Utils.trCorner(map, 8);
298             break;
299             case 3:
300                 popupPos = SYP.Utils.brCorner(map, 8);
301             break;
302             case 4:
303                 popupPos = SYP.Utils.blCorner(map, 8);
304             break;
305             default:
306                 popupPos = SYP.Utils.brCorner(map, 8);
307            break;
308         }
309
310         // we cannot reuse popup; we need to recreate it in order for IE
311         // expressions to work. Otherwise, we get a 0x0 image on second view.
312         if (popup) {
313             popup.destroy();
314         }
315         var contentHTML;
316         if (feature.cluster[0].attributes.name) {
317             // escaping name is necessary because it's not enclosed in another html tag.
318             contentHTML = "<h2>" +
319                           SYP.Utils.escapeHTML(feature.cluster[0].attributes.name) +
320                           "</h2>" + 
321                           feature.cluster[0].attributes.description;
322         } else {
323             contentHTML = feature.cluster[0].attributes.description;
324         }
325         if (!contentHTML || !contentHTML.length) {
326             this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
327             return;
328         }
329         popup = SYP.createPopup(popupPos, contentHTML);
330         var control = this;
331         popup.hide = function () {
332             OpenLayers.Element.hide(this.div);
333             control.unselectAll();
334         };
335         map.addPopup(popup);
336         feature.popup = popup;
337         var anchor = popup.div.getElementsByTagName("a")[0];
338         if (anchor) {
339             anchor.onclick = function() { 
340                 SYP.showBigImage(this.href);
341                 return false;
342             }
343         }
344     },
345
346     showBigImage: function (href) {
347         if (OpenLayers.Util.getBrowserName() == "msie") {
348             document.getElementById('bigimg_container').style.display = "block";
349         } else {
350             document.getElementById('bigimg_container').style.display = "table";
351         }
352
353         var maxHeight = document.body.clientHeight * 0.9;
354         var maxWidth = document.body.clientWidth * 0.9;
355         document.getElementById('bigimg').style.height = "";
356         document.getElementById('bigimg').style.width = "";
357         document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
358         document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
359         document.getElementById('bigimg').onload = function () {
360             var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
361             var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
362             if (heightRatio > 1 || widthRatio > 1) {
363                 if (heightRatio > widthRatio) {
364                     this.style.height = this.style.maxHeight;
365                 } else {
366                     this.style.width = this.style.maxWidth;
367                 }
368             }
369
370             var offsetTop = this.offsetTop;
371             var offsetLeft = this.offsetLeft;
372             var par = this.offsetParent;
373             var ismsie = OpenLayers.Util.getBrowserName() == "msie";
374             while (par && !ismsie) {
375                 offsetTop += par.offsetTop;
376                 offsetLeft += par.offsetLeft;
377                 par = par.offsetParent;
378             }
379             var icon = document.getElementById('bigimg_close');
380             icon.style.top = offsetTop;
381             icon.style.left = offsetLeft + this.clientWidth - icon.clientWidth;
382
383         };
384         document.getElementById('bigimg').src = href;
385     },
386
387     closeBigImage: function() {
388         document.getElementById('bigimg').src = "";
389         document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
390         document.getElementById('bigimg_container').style.display = "none";
391     },
392
393     Utils: {
394         tlCorner: function(map, margin) {
395             var bounds = map.calculateBounds();
396             var corner = new OpenLayers.LonLat(bounds.left, bounds.top);
397             var cornerAsPx = map.getPixelFromLonLat(corner);
398             cornerAsPx = cornerAsPx.add( +margin, +margin);
399             return map.getLonLatFromPixel(cornerAsPx);
400         },
401
402         trCorner: function(map, margin) {
403             var bounds = map.calculateBounds();
404             var corner = new OpenLayers.LonLat(bounds.right, bounds.top);
405             var cornerAsPx = map.getPixelFromLonLat(corner);
406             cornerAsPx = cornerAsPx.add( -margin, +margin);
407             return map.getLonLatFromPixel(cornerAsPx);
408         },
409
410         brCorner: function(map, margin) {
411             var bounds = map.calculateBounds();
412             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
413             var cornerAsPx = map.getPixelFromLonLat(corner);
414             cornerAsPx = cornerAsPx.add( -margin, -margin);
415             return map.getLonLatFromPixel(cornerAsPx);
416         },
417
418         blCorner: function(map, margin) {
419             var bounds = map.calculateBounds();
420             var corner = new OpenLayers.LonLat(bounds.left, bounds.bottom);
421             var cornerAsPx = map.getPixelFromLonLat(corner);
422             cornerAsPx = cornerAsPx.add( +margin, -margin);
423             return map.getLonLatFromPixel(cornerAsPx);
424         },
425
426         /* minimum bounds rectangle containing all feature locations.
427          * FIXME: if two features are close, but separated by 180th meridian,
428          * their mbr will span the whole earth. Actually, 179° lon and -170°
429          * lon are considerated very near.
430          */
431         mbr: function (layer) {
432             var features = [];
433             var map = layer.map;
434
435             var mapProj = map.getProjectionObject();
436             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
437
438             for (var i =0; i < layer.features.length; i++) {
439                 if (layer.features[i].cluster) {
440                     features = features.concat(layer.features[i].cluster);
441                 } else {
442                     features = features.concat(layer.features);
443                 }
444             }
445
446             var minlon = 180;
447             var minlat = 88;
448             var maxlon = -180;
449             var maxlat = -88;
450
451             if (features.length == 0) {
452                 // keep default values
453             } else if (features.length == 1) {
454                 // in case there's only one feature, we show an area of at least 
455                 // 4 x 4 degrees
456                 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
457                 var lonlat = pos.transform(mapProj, sypOrigProj);
458
459                 minlon = Math.max (lonlat.lon - 2, -180);
460                 maxlon = Math.min (lonlat.lon + 2, 180);
461                 minlat = Math.max (lonlat.lat - 2, -90);
462                 maxlat = Math.min (lonlat.lat + 2, 90);
463             } else {
464                 for (var i = 0; i < features.length; i++) {
465                     var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
466                     var lonlat = pos.transform(mapProj, sypOrigProj);
467                     minlon = Math.min (lonlat.lon, minlon);
468                     minlat = Math.min (lonlat.lat, minlat);
469                     maxlon = Math.max (lonlat.lon, maxlon);
470                     maxlat = Math.max (lonlat.lat, maxlat);
471                 }
472             }
473
474             return [minlon, minlat, maxlon, maxlat];
475
476         },
477
478         displayUserMessage: function(message, status) {
479             var div = document.getElementById('message');
480             while (div.firstChild)
481                 div.removeChild(div.firstChild);
482             var textNode = document.createTextNode(message);
483             switch (status) {
484                 case "error":
485                     div.style.color = "red";
486                     break;
487                 case "warn":
488                     div.style.color = "#FF8C00";
489                     break;
490                 case "success":
491                     div.style.color = "green";
492                     break;
493                 default:
494                     div.style.color = "black";
495                     break;
496             }
497             div.style.display = "block";
498             div.appendChild(textNode);
499         },
500
501         escapeHTML: function (str) {
502             if (!str) {
503                 return "";
504             }
505             return str.
506              replace(/&/gm, '&amp;').
507              replace(/'/gm, '&#39;').
508              replace(/"/gm, '&quot;').
509              replace(/>/gm, '&gt;').
510              replace(/</gm, '&lt;');
511         }
512     }
513 };
514
515 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
516 // navigator.language
517 if (OpenLayers.Lang[SypStrings.language]) {
518     OpenLayers.Lang.setCode(SypStrings.language);
519 }
520
521 // avoid alerts
522 OpenLayers.Console.userError = function(error) { 
523     SYP.Utils.displayUserMessage(error, "error");
524 }
525
526 // sometimes, especially when cache is clear, firefox does not compute
527 // correctly popup size. That's because at the end of getRenderedDimensions,
528 // dimensions of image is not known. Then, popup size is too small for its
529 // content. We work around the problem by checking that computed size is at
530 // least as big as content. To achieve that, we need to override
531 // OpenLayers.Popup.Anchored.prototype.updateSize to modify it slightly.
532 OpenLayers.Popup.Anchored.prototype.updateSize = function() {
533     var self = this;
534
535     window.setTimeout(function() { // timeout added by SYP
536
537         // determine actual render dimensions of the contents by putting its
538         // contents into a fake contentDiv (for the CSS) and then measuring it
539         var preparedHTML = "<div class='" + self.contentDisplayClass+ "'>" + 
540             self.contentDiv.innerHTML + 
541             "</div>";
542
543         var containerElement = (self.map) ? self.map.layerContainerDiv
544                                           : document.body;
545         var realSize = OpenLayers.Util.getRenderedDimensions(
546             preparedHTML, null, {
547                 displayClass: self.displayClass,
548                 containerElement: containerElement
549             }
550         );
551
552         /*
553          * XXX: next four lines are added by SYP!
554          */
555         if (self.contentDiv) {
556             realSize.w = Math.max (realSize.w, self.contentDiv.scrollWidth);
557             realSize.h = Math.max (realSize.h, self.contentDiv.scrollHeight);
558         }
559
560         // is the "real" size of the div is safe to display in our map?
561         var safeSize = self.getSafeContentSize(realSize);
562
563         var newSize = null;
564         if (safeSize.equals(realSize)) {
565             //real size of content is small enough to fit on the map, 
566             // so we use real size.
567             newSize = realSize;
568
569         } else {
570
571             //make a new OL.Size object with the clipped dimensions 
572             // set or null if not clipped.
573             var fixedSize = new OpenLayers.Size();
574             fixedSize.w = (safeSize.w < realSize.w) ? safeSize.w : null;
575             fixedSize.h = (safeSize.h < realSize.h) ? safeSize.h : null;
576
577             if (fixedSize.w && fixedSize.h) {
578                 //content is too big in both directions, so we will use 
579                 // max popup size (safeSize), knowing well that it will 
580                 // overflow both ways.                
581                 newSize = safeSize;
582             } else {
583                 //content is clipped in only one direction, so we need to 
584                 // run getRenderedDimensions() again with a fixed dimension
585                 var clippedSize = OpenLayers.Util.getRenderedDimensions(
586                     preparedHTML, fixedSize, {
587                         displayClass: self.contentDisplayClass,
588                         containerElement: containerElement
589                     }
590                 );
591
592                 //if the clipped size is still the same as the safeSize, 
593                 // that means that our content must be fixed in the 
594                 // offending direction. If overflow is 'auto', this means 
595                 // we are going to have a scrollbar for sure, so we must 
596                 // adjust for that.
597                 //
598                 var currentOverflow = OpenLayers.Element.getStyle(
599                     self.contentDiv, "overflow"
600                 );
601                 if ( (currentOverflow != "hidden") && 
602                      (clippedSize.equals(safeSize)) ) {
603                     var scrollBar = OpenLayers.Util.getScrollbarWidth();
604                     if (fixedSize.w) {
605                         clippedSize.h += scrollBar;
606                     } else {
607                         clippedSize.w += scrollBar;
608                     }
609                 }
610
611                 newSize = self.getSafeContentSize(clippedSize);
612             }
613         }                        
614         self.setSize(newSize);     
615     }, 0);
616 }