9bccba64d4e1d6796c7b06049e85cc0fb974e1c8
[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     onFeatureSelect: function(feature) {
250         var map = feature.layer.map;
251         if (feature.attributes.count > 1) {
252             this.unselect(feature);
253             var lonlat = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
254             map.setCenter(lonlat, map.zoom + 1);
255             return;
256         }
257         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
258         if (permaControl[0]) {
259             permaControl[0].div.style.display = "none";
260         }
261         var popup = feature.popup;
262
263         var popupPos = null;
264         switch (sypSettings.popupPos) {
265             case 0:
266                 popupPos = feature.geometry.getBounds().getCenterLonLat();
267             break;
268             case 1:
269                 popupPos = SYP.Utils.tlCorner(map, 8);
270             break;
271             case 2:
272                 popupPos = SYP.Utils.trCorner(map, 8);
273             break;
274             case 3:
275                 popupPos = SYP.Utils.brCorner(map, 8);
276             break;
277             case 4:
278                 popupPos = SYP.Utils.blCorner(map, 8);
279             break;
280             default:
281                 popupPos = SYP.Utils.brCorner(map, 8);
282            break;
283         }
284
285         // we cannot reuse popup; we need to recreate it in order for IE
286         // expressions to work. Otherwise, we get a 0x0 image on second view.
287         if (popup) {
288             popup.destroy();
289         }
290         var contentHTML;
291         if (feature.cluster[0].attributes.name) {
292             // escaping name is necessary because it's not enclosed in another html tag.
293             contentHTML = "<h2>" +
294                           SYP.Utils.escapeHTML(feature.cluster[0].attributes.name) +
295                           "</h2>" + 
296                           feature.cluster[0].attributes.description;
297         } else {
298             contentHTML = feature.cluster[0].attributes.description;
299         }
300         if (!contentHTML || !contentHTML.length) {
301             this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
302             return;
303         }
304         popup = SYP.createPopup(popupPos, contentHTML);
305         var control = this;
306         popup.hide = function () {
307             OpenLayers.Element.hide(this.div);
308             control.unselectAll();
309         };
310         map.addPopup(popup);
311         feature.popup = popup;
312         var anchor = popup.div.getElementsByTagName("a")[0];
313         if (anchor) {
314             anchor.onclick = function() { 
315                 SYP.showBigImage(this.href);
316                 return false;
317             }
318         }
319     },
320
321     showBigImage: function (href) {
322         if (OpenLayers.Util.getBrowserName() == "msie") {
323             document.getElementById('bigimg_container').style.display = "block";
324         } else {
325             document.getElementById('bigimg_container').style.display = "table";
326         }
327
328         var maxHeight = document.body.clientHeight * 0.9;
329         var maxWidth = document.body.clientWidth * 0.9;
330         document.getElementById('bigimg').style.height = "";
331         document.getElementById('bigimg').style.width = "";
332         document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
333         document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
334         document.getElementById('bigimg').onload = function () {
335             var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
336             var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
337             if (heightRatio > 1 || widthRatio > 1) {
338                 if (heightRatio > widthRatio) {
339                     this.style.height = this.style.maxHeight;
340                 } else {
341                     this.style.width = this.style.maxWidth;
342                 }
343             }
344
345             var offsetTop = this.offsetTop;
346             var offsetLeft = this.offsetLeft;
347             var par = this.offsetParent;
348             var ismsie = OpenLayers.Util.getBrowserName() == "msie";
349             while (par && !ismsie) {
350                 offsetTop += par.offsetTop;
351                 offsetLeft += par.offsetLeft;
352                 par = par.offsetParent;
353             }
354             var icon = document.getElementById('bigimg_close');
355             icon.style.top = offsetTop;
356             icon.style.left = offsetLeft + this.clientWidth - icon.clientWidth;
357
358         };
359         document.getElementById('bigimg').src = href;
360     },
361
362     closeBigImage: function() {
363         document.getElementById('bigimg').src = "";
364         document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
365         document.getElementById('bigimg_container').style.display = "none";
366     },
367
368     Utils: {
369         tlCorner: function(map, margin) {
370             var bounds = map.calculateBounds();
371             var corner = new OpenLayers.LonLat(bounds.left, bounds.top);
372             var cornerAsPx = map.getPixelFromLonLat(corner);
373             cornerAsPx = cornerAsPx.add( +margin, +margin);
374             return map.getLonLatFromPixel(cornerAsPx);
375         },
376
377         trCorner: function(map, margin) {
378             var bounds = map.calculateBounds();
379             var corner = new OpenLayers.LonLat(bounds.right, bounds.top);
380             var cornerAsPx = map.getPixelFromLonLat(corner);
381             cornerAsPx = cornerAsPx.add( -margin, +margin);
382             return map.getLonLatFromPixel(cornerAsPx);
383         },
384
385         brCorner: function(map, margin) {
386             var bounds = map.calculateBounds();
387             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
388             var cornerAsPx = map.getPixelFromLonLat(corner);
389             cornerAsPx = cornerAsPx.add( -margin, -margin);
390             return map.getLonLatFromPixel(cornerAsPx);
391         },
392
393         blCorner: function(map, margin) {
394             var bounds = map.calculateBounds();
395             var corner = new OpenLayers.LonLat(bounds.left, bounds.bottom);
396             var cornerAsPx = map.getPixelFromLonLat(corner);
397             cornerAsPx = cornerAsPx.add( +margin, -margin);
398             return map.getLonLatFromPixel(cornerAsPx);
399         },
400
401         /* minimum bounds rectangle containing all feature locations.
402          * FIXME: if two features are close, but separated by 180th meridian,
403          * their mbr will span the whole earth. Actually, 179° lon and -170°
404          * lon are considerated very near.
405          */
406         mbr: function (layer) {
407             var features = [];
408             var map = layer.map;
409
410             var mapProj = map.getProjectionObject();
411             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
412
413             for (var i =0; i < layer.features.length; i++) {
414                 if (layer.features[i].cluster) {
415                     features = features.concat(layer.features[i].cluster);
416                 } else {
417                     features = features.concat(layer.features);
418                 }
419             }
420
421             var minlon = 180;
422             var minlat = 88;
423             var maxlon = -180;
424             var maxlat = -88;
425
426             if (features.length == 0) {
427                 // keep default values
428             } else if (features.length == 1) {
429                 // in case there's only one feature, we show an area of at least 
430                 // 4 x 4 degrees
431                 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
432                 var lonlat = pos.transform(mapProj, sypOrigProj);
433
434                 minlon = Math.max (lonlat.lon - 2, -180);
435                 maxlon = Math.min (lonlat.lon + 2, 180);
436                 minlat = Math.max (lonlat.lat - 2, -90);
437                 maxlat = Math.min (lonlat.lat + 2, 90);
438             } else {
439                 for (var i = 0; i < features.length; i++) {
440                     var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
441                     var lonlat = pos.transform(mapProj, sypOrigProj);
442                     minlon = Math.min (lonlat.lon, minlon);
443                     minlat = Math.min (lonlat.lat, minlat);
444                     maxlon = Math.max (lonlat.lon, maxlon);
445                     maxlat = Math.max (lonlat.lat, maxlat);
446                 }
447             }
448
449             return [minlon, minlat, maxlon, maxlat];
450
451         },
452
453         displayUserMessage: function(message, status) {
454             var div = document.getElementById('message');
455             while (div.firstChild)
456                 div.removeChild(div.firstChild);
457             var textNode = document.createTextNode(message);
458             switch (status) {
459                 case "error":
460                     div.style.color = "red";
461                     break;
462                 case "warn":
463                     div.style.color = "#FF8C00";
464                     break;
465                 case "success":
466                     div.style.color = "green";
467                     break;
468                 default:
469                     div.style.color = "black";
470                     break;
471             }
472             div.style.display = "block";
473             div.appendChild(textNode);
474         },
475
476         escapeHTML: function (str) {
477             if (!str) {
478                 return "";
479             }
480             return str.
481              replace(/&/gm, '&amp;').
482              replace(/'/gm, '&#39;').
483              replace(/"/gm, '&quot;').
484              replace(/>/gm, '&gt;').
485              replace(/</gm, '&lt;');
486         }
487     }
488 };
489
490 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
491 // navigator.language
492 if (OpenLayers.Lang[SypStrings.language]) {
493     OpenLayers.Lang.setCode(SypStrings.language);
494 }
495
496 // avoid alerts
497 OpenLayers.Console.userError = function(error) { 
498     SYP.Utils.displayUserMessage(error, "error");
499 }
500
501 // sometimes, especially when cache is clear, firefox does not compute
502 // correctly popup size. That's because at the end of getRenderedDimensions,
503 // dimensions of image is not known. Then, popup size is too small for its
504 // content. We work around the problem by checking that computed size is at
505 // least as big as content. To achieve that, we need to override
506 // OpenLayers.Popup.Anchored.prototype.updateSize to modify it slightly.
507 OpenLayers.Popup.Anchored.prototype.updateSize = function() {
508     var self = this;
509
510     window.setTimeout(function() { // timeout added by SYP
511
512         // determine actual render dimensions of the contents by putting its
513         // contents into a fake contentDiv (for the CSS) and then measuring it
514         var preparedHTML = "<div class='" + self.contentDisplayClass+ "'>" + 
515             self.contentDiv.innerHTML + 
516             "</div>";
517
518         var containerElement = (self.map) ? self.map.layerContainerDiv
519                                           : document.body;
520         var realSize = OpenLayers.Util.getRenderedDimensions(
521             preparedHTML, null, {
522                 displayClass: self.displayClass,
523                 containerElement: containerElement
524             }
525         );
526
527         /*
528          * XXX: next four lines are added by SYP!
529          */
530         if (self.contentDiv) {
531             realSize.w = Math.max (realSize.w, self.contentDiv.scrollWidth);
532             realSize.h = Math.max (realSize.h, self.contentDiv.scrollHeight);
533         }
534
535         // is the "real" size of the div is safe to display in our map?
536         var safeSize = self.getSafeContentSize(realSize);
537
538         var newSize = null;
539         if (safeSize.equals(realSize)) {
540             //real size of content is small enough to fit on the map, 
541             // so we use real size.
542             newSize = realSize;
543
544         } else {
545
546             //make a new OL.Size object with the clipped dimensions 
547             // set or null if not clipped.
548             var fixedSize = new OpenLayers.Size();
549             fixedSize.w = (safeSize.w < realSize.w) ? safeSize.w : null;
550             fixedSize.h = (safeSize.h < realSize.h) ? safeSize.h : null;
551
552             if (fixedSize.w && fixedSize.h) {
553                 //content is too big in both directions, so we will use 
554                 // max popup size (safeSize), knowing well that it will 
555                 // overflow both ways.                
556                 newSize = safeSize;
557             } else {
558                 //content is clipped in only one direction, so we need to 
559                 // run getRenderedDimensions() again with a fixed dimension
560                 var clippedSize = OpenLayers.Util.getRenderedDimensions(
561                     preparedHTML, fixedSize, {
562                         displayClass: self.contentDisplayClass,
563                         containerElement: containerElement
564                     }
565                 );
566
567                 //if the clipped size is still the same as the safeSize, 
568                 // that means that our content must be fixed in the 
569                 // offending direction. If overflow is 'auto', this means 
570                 // we are going to have a scrollbar for sure, so we must 
571                 // adjust for that.
572                 //
573                 var currentOverflow = OpenLayers.Element.getStyle(
574                     self.contentDiv, "overflow"
575                 );
576                 if ( (currentOverflow != "hidden") && 
577                      (clippedSize.equals(safeSize)) ) {
578                     var scrollBar = OpenLayers.Util.getScrollbarWidth();
579                     if (fixedSize.w) {
580                         clippedSize.h += scrollBar;
581                     } else {
582                         clippedSize.w += scrollBar;
583                     }
584                 }
585
586                 newSize = self.getSafeContentSize(clippedSize);
587             }
588         }                        
589         self.setSize(newSize);     
590     }, 0);
591 }