]> dev.renevier.net Git - syp.git/blob - js/syp.js
konqueror compatibility
[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         }, {
132             context: {
133                 height: function(feature) {
134                     var defaultHeight = SYP.Markers.HEIGHT || 32;
135                     var increase = 4 * (feature.attributes.count - 1);
136                     return Math.min(defaultHeight + increase, 50);
137                 }
138             }
139         });
140         var selectStyle = new OpenLayers.Style({
141             externalGraphic: this.Markers.SELECT_ICON,
142             graphicHeight: this.Markers.HEIGHT || 32 
143         });
144         var styleMap = new OpenLayers.StyleMap (
145                         {"default": defaultStyle,
146                          "select": selectStyle});
147
148         var layer = new OpenLayers.Layer.GML("KML", "items.php", 
149            {
150                strategies: [
151                 new OpenLayers.Strategy.Cluster()
152                 ],
153             styleMap: styleMap,
154             format: OpenLayers.Format.KML, 
155             projection: this.map.displayProjection,
156             eventListeners: { scope: this,
157                               loadend: this.dataLayerEndLoad
158                             }
159            });
160
161         return layer;
162     },
163
164     createSelectControl: function() {
165         var control = new OpenLayers.Control.SelectFeature(
166                                             this.dataLayer, {
167                                                onSelect: this.onFeatureSelect,
168                                                onUnselect: this.onFeatureUnselect,
169                                                toggle: true,
170                                                clickout: false
171                                                             });
172         return control;
173     },
174
175     dataLayerEndLoad: function() {
176         if (!this.checkForFeatures()) {
177             return;
178         }
179
180         var map = this.map;
181         if (map.getControlsByClass("OpenLayers.Control.ArgParser")[0].center
182             == null) { // map center was not set in ArgParser control.
183             var orig = this.Utils.mbr (this.dataLayer);
184             var centerBounds = new OpenLayers.Bounds();
185
186             var mapProj = map.getProjectionObject();
187             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
188
189             var bottomLeft = new OpenLayers.LonLat(orig[0],orig[1]);
190             bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
191             var topRight = new OpenLayers.LonLat(orig[2],orig[3])
192             topRight = topRight.transform(sypOrigProj, mapProj);
193
194             centerBounds.extend(bottomLeft);
195             centerBounds.extend(topRight);
196             map.zoomToExtent(centerBounds);
197         }
198     },
199
200     checkForFeatures: function() {
201         var features = this.dataLayer.features;
202         if (features.length == 0) {
203             var message = SypStrings.noImageRegistered;
204             this.Utils.displayUserMessage(message, "warn");
205         }
206         return !!features.length;
207     },
208
209     createPopup: function(position, contentHTML) {
210         var popup = new OpenLayers.Popup.Anchored("popup",
211                                                   position,
212                                                   null,
213                                                   contentHTML,
214                                                   null,
215                                                   true);
216         popup.autoSize = true;
217         popup.backgroundColor = ""; // deal with it in css
218         popup.border = ""; // deal with it in css
219         popup.closeOnMove = true;
220         return popup;
221     },
222
223     onFeatureUnselect: function (feature) {
224         var map = feature.layer.map;
225         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
226         if (permaControl[0]) {
227             permaControl[0].div.style.display = "";
228         }
229         if (!feature.popup) {
230             this.map.events.unregister("movestart", this, this._unselect);
231             return;
232         }
233         var popup = feature.popup;
234         if (popup.visible()) {
235             popup.hide();
236         }
237     },
238
239     onFeatureSelect: function(feature) {
240         var map = feature.layer.map;
241         if (feature.attributes.count > 1) {
242             this.unselect(feature);
243             var lonlat = new OpenLayers.LonLat(feature.geometry.x, feature.geometry.y);
244             map.setCenter(lonlat, map.zoom + 1);
245             return;
246         }
247         var permaControl = map.getControlsByClass("OpenLayers.Control.Permalink");
248         if (permaControl[0]) {
249             permaControl[0].div.style.display = "none";
250         }
251         var popup = feature.popup;
252
253         var popupPos = null;
254         switch (sypSettings.popupPos) {
255             case 0:
256                 popupPos = feature.geometry.getBounds().getCenterLonLat();
257             break;
258             case 1:
259                 popupPos = SYP.Utils.tlCorner(map, 8);
260             break;
261             case 2:
262                 popupPos = SYP.Utils.trCorner(map, 8);
263             break;
264             case 3:
265                 popupPos = SYP.Utils.brCorner(map, 8);
266             break;
267             case 4:
268                 popupPos = SYP.Utils.blCorner(map, 8);
269             break;
270             default:
271                 popupPos = SYP.Utils.brCorner(map, 8);
272            break;
273         }
274
275         // we cannot reuse popup; we need to recreate it in order for IE
276         // expressions to work. Otherwise, we get a 0x0 image on second view.
277         if (popup) {
278             popup.destroy();
279         }
280         var contentHTML;
281         if (feature.cluster[0].attributes.name) {
282             // escaping name is necessary because it's not enclosed in another html tag.
283             contentHTML = "<h2>" +
284                           SYP.Utils.escapeHTML(feature.cluster[0].attributes.name) +
285                           "</h2>" + 
286                           feature.cluster[0].attributes.description;
287         } else {
288             contentHTML = feature.cluster[0].attributes.description;
289         }
290         if (!contentHTML || !contentHTML.length) {
291             this.map.events.register("movestart", this, this._unselect = function () { this.unselect(feature)});
292             return;
293         }
294         popup = SYP.createPopup(popupPos, contentHTML);
295         var control = this;
296         popup.hide = function () {
297             OpenLayers.Element.hide(this.div);
298             control.unselectAll();
299         };
300         map.addPopup(popup);
301         feature.popup = popup;
302         var anchor = popup.div.getElementsByTagName("a")[0];
303         if (anchor) {
304             anchor.onclick = function() { 
305                 SYP.showBigImage(this.href);
306                 return false;
307             }
308         }
309     },
310
311     showBigImage: function (href) {
312         if (OpenLayers.Util.getBrowserName() == "msie") {
313             document.getElementById('bigimg_container').style.display = "block";
314         } else {
315             document.getElementById('bigimg_container').style.display = "table";
316         }
317
318         var maxHeight = document.body.clientHeight * 0.9;
319         var maxWidth = document.body.clientWidth * 0.9;
320         document.getElementById('bigimg').style.height = "";
321         document.getElementById('bigimg').style.width = "";
322         document.getElementById('bigimg').style.maxHeight = maxHeight + "px";
323         document.getElementById('bigimg').style.maxWidth = maxWidth + "px";
324         document.getElementById('bigimg').onload = function () {
325             var heightRatio = this.clientHeight / parseInt(this.style.maxHeight);
326             var widthRatio = this.clientWidth / parseInt(this.style.maxWidth);
327             if (heightRatio > 1 || widthRatio > 1) {
328                 if (heightRatio > widthRatio) {
329                     this.style.height = this.style.maxHeight;
330                 } else {
331                     this.style.width = this.style.maxWidth;
332                 }
333             }
334
335             var offsetTop = this.offsetTop;
336             var offsetLeft = this.offsetLeft;
337             var par = this.offsetParent;
338             var ismsie = OpenLayers.Util.getBrowserName() == "msie";
339             while (par && !ismsie) {
340                 offsetTop += par.offsetTop;
341                 offsetLeft += par.offsetLeft;
342                 par = par.offsetParent;
343             }
344             var icon = document.getElementById('bigimg_close');
345             icon.style.top = offsetTop;
346             icon.style.left = offsetLeft + this.clientWidth - icon.clientWidth;
347
348         };
349         document.getElementById('bigimg').src = href;
350     },
351
352     closeBigImage: function() {
353         document.getElementById('bigimg').src = "";
354         document.getElementById('bigimg').parentNode.innerHTML = document.getElementById('bigimg').parentNode.innerHTML;
355         document.getElementById('bigimg_container').style.display = "none";
356     },
357
358     Utils: {
359         tlCorner: function(map, margin) {
360             var bounds = map.calculateBounds();
361             var corner = new OpenLayers.LonLat(bounds.left, bounds.top);
362             var cornerAsPx = map.getPixelFromLonLat(corner);
363             cornerAsPx = cornerAsPx.add( +margin, +margin);
364             return map.getLonLatFromPixel(cornerAsPx);
365         },
366
367         trCorner: function(map, margin) {
368             var bounds = map.calculateBounds();
369             var corner = new OpenLayers.LonLat(bounds.right, bounds.top);
370             var cornerAsPx = map.getPixelFromLonLat(corner);
371             cornerAsPx = cornerAsPx.add( -margin, +margin);
372             return map.getLonLatFromPixel(cornerAsPx);
373         },
374
375         brCorner: function(map, margin) {
376             var bounds = map.calculateBounds();
377             var corner = new OpenLayers.LonLat(bounds.right, bounds.bottom);
378             var cornerAsPx = map.getPixelFromLonLat(corner);
379             cornerAsPx = cornerAsPx.add( -margin, -margin);
380             return map.getLonLatFromPixel(cornerAsPx);
381         },
382
383         blCorner: function(map, margin) {
384             var bounds = map.calculateBounds();
385             var corner = new OpenLayers.LonLat(bounds.left, bounds.bottom);
386             var cornerAsPx = map.getPixelFromLonLat(corner);
387             cornerAsPx = cornerAsPx.add( +margin, -margin);
388             return map.getLonLatFromPixel(cornerAsPx);
389         },
390
391         /* minimum bounds rectangle containing all feature locations.
392          * FIXME: if two features are close, but separated by 180th meridian,
393          * their mbr will span the whole earth. Actually, 179° lon and -170°
394          * lon are considerated very near.
395          */
396         mbr: function (layer) {
397             var features = [];
398             var map = layer.map;
399
400             var mapProj = map.getProjectionObject();
401             var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
402
403             for (var i =0; i < layer.features.length; i++) {
404                 if (layer.features[i].cluster) {
405                     features = features.concat(layer.features[i].cluster);
406                 } else {
407                     features = features.concat(layer.features);
408                 }
409             }
410
411             var minlon = 180;
412             var minlat = 88;
413             var maxlon = -180;
414             var maxlat = -88;
415
416             if (features.length == 0) {
417                 // keep default values
418             } else if (features.length == 1) {
419                 // in case there's only one feature, we show an area of at least 
420                 // 4 x 4 degrees
421                 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
422                 var lonlat = pos.transform(mapProj, sypOrigProj);
423
424                 minlon = Math.max (lonlat.lon - 2, -180);
425                 maxlon = Math.min (lonlat.lon + 2, 180);
426                 minlat = Math.max (lonlat.lat - 2, -90);
427                 maxlat = Math.min (lonlat.lat + 2, 90);
428             } else {
429                 for (var i = 0; i < features.length; i++) {
430                     var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
431                     var lonlat = pos.transform(mapProj, sypOrigProj);
432                     minlon = Math.min (lonlat.lon, minlon);
433                     minlat = Math.min (lonlat.lat, minlat);
434                     maxlon = Math.max (lonlat.lon, maxlon);
435                     maxlat = Math.max (lonlat.lat, maxlat);
436                 }
437             }
438
439             return [minlon, minlat, maxlon, maxlat];
440
441         },
442
443         displayUserMessage: function(message, status) {
444             var div = document.getElementById('message');
445             while (div.firstChild)
446                 div.removeChild(div.firstChild);
447             var textNode = document.createTextNode(message);
448             switch (status) {
449                 case "error":
450                     div.style.color = "red";
451                     break;
452                 case "warn":
453                     div.style.color = "#FF8C00";
454                     break;
455                 case "success":
456                     div.style.color = "green";
457                     break;
458                 default:
459                     div.style.color = "black";
460                     break;
461             }
462             div.style.display = "block";
463             div.appendChild(textNode);
464         },
465
466         escapeHTML: function (str) {
467             if (!str) {
468                 return "";
469             }
470             return str.
471              replace(/&/gm, '&amp;').
472              replace(/'/gm, '&#39;').
473              replace(/"/gm, '&quot;').
474              replace(/>/gm, '&gt;').
475              replace(/</gm, '&lt;');
476         }
477     }
478 };
479
480 // if possible, determine language with HTTP_ACCEPT_LANGUAGE instead of
481 // navigator.language
482 if (OpenLayers.Lang[SypStrings.language]) {
483     OpenLayers.Lang.setCode(SypStrings.language);
484 }
485
486 // avoid alerts
487 OpenLayers.Console.userError = function(error) { 
488     SYP.Utils.displayUserMessage(error, "error");
489 }
490
491 // sometimes, especially when cache is clear, firefox does not compute
492 // correctly popup size. That's because at the end of getRenderedDimensions,
493 // dimensions of image is not known. Then, popup size is too small for its
494 // content. We work around the problem by checking that computed size is at
495 // least as big as content. To achieve that, we need to override
496 // OpenLayers.Popup.Anchored.prototype.updateSize to modify it slightly.
497 OpenLayers.Popup.Anchored.prototype.updateSize = function() {
498     var self = this;
499
500     window.setTimeout(function() { // timeout added by SYP
501
502         // determine actual render dimensions of the contents by putting its
503         // contents into a fake contentDiv (for the CSS) and then measuring it
504         var preparedHTML = "<div class='" + self.contentDisplayClass+ "'>" + 
505             self.contentDiv.innerHTML + 
506             "</div>";
507
508         var containerElement = (self.map) ? self.map.layerContainerDiv
509                                           : document.body;
510         var realSize = OpenLayers.Util.getRenderedDimensions(
511             preparedHTML, null, {
512                 displayClass: self.displayClass,
513                 containerElement: containerElement
514             }
515         );
516
517         /*
518          * XXX: next four lines are added by SYP!
519          */
520         if (self.contentDiv) {
521             realSize.w = Math.max (realSize.w, self.contentDiv.scrollWidth);
522             realSize.h = Math.max (realSize.h, self.contentDiv.scrollHeight);
523         }
524
525         // is the "real" size of the div is safe to display in our map?
526         var safeSize = self.getSafeContentSize(realSize);
527
528         var newSize = null;
529         if (safeSize.equals(realSize)) {
530             //real size of content is small enough to fit on the map, 
531             // so we use real size.
532             newSize = realSize;
533
534         } else {
535
536             //make a new OL.Size object with the clipped dimensions 
537             // set or null if not clipped.
538             var fixedSize = new OpenLayers.Size();
539             fixedSize.w = (safeSize.w < realSize.w) ? safeSize.w : null;
540             fixedSize.h = (safeSize.h < realSize.h) ? safeSize.h : null;
541
542             if (fixedSize.w && fixedSize.h) {
543                 //content is too big in both directions, so we will use 
544                 // max popup size (safeSize), knowing well that it will 
545                 // overflow both ways.                
546                 newSize = safeSize;
547             } else {
548                 //content is clipped in only one direction, so we need to 
549                 // run getRenderedDimensions() again with a fixed dimension
550                 var clippedSize = OpenLayers.Util.getRenderedDimensions(
551                     preparedHTML, fixedSize, {
552                         displayClass: self.contentDisplayClass,
553                         containerElement: containerElement
554                     }
555                 );
556
557                 //if the clipped size is still the same as the safeSize, 
558                 // that means that our content must be fixed in the 
559                 // offending direction. If overflow is 'auto', this means 
560                 // we are going to have a scrollbar for sure, so we must 
561                 // adjust for that.
562                 //
563                 var currentOverflow = OpenLayers.Element.getStyle(
564                     self.contentDiv, "overflow"
565                 );
566                 if ( (currentOverflow != "hidden") && 
567                      (clippedSize.equals(safeSize)) ) {
568                     var scrollBar = OpenLayers.Util.getScrollbarWidth();
569                     if (fixedSize.w) {
570                         clippedSize.h += scrollBar;
571                     } else {
572                         clippedSize.w += scrollBar;
573                     }
574                 }
575
576                 newSize = self.getSafeContentSize(clippedSize);
577             }
578         }                        
579         self.setSize(newSize);     
580     }, 0);
581 }