1 /* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
2 * license. See http://svn.openlayers.org/trunk/openlayers/license.txt for the
3 * full text of the license. */
6 * @requires OpenLayers/Console.js
15 * Function: getElement
16 * This is the old $() from prototype
18 OpenLayers.Util.getElement = function() {
21 for (var i=0, len=arguments.length; i<len; i++) {
22 var element = arguments[i];
23 if (typeof element == 'string') {
24 element = document.getElementById(element);
26 if (arguments.length == 1) {
29 elements.push(element);
35 * Maintain existing definition of $.
37 if(typeof window.$ === "undefined") {
38 window.$ = OpenLayers.Util.getElement;
43 * Copy all properties of a source object to a destination object. Modifies
44 * the passed in destination object. Any properties on the source object
45 * that are set to undefined will not be (re)set on the destination object.
48 * destination - {Object} The object that will be modified
49 * source - {Object} The object with properties to be set on the destination
52 * {Object} The destination object.
54 OpenLayers.Util.extend = function(destination, source) {
55 destination = destination || {};
57 for(var property in source) {
58 var value = source[property];
59 if(value !== undefined) {
60 destination[property] = value;
65 * IE doesn't include the toString property when iterating over an object's
66 * properties with the for(property in object) syntax. Explicitly check if
67 * the source has its own toString property.
71 * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative
72 * prototype object" when calling hawOwnProperty if the source object
73 * is an instance of window.Event.
76 var sourceIsEvt = typeof window.Event == "function"
77 && source instanceof window.Event;
80 && source.hasOwnProperty && source.hasOwnProperty('toString')) {
81 destination.toString = source.toString;
89 * Function: removeItem
90 * Remove an object from an array. Iterates through the array
91 * to find the item, then removes it.
98 * {Array} A reference to the array
100 OpenLayers.Util.removeItem = function(array, item) {
101 for(var i = array.length - 1; i >= 0; i--) {
102 if(array[i] == item) {
104 //break;more than once??
111 * Function: clearArray
112 * *Deprecated*. This function will disappear in 3.0.
113 * Please use "array.length = 0" instead.
118 OpenLayers.Util.clearArray = function(array) {
119 OpenLayers.Console.warn(
121 "methodDeprecated", {'newMethod': 'array = []'}
129 * Seems to exist already in FF, but not in MOZ.
136 * {Integer} The index at, which the object was found in the array.
137 * If not found, returns -1.
139 OpenLayers.Util.indexOf = function(array, obj) {
141 for(var i=0, len=array.length; i<len; i++) {
142 if (array[i] == obj) {
152 * Function: modifyDOMElement
154 * Modifies many properties of a DOM element all at once. Passing in
155 * null to an individual parameter will avoid setting the attribute.
158 * id - {String} The element id attribute to set.
159 * px - {<OpenLayers.Pixel>} The left and top style position.
160 * sz - {<OpenLayers.Size>} The width and height style attributes.
161 * position - {String} The position attribute. eg: absolute,
163 * border - {String} The style.border attribute. eg:
165 * overflow - {String} The style.overview attribute.
166 * opacity - {Float} Fractional value (0.0 - 1.0)
168 OpenLayers.Util.modifyDOMElement = function(element, id, px, sz, position,
169 border, overflow, opacity) {
175 element.style.left = px.x + "px";
176 element.style.top = px.y + "px";
179 element.style.width = sz.w + "px";
180 element.style.height = sz.h + "px";
183 element.style.position = position;
186 element.style.border = border;
189 element.style.overflow = overflow;
191 if (parseFloat(opacity) >= 0.0 && parseFloat(opacity) < 1.0) {
192 element.style.filter = 'alpha(opacity=' + (opacity * 100) + ')';
193 element.style.opacity = opacity;
194 } else if (parseFloat(opacity) == 1.0) {
195 element.style.filter = '';
196 element.style.opacity = '';
201 * Function: createDiv
202 * Creates a new div and optionally set some standard attributes.
203 * Null may be passed to each parameter if you do not wish to
204 * set a particular attribute.
205 * Note - zIndex is NOT set on the resulting div.
208 * id - {String} An identifier for this element. If no id is
209 * passed an identifier will be created
211 * px - {<OpenLayers.Pixel>} The element left and top position.
212 * sz - {<OpenLayers.Size>} The element width and height.
213 * imgURL - {String} A url pointing to an image to use as a
215 * position - {String} The style.position value. eg: absolute,
217 * border - {String} The the style.border value.
218 * eg: 2px solid black
219 * overflow - {String} The style.overflow value. Eg. hidden
220 * opacity - {Float} Fractional value (0.0 - 1.0)
223 * {DOMElement} A DOM Div created with the specified attributes.
225 OpenLayers.Util.createDiv = function(id, px, sz, imgURL, position,
226 border, overflow, opacity) {
228 var dom = document.createElement('div');
231 dom.style.backgroundImage = 'url(' + imgURL + ')';
234 //set generic properties
236 id = OpenLayers.Util.createUniqueID("OpenLayersDiv");
239 position = "absolute";
241 OpenLayers.Util.modifyDOMElement(dom, id, px, sz, position,
242 border, overflow, opacity);
248 * Function: createImage
249 * Creates an img element with specific attribute values.
252 * id - {String} The id field for the img. If none assigned one will be
253 * automatically generated.
254 * px - {<OpenLayers.Pixel>} The left and top positions.
255 * sz - {<OpenLayers.Size>} The style.width and style.height values.
256 * imgURL - {String} The url to use as the image source.
257 * position - {String} The style.position value.
258 * border - {String} The border to place around the image.
259 * opacity - {Float} Fractional value (0.0 - 1.0)
260 * delayDisplay - {Boolean} If true waits until the image has been
264 * {DOMElement} A DOM Image created with the specified attributes.
266 OpenLayers.Util.createImage = function(id, px, sz, imgURL, position, border,
267 opacity, delayDisplay) {
269 var image = document.createElement("img");
271 //set generic properties
273 id = OpenLayers.Util.createUniqueID("OpenLayersDiv");
276 position = "relative";
278 OpenLayers.Util.modifyDOMElement(image, id, px, sz, position,
279 border, null, opacity);
282 image.style.display = "none";
283 OpenLayers.Event.observe(image, "load",
284 OpenLayers.Function.bind(OpenLayers.Util.onImageLoad, image));
285 OpenLayers.Event.observe(image, "error",
286 OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError, image));
290 //set special properties
291 image.style.alt = id;
292 image.galleryImg = "no";
303 * Function: setOpacity
304 * *Deprecated*. This function has been deprecated. Instead, please use
305 * <OpenLayers.Util.modifyDOMElement>
307 * <OpenLayers.Util.modifyAlphaImageDiv>
309 * Set the opacity of a DOM Element
310 * Note that for this function to work in IE, elements must "have layout"
312 * http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/haslayout.asp
315 * element - {DOMElement} Set the opacity on this DOM element
316 * opacity - {Float} Opacity value (0.0 - 1.0)
318 OpenLayers.Util.setOpacity = function(element, opacity) {
319 OpenLayers.Util.modifyDOMElement(element, null, null, null,
320 null, null, null, opacity);
324 * Function: onImageLoad
325 * Bound to image load events. For all images created with <createImage> or
326 * <createAlphaImageDiv>, this function will be bound to the load event.
328 OpenLayers.Util.onImageLoad = function() {
329 // The complex check here is to solve issues described in #480.
330 // Every time a map view changes, it increments the 'viewRequestID'
331 // property. As the requests for the images for the new map view are sent
332 // out, they are tagged with this unique viewRequestID.
334 // If an image has no viewRequestID property set, we display it regardless,
335 // but if it does have a viewRequestID property, we check that it matches
336 // the viewRequestID set on the map.
338 // If the viewRequestID on the map has changed, that means that the user
339 // has changed the map view since this specific request was sent out, and
340 // therefore this tile does not need to be displayed (so we do not execute
341 // this code that turns its display on).
343 if (!this.viewRequestID ||
344 (this.map && this.viewRequestID == this.map.viewRequestID)) {
345 this.style.backgroundColor ="transparent";
346 this.style.display = "";
351 * Property: onImageLoadErrorColor
352 * {String} The color tiles with load errors will turn.
355 OpenLayers.Util.onImageLoadErrorColor = "pink";
358 * Property: IMAGE_RELOAD_ATTEMPTS
359 * {Integer} How many times should we try to reload an image before giving up?
362 OpenLayers.IMAGE_RELOAD_ATTEMPTS = 0;
365 * Function: onImageLoadError
367 OpenLayers.Util.onImageLoadError = function() {
368 this._attempts = (this._attempts) ? (this._attempts + 1) : 1;
369 if (this._attempts <= OpenLayers.IMAGE_RELOAD_ATTEMPTS) {
370 var urls = this.urls;
371 if (urls && urls instanceof Array && urls.length > 1){
372 var src = this.src.toString();
374 for (k = 0; current_url = urls[k]; k++){
375 if(src.indexOf(current_url) != -1){
379 var guess = Math.floor(urls.length * Math.random());
380 var new_url = urls[guess];
382 while(new_url == current_url && k++ < 4){
383 guess = Math.floor(urls.length * Math.random());
384 new_url = urls[guess];
386 this.src = src.replace(current_url, new_url);
391 this.style.backgroundColor = OpenLayers.Util.onImageLoadErrorColor;
393 this.style.display = "";
397 * Property: alphaHackNeeded
398 * {Boolean} true if the png alpha hack is necessary and possible, false otherwise.
400 OpenLayers.Util.alphaHackNeeded = null;
403 * Function: alphaHack
404 * Checks whether it's necessary (and possible) to use the png alpha
405 * hack which allows alpha transparency for png images under Internet
409 * {Boolean} true if the png alpha hack is necessary and possible, false otherwise.
411 OpenLayers.Util.alphaHack = function() {
412 if (OpenLayers.Util.alphaHackNeeded == null) {
413 var arVersion = navigator.appVersion.split("MSIE");
414 var version = parseFloat(arVersion[1]);
417 // IEs4Lin dies when trying to access document.body.filters, because
418 // the property is there, but requires a DLL that can't be provided. This
419 // means that we need to wrap this in a try/catch so that this can
423 filter = !!(document.body.filters);
426 OpenLayers.Util.alphaHackNeeded = (filter &&
427 (version >= 5.5) && (version < 7));
429 return OpenLayers.Util.alphaHackNeeded;
433 * Function: modifyAlphaImageDiv
435 * div - {DOMElement} Div containing Alpha-adjusted Image
437 * px - {<OpenLayers.Pixel>}
438 * sz - {<OpenLayers.Size>}
440 * position - {String}
442 * sizing {String} 'crop', 'scale', or 'image'. Default is "scale"
443 * opacity - {Float} Fractional value (0.0 - 1.0)
445 OpenLayers.Util.modifyAlphaImageDiv = function(div, id, px, sz, imgURL,
446 position, border, sizing,
449 OpenLayers.Util.modifyDOMElement(div, id, px, sz, position,
450 null, null, opacity);
452 var img = div.childNodes[0];
457 OpenLayers.Util.modifyDOMElement(img, div.id + "_innerImage", null, sz,
460 if (OpenLayers.Util.alphaHack()) {
461 if(div.style.display != "none") {
462 div.style.display = "inline-block";
464 if (sizing == null) {
468 div.style.filter = "progid:DXImageTransform.Microsoft" +
469 ".AlphaImageLoader(src='" + img.src + "', " +
470 "sizingMethod='" + sizing + "')";
471 if (parseFloat(div.style.opacity) >= 0.0 &&
472 parseFloat(div.style.opacity) < 1.0) {
473 div.style.filter += " alpha(opacity=" + div.style.opacity * 100 + ")";
476 img.style.filter = "alpha(opacity=0)";
481 * Function: createAlphaImageDiv
484 * px - {<OpenLayers.Pixel>}
485 * sz - {<OpenLayers.Size>}
487 * position - {String}
489 * sizing - {String} 'crop', 'scale', or 'image'. Default is "scale"
490 * opacity - {Float} Fractional value (0.0 - 1.0)
491 * delayDisplay - {Boolean} If true waits until the image has been
495 * {DOMElement} A DOM Div created with a DOM Image inside it. If the hack is
496 * needed for transparency in IE, it is added.
498 OpenLayers.Util.createAlphaImageDiv = function(id, px, sz, imgURL,
499 position, border, sizing,
500 opacity, delayDisplay) {
502 var div = OpenLayers.Util.createDiv();
503 var img = OpenLayers.Util.createImage(null, null, null, null, null, null,
505 div.appendChild(img);
508 img.style.display = "none";
509 OpenLayers.Event.observe(img, "load",
510 OpenLayers.Function.bind(OpenLayers.Util.onImageLoad, div));
511 OpenLayers.Event.observe(img, "error",
512 OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError, div));
515 OpenLayers.Util.modifyAlphaImageDiv(div, id, px, sz, imgURL, position,
516 border, sizing, opacity);
523 * Function: upperCaseObject
524 * Creates a new hashtable and copies over all the keys from the
525 * passed-in object, but storing them under an uppercased
526 * version of the key at which they were stored.
532 * {Object} A new Object with all the same keys but uppercased
534 OpenLayers.Util.upperCaseObject = function (object) {
536 for (var key in object) {
537 uObject[key.toUpperCase()] = object[key];
543 * Function: applyDefaults
544 * Takes an object and copies any properties that don't exist from
545 * another properties, by analogy with OpenLayers.Util.extend() from
549 * to - {Object} The destination object.
550 * from - {Object} The source object. Any properties of this object that
551 * are undefined in the to object will be set on the to object.
554 * {Object} A reference to the to object. Note that the to argument is modified
555 * in place and returned by this function.
557 OpenLayers.Util.applyDefaults = function (to, from) {
560 * FF/Windows < 2.0.0.13 reports "Illegal operation on WrappedNative
561 * prototype object" when calling hawOwnProperty if the source object is an
562 * instance of window.Event.
564 var fromIsEvt = typeof window.Event == "function"
565 && from instanceof window.Event;
567 for (var key in from) {
568 if (to[key] === undefined ||
569 (!fromIsEvt && from.hasOwnProperty
570 && from.hasOwnProperty(key) && !to.hasOwnProperty(key))) {
575 * IE doesn't include the toString property when iterating over an object's
576 * properties with the for(property in object) syntax. Explicitly check if
577 * the source has its own toString property.
579 if(!fromIsEvt && from && from.hasOwnProperty
580 && from.hasOwnProperty('toString') && !to.hasOwnProperty('toString')) {
581 to.toString = from.toString;
588 * Function: getParameterString
594 * {String} A concatenation of the properties of an object in
595 * http parameter notation.
596 * (ex. <i>"key1=value1&key2=value2&key3=value3"</i>)
597 * If a parameter is actually a list, that parameter will then
598 * be set to a comma-seperated list of values (foo,bar) instead
599 * of being URL escaped (foo%3Abar).
601 OpenLayers.Util.getParameterString = function(params) {
602 var paramsArray = [];
604 for (var key in params) {
605 var value = params[key];
606 if ((value != null) && (typeof value != 'function')) {
608 if (typeof value == 'object' && value.constructor == Array) {
609 /* value is an array; encode items and separate with "," */
610 var encodedItemArray = [];
611 for (var itemIndex=0, len=value.length; itemIndex<len; itemIndex++) {
612 encodedItemArray.push(encodeURIComponent(value[itemIndex]));
614 encodedValue = encodedItemArray.join(",");
617 /* value is a string; simply encode */
618 encodedValue = encodeURIComponent(value);
620 paramsArray.push(encodeURIComponent(key) + "=" + encodedValue);
624 return paramsArray.join("&");
629 * {String} Default is ''.
631 OpenLayers.ImgPath = '';
634 * Function: getImagesLocation
637 * {String} The fully formatted image location string
639 OpenLayers.Util.getImagesLocation = function() {
640 return OpenLayers.ImgPath || (OpenLayers._getScriptLocation() + "img/");
646 * Execute functions until one of them doesn't throw an error.
647 * Capitalized because "try" is a reserved word in JavaScript.
648 * Taken directly from OpenLayers.Util.Try()
651 * [*] - {Function} Any number of parameters may be passed to Try()
652 * It will attempt to execute each of them until one of them
653 * successfully executes.
654 * If none executes successfully, returns null.
657 * {*} The value returned by the first successfully executed function.
659 OpenLayers.Util.Try = function() {
660 var returnValue = null;
662 for (var i=0, len=arguments.length; i<len; i++) {
663 var lambda = arguments[i];
665 returnValue = lambda();
677 * These could/should be made namespace aware?
686 OpenLayers.Util.getNodes=function(p, tagName) {
687 var nodes = OpenLayers.Util.Try(
689 return OpenLayers.Util._getNodes(p.documentElement.childNodes,
693 return OpenLayers.Util._getNodes(p.childNodes, tagName);
700 * Function: _getNodes
709 OpenLayers.Util._getNodes=function(nodes, tagName) {
711 for (var i=0, len=nodes.length; i<len; i++) {
712 if (nodes[i].nodeName==tagName) {
713 retArray.push(nodes[i]);
723 * Function: getTagText
733 OpenLayers.Util.getTagText = function (parent, item, index) {
734 var result = OpenLayers.Util.getNodes(parent, item);
735 if (result && (result.length > 0))
740 if (result[index].childNodes.length > 1) {
741 return result.childNodes[1].nodeValue;
743 else if (result[index].childNodes.length == 1) {
744 return result[index].firstChild.nodeValue;
752 * Function: getXmlNodeValue
758 * {String} The text value of the given node, without breaking in firefox or IE
760 OpenLayers.Util.getXmlNodeValue = function(node) {
766 val = node.textContent;
769 val = node.firstChild.nodeValue;
773 val = node.textContent;
779 * Function: mouseLeft
783 * div - {HTMLDivElement}
788 OpenLayers.Util.mouseLeft = function (evt, div) {
789 // start with the element to which the mouse has moved
790 var target = (evt.relatedTarget) ? evt.relatedTarget : evt.toElement;
791 // walk up the DOM tree.
792 while (target != div && target != null) {
793 target = target.parentNode;
795 // if the target we stop at isn't the div, then we've left the div.
796 return (target != div);
800 * Property: precision
801 * {Number} The number of significant digits to retain to avoid
802 * floating point precision errors.
804 * We use 14 as a "safe" default because, although IEEE 754 double floats
805 * (standard on most modern operating systems) support up to about 16
806 * significant digits, 14 significant digits are sufficient to represent
807 * sub-millimeter accuracy in any coordinate system that anyone is likely to
808 * use with OpenLayers.
810 * If DEFAULT_PRECISION is set to 0, the original non-truncating behavior
811 * of OpenLayers <2.8 is preserved. Be aware that this will cause problems
812 * with certain projections, e.g. spherical Mercator.
815 OpenLayers.Util.DEFAULT_PRECISION = 14;
819 * Convenience method to cast an object to a Number, rounded to the
820 * desired floating point precision.
823 * number - {Number} The number to cast and round.
824 * precision - {Number} An integer suitable for use with
825 * Number.toPrecision(). Defaults to OpenLayers.Util.DEFAULT_PRECISION.
826 * If set to 0, no rounding is performed.
829 * {Number} The cast, rounded number.
831 OpenLayers.Util.toFloat = function (number, precision) {
832 if (precision == null) {
833 precision = OpenLayers.Util.DEFAULT_PRECISION;
836 if (precision == 0) {
837 number = parseFloat(number);
839 number = parseFloat(parseFloat(number).toPrecision(precision));
853 OpenLayers.Util.rad = function(x) {return x*Math.PI/180;};
856 * Function: distVincenty
857 * Given two objects representing points with geographic coordinates, this
858 * calculates the distance between those points on the surface of an
862 * p1 - {<OpenLayers.LonLat>} (or any object with both .lat, .lon properties)
863 * p2 - {<OpenLayers.LonLat>} (or any object with both .lat, .lon properties)
866 * {Float} The distance (in km) between the two input points as measured on an
867 * ellipsoid. Note that the input point objects must be in geographic
868 * coordinates (decimal degrees) and the return distance is in kilometers.
870 OpenLayers.Util.distVincenty=function(p1, p2) {
871 var a = 6378137, b = 6356752.3142, f = 1/298.257223563;
872 var L = OpenLayers.Util.rad(p2.lon - p1.lon);
873 var U1 = Math.atan((1-f) * Math.tan(OpenLayers.Util.rad(p1.lat)));
874 var U2 = Math.atan((1-f) * Math.tan(OpenLayers.Util.rad(p2.lat)));
875 var sinU1 = Math.sin(U1), cosU1 = Math.cos(U1);
876 var sinU2 = Math.sin(U2), cosU2 = Math.cos(U2);
877 var lambda = L, lambdaP = 2*Math.PI;
879 while (Math.abs(lambda-lambdaP) > 1e-12 && --iterLimit>0) {
880 var sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda);
881 var sinSigma = Math.sqrt((cosU2*sinLambda) * (cosU2*sinLambda) +
882 (cosU1*sinU2-sinU1*cosU2*cosLambda) * (cosU1*sinU2-sinU1*cosU2*cosLambda));
884 return 0; // co-incident points
886 var cosSigma = sinU1*sinU2 + cosU1*cosU2*cosLambda;
887 var sigma = Math.atan2(sinSigma, cosSigma);
888 var alpha = Math.asin(cosU1 * cosU2 * sinLambda / sinSigma);
889 var cosSqAlpha = Math.cos(alpha) * Math.cos(alpha);
890 var cos2SigmaM = cosSigma - 2*sinU1*sinU2/cosSqAlpha;
891 var C = f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));
893 lambda = L + (1-C) * f * Math.sin(alpha) *
894 (sigma + C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));
897 return NaN; // formula failed to converge
899 var uSq = cosSqAlpha * (a*a - b*b) / (b*b);
900 var A = 1 + uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));
901 var B = uSq/1024 * (256+uSq*(-128+uSq*(74-47*uSq)));
902 var deltaSigma = B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
903 B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));
904 var s = b*A*(sigma-deltaSigma);
905 var d = s.toFixed(3)/1000; // round to 1mm precision
910 * Function: getParameters
911 * Parse the parameters from a URL or from the current page itself into a
912 * JavaScript Object. Note that parameter values with commas are separated
916 * url - {String} Optional url used to extract the query string.
917 * If null, query string is taken from page location.
920 * {Object} An object of key/value pairs from the query string.
922 OpenLayers.Util.getParameters = function(url) {
923 // if no url specified, take it from the location bar
924 url = url || window.location.href;
926 //parse out parameters portion of url string
927 var paramsString = "";
928 if (OpenLayers.String.contains(url, '?')) {
929 var start = url.indexOf('?') + 1;
930 var end = OpenLayers.String.contains(url, "#") ?
931 url.indexOf('#') : url.length;
932 paramsString = url.substring(start, end);
936 var pairs = paramsString.split(/[&;]/);
937 for(var i=0, len=pairs.length; i<len; ++i) {
938 var keyValue = pairs[i].split('=');
940 var key = decodeURIComponent(keyValue[0]);
941 var value = keyValue[1] || ''; //empty string if no value
943 //decode individual values
944 value = value.split(",");
945 for(var j=0, jlen=value.length; j<jlen; j++) {
946 value[j] = decodeURIComponent(value[j]);
949 //if there's only one value, do not return as array
950 if (value.length == 1) {
954 parameters[key] = value;
962 * *Deprecated*. Will be removed in 3.0. Please use instead
963 * <OpenLayers.Util.getParameters>
966 * url - {String} Optional url used to extract the query string.
967 * If null, query string is taken from page location.
970 * {Object} An object of key/value pairs from the query string.
972 OpenLayers.Util.getArgs = function(url) {
973 OpenLayers.Console.warn(
975 "methodDeprecated", {'newMethod': 'OpenLayers.Util.getParameters'}
978 return OpenLayers.Util.getParameters(url);
982 * Property: lastSeqID
983 * {Integer} The ever-incrementing count variable.
984 * Used for generating unique ids.
986 OpenLayers.Util.lastSeqID = 0;
989 * Function: createUniqueID
990 * Create a unique identifier for this session. Each time this function
991 * is called, a counter is incremented. The return will be the optional
992 * prefix (defaults to "id_") appended with the counter value.
995 * prefix {String} Optionsal string to prefix unique id. Default is "id_".
998 * {String} A unique id string, built on the passed in prefix.
1000 OpenLayers.Util.createUniqueID = function(prefix) {
1001 if (prefix == null) {
1004 OpenLayers.Util.lastSeqID += 1;
1005 return prefix + OpenLayers.Util.lastSeqID;
1009 * Constant: INCHES_PER_UNIT
1010 * {Object} Constant inches per unit -- borrowed from MapServer mapscale.c
1011 * derivation of nautical miles from http://en.wikipedia.org/wiki/Nautical_mile
1012 * Includes the full set of units supported by CS-MAP (http://trac.osgeo.org/csmap/)
1013 * and PROJ.4 (http://trac.osgeo.org/proj/)
1014 * The hardcoded table is maintain in a CS-MAP source code module named CSdataU.c
1015 * The hardcoded table of PROJ.4 units are in pj_units.c.
1017 OpenLayers.INCHES_PER_UNIT = {
1026 OpenLayers.INCHES_PER_UNIT["in"]= OpenLayers.INCHES_PER_UNIT.inches;
1027 OpenLayers.INCHES_PER_UNIT["degrees"] = OpenLayers.INCHES_PER_UNIT.dd;
1028 OpenLayers.INCHES_PER_UNIT["nmi"] = 1852 * OpenLayers.INCHES_PER_UNIT.m;
1030 // Units from CS-Map
1031 OpenLayers.METERS_PER_INCH = 0.02540005080010160020;
1032 OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, {
1033 "Inch": OpenLayers.INCHES_PER_UNIT.inches,
1034 "Meter": 1.0 / OpenLayers.METERS_PER_INCH, //EPSG:9001
1035 "Foot": 0.30480060960121920243 / OpenLayers.METERS_PER_INCH, //EPSG:9003
1036 "IFoot": 0.30480000000000000000 / OpenLayers.METERS_PER_INCH, //EPSG:9002
1037 "ClarkeFoot": 0.3047972651151 / OpenLayers.METERS_PER_INCH, //EPSG:9005
1038 "SearsFoot": 0.30479947153867624624 / OpenLayers.METERS_PER_INCH, //EPSG:9041
1039 "GoldCoastFoot": 0.30479971018150881758 / OpenLayers.METERS_PER_INCH, //EPSG:9094
1040 "IInch": 0.02540000000000000000 / OpenLayers.METERS_PER_INCH,
1041 "MicroInch": 0.00002540000000000000 / OpenLayers.METERS_PER_INCH,
1042 "Mil": 0.00000002540000000000 / OpenLayers.METERS_PER_INCH,
1043 "Centimeter": 0.01000000000000000000 / OpenLayers.METERS_PER_INCH,
1044 "Kilometer": 1000.00000000000000000000 / OpenLayers.METERS_PER_INCH, //EPSG:9036
1045 "Yard": 0.91440182880365760731 / OpenLayers.METERS_PER_INCH,
1046 "SearsYard": 0.914398414616029 / OpenLayers.METERS_PER_INCH, //EPSG:9040
1047 "IndianYard": 0.91439853074444079983 / OpenLayers.METERS_PER_INCH, //EPSG:9084
1048 "IndianYd37": 0.91439523 / OpenLayers.METERS_PER_INCH, //EPSG:9085
1049 "IndianYd62": 0.9143988 / OpenLayers.METERS_PER_INCH, //EPSG:9086
1050 "IndianYd75": 0.9143985 / OpenLayers.METERS_PER_INCH, //EPSG:9087
1051 "IndianFoot": 0.30479951 / OpenLayers.METERS_PER_INCH, //EPSG:9080
1052 "IndianFt37": 0.30479841 / OpenLayers.METERS_PER_INCH, //EPSG:9081
1053 "IndianFt62": 0.3047996 / OpenLayers.METERS_PER_INCH, //EPSG:9082
1054 "IndianFt75": 0.3047995 / OpenLayers.METERS_PER_INCH, //EPSG:9083
1055 "Mile": 1609.34721869443738887477 / OpenLayers.METERS_PER_INCH,
1056 "IYard": 0.91440000000000000000 / OpenLayers.METERS_PER_INCH, //EPSG:9096
1057 "IMile": 1609.34400000000000000000 / OpenLayers.METERS_PER_INCH, //EPSG:9093
1058 "NautM": 1852.00000000000000000000 / OpenLayers.METERS_PER_INCH, //EPSG:9030
1059 "Lat-66": 110943.316488932731 / OpenLayers.METERS_PER_INCH,
1060 "Lat-83": 110946.25736872234125 / OpenLayers.METERS_PER_INCH,
1061 "Decimeter": 0.10000000000000000000 / OpenLayers.METERS_PER_INCH,
1062 "Millimeter": 0.00100000000000000000 / OpenLayers.METERS_PER_INCH,
1063 "Dekameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1064 "Decameter": 10.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1065 "Hectometer": 100.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1066 "GermanMeter": 1.0000135965 / OpenLayers.METERS_PER_INCH, //EPSG:9031
1067 "CaGrid": 0.999738 / OpenLayers.METERS_PER_INCH,
1068 "ClarkeChain": 20.1166194976 / OpenLayers.METERS_PER_INCH, //EPSG:9038
1069 "GunterChain": 20.11684023368047 / OpenLayers.METERS_PER_INCH, //EPSG:9033
1070 "BenoitChain": 20.116782494375872 / OpenLayers.METERS_PER_INCH, //EPSG:9062
1071 "SearsChain": 20.11676512155 / OpenLayers.METERS_PER_INCH, //EPSG:9042
1072 "ClarkeLink": 0.201166194976 / OpenLayers.METERS_PER_INCH, //EPSG:9039
1073 "GunterLink": 0.2011684023368047 / OpenLayers.METERS_PER_INCH, //EPSG:9034
1074 "BenoitLink": 0.20116782494375872 / OpenLayers.METERS_PER_INCH, //EPSG:9063
1075 "SearsLink": 0.2011676512155 / OpenLayers.METERS_PER_INCH, //EPSG:9043
1076 "Rod": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1077 "IntnlChain": 20.1168 / OpenLayers.METERS_PER_INCH, //EPSG:9097
1078 "IntnlLink": 0.201168 / OpenLayers.METERS_PER_INCH, //EPSG:9098
1079 "Perch": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1080 "Pole": 5.02921005842012 / OpenLayers.METERS_PER_INCH,
1081 "Furlong": 201.1684023368046 / OpenLayers.METERS_PER_INCH,
1082 "Rood": 3.778266898 / OpenLayers.METERS_PER_INCH,
1083 "CapeFoot": 0.3047972615 / OpenLayers.METERS_PER_INCH,
1084 "Brealey": 375.00000000000000000000 / OpenLayers.METERS_PER_INCH,
1085 "ModAmFt": 0.304812252984505969011938 / OpenLayers.METERS_PER_INCH,
1086 "Fathom": 1.8288 / OpenLayers.METERS_PER_INCH,
1087 "NautM-UK": 1853.184 / OpenLayers.METERS_PER_INCH,
1088 "50kilometers": 50000.0 / OpenLayers.METERS_PER_INCH,
1089 "150kilometers": 150000.0 / OpenLayers.METERS_PER_INCH
1092 //unit abbreviations supported by PROJ.4
1093 OpenLayers.Util.extend(OpenLayers.INCHES_PER_UNIT, {
1094 "mm": OpenLayers.INCHES_PER_UNIT["Meter"] / 1000.0,
1095 "cm": OpenLayers.INCHES_PER_UNIT["Meter"] / 100.0,
1096 "dm": OpenLayers.INCHES_PER_UNIT["Meter"] * 100.0,
1097 "km": OpenLayers.INCHES_PER_UNIT["Meter"] * 1000.0,
1098 "kmi": OpenLayers.INCHES_PER_UNIT["nmi"], //International Nautical Mile
1099 "fath": OpenLayers.INCHES_PER_UNIT["Fathom"], //International Fathom
1100 "ch": OpenLayers.INCHES_PER_UNIT["IntnlChain"], //International Chain
1101 "link": OpenLayers.INCHES_PER_UNIT["IntnlLink"], //International Link
1102 "us-in": OpenLayers.INCHES_PER_UNIT["inches"], //U.S. Surveyor's Inch
1103 "us-ft": OpenLayers.INCHES_PER_UNIT["Foot"], //U.S. Surveyor's Foot
1104 "us-yd": OpenLayers.INCHES_PER_UNIT["Yard"], //U.S. Surveyor's Yard
1105 "us-ch": OpenLayers.INCHES_PER_UNIT["GunterChain"], //U.S. Surveyor's Chain
1106 "us-mi": OpenLayers.INCHES_PER_UNIT["Mile"], //U.S. Surveyor's Statute Mile
1107 "ind-yd": OpenLayers.INCHES_PER_UNIT["IndianYd37"], //Indian Yard
1108 "ind-ft": OpenLayers.INCHES_PER_UNIT["IndianFt37"], //Indian Foot
1109 "ind-ch": 20.11669506 / OpenLayers.METERS_PER_INCH //Indian Chain
1113 * Constant: DOTS_PER_INCH
1114 * {Integer} 72 (A sensible default)
1116 OpenLayers.DOTS_PER_INCH = 72;
1119 * Function: normalizeScale
1125 * {Float} A normalized scale value, in 1 / X format.
1126 * This means that if a value less than one ( already 1/x) is passed
1127 * in, it just returns scale directly. Otherwise, it returns
1130 OpenLayers.Util.normalizeScale = function (scale) {
1131 var normScale = (scale > 1.0) ? (1.0 / scale)
1137 * Function: getResolutionFromScale
1141 * units - {String} Index into OpenLayers.INCHES_PER_UNIT hashtable.
1142 * Default is degrees
1145 * {Float} The corresponding resolution given passed-in scale and unit
1148 OpenLayers.Util.getResolutionFromScale = function (scale, units) {
1150 if (units == null) {
1154 var normScale = OpenLayers.Util.normalizeScale(scale);
1156 var resolution = 1 / (normScale * OpenLayers.INCHES_PER_UNIT[units]
1157 * OpenLayers.DOTS_PER_INCH);
1162 * Function: getScaleFromResolution
1165 * resolution - {Float}
1166 * units - {String} Index into OpenLayers.INCHES_PER_UNIT hashtable.
1167 * Default is degrees
1170 * {Float} The corresponding scale given passed-in resolution and unit
1173 OpenLayers.Util.getScaleFromResolution = function (resolution, units) {
1175 if (units == null) {
1179 var scale = resolution * OpenLayers.INCHES_PER_UNIT[units] *
1180 OpenLayers.DOTS_PER_INCH;
1185 * Function: safeStopPropagation
1186 * *Deprecated*. This function has been deprecated. Please use directly
1187 * <OpenLayers.Event.stop> passing 'true' as the 2nd
1188 * argument (preventDefault)
1190 * Safely stop the propagation of an event *without* preventing
1191 * the default browser action from occurring.
1196 OpenLayers.Util.safeStopPropagation = function(evt) {
1197 OpenLayers.Event.stop(evt, true);
1201 * Function: pagePositon
1202 * Calculates the position of an element on the page.
1205 * forElement - {DOMElement}
1208 * {Array} two item array, L value then T value.
1210 OpenLayers.Util.pagePosition = function(forElement) {
1211 var valueT = 0, valueL = 0;
1213 var element = forElement;
1214 var child = forElement;
1217 if(element == document.body) {
1218 if(OpenLayers.Element.getStyle(child, 'position') == 'absolute') {
1223 valueT += element.offsetTop || 0;
1224 valueL += element.offsetLeft || 0;
1228 // wrapping this in a try/catch because IE chokes on the offsetParent
1229 element = element.offsetParent;
1231 OpenLayers.Console.error(OpenLayers.i18n(
1232 "pagePositionFailed",{'elemId':element.id}));
1237 element = forElement;
1239 valueT -= element.scrollTop || 0;
1240 valueL -= element.scrollLeft || 0;
1241 element = element.parentNode;
1244 return [valueL, valueT];
1249 * Function: isEquivalentUrl
1250 * Test two URLs for equivalence.
1252 * Setting 'ignoreCase' allows for case-independent comparison.
1254 * Comparison is based on:
1256 * - Host (evaluated without the port)
1257 * - Port (set 'ignorePort80' to ignore "80" values)
1258 * - Hash ( set 'ignoreHash' to disable)
1259 * - Pathname (for relative <-> absolute comparison)
1260 * - Arguments (so they can be out of order)
1265 * options - {Object} Allows for customization of comparison:
1266 * 'ignoreCase' - Default is True
1267 * 'ignorePort80' - Default is True
1268 * 'ignoreHash' - Default is True
1271 * {Boolean} Whether or not the two URLs are equivalent
1273 OpenLayers.Util.isEquivalentUrl = function(url1, url2, options) {
1274 options = options || {};
1276 OpenLayers.Util.applyDefaults(options, {
1282 var urlObj1 = OpenLayers.Util.createUrlObject(url1, options);
1283 var urlObj2 = OpenLayers.Util.createUrlObject(url2, options);
1285 //compare all keys except for "args" (treated below)
1286 for(var key in urlObj1) {
1287 if(key !== "args") {
1288 if(urlObj1[key] != urlObj2[key]) {
1294 // compare search args - irrespective of order
1295 for(var key in urlObj1.args) {
1296 if(urlObj1.args[key] != urlObj2.args[key]) {
1299 delete urlObj2.args[key];
1301 // urlObj2 shouldn't have any args left
1302 for(var key in urlObj2.args) {
1310 * Function: createUrlObject
1314 * options - {Object} A hash of options. Can be one of:
1315 * ignoreCase: lowercase url,
1316 * ignorePort80: don't include explicit port if port is 80,
1317 * ignoreHash: Don't include part of url after the hash (#).
1320 * {Object} An object with separate url, a, port, host, and args parsed out
1321 * and ready for comparison
1323 OpenLayers.Util.createUrlObject = function(url, options) {
1324 options = options || {};
1326 // deal with relative urls first
1327 if(!(/^\w+:\/\//).test(url)) {
1328 var loc = window.location;
1329 var port = loc.port ? ":" + loc.port : "";
1330 var fullUrl = loc.protocol + "//" + loc.host.split(":").shift() + port;
1331 if(url.indexOf("/") === 0) {
1333 url = fullUrl + url;
1335 // relative to current path
1336 var parts = loc.pathname.split("/");
1338 url = fullUrl + parts.join("/") + "/" + url;
1342 if (options.ignoreCase) {
1343 url = url.toLowerCase();
1346 var a = document.createElement('a');
1351 //host (without port)
1352 urlObject.host = a.host.split(":").shift();
1355 urlObject.protocol = a.protocol;
1357 //port (get uniform browser behavior with port 80 here)
1358 if(options.ignorePort80) {
1359 urlObject.port = (a.port == "80" || a.port == "0") ? "" : a.port;
1361 urlObject.port = (a.port == "" || a.port == "0") ? "80" : a.port;
1365 urlObject.hash = (options.ignoreHash || a.hash === "#") ? "" : a.hash;
1368 var queryString = a.search;
1370 var qMark = url.indexOf("?");
1371 queryString = (qMark != -1) ? url.substr(qMark) : "";
1373 urlObject.args = OpenLayers.Util.getParameters(queryString);
1375 //pathname (uniform browser behavior with leading "/")
1376 urlObject.pathname = (a.pathname.charAt(0) == "/") ? a.pathname : "/" + a.pathname;
1382 * Function: removeTail
1383 * Takes a url and removes everything after the ? and #
1386 * url - {String} The url to process
1389 * {String} The string with all queryString and Hash removed
1391 OpenLayers.Util.removeTail = function(url) {
1394 var qMark = url.indexOf("?");
1395 var hashMark = url.indexOf("#");
1398 head = (hashMark != -1) ? url.substr(0,hashMark) : url;
1400 head = (hashMark != -1) ? url.substr(0,Math.min(qMark, hashMark))
1401 : url.substr(0, qMark);
1408 * Function: getBrowserName
1411 * {String} A string which specifies which is the current
1412 * browser in which we are running.
1414 * Currently-supported browser detection and codes:
1415 * * 'opera' -- Opera
1416 * * 'msie' -- Internet Explorer
1417 * * 'safari' -- Safari
1418 * * 'firefox' -- FireFox
1419 * * 'mozilla' -- Mozilla
1421 * If we are unable to property identify the browser, we
1422 * return an empty string.
1424 OpenLayers.Util.getBrowserName = function() {
1425 var browserName = "";
1427 var ua = navigator.userAgent.toLowerCase();
1428 if ( ua.indexOf( "opera" ) != -1 ) {
1429 browserName = "opera";
1430 } else if ( ua.indexOf( "msie" ) != -1 ) {
1431 browserName = "msie";
1432 } else if ( ua.indexOf( "safari" ) != -1 ) {
1433 browserName = "safari";
1434 } else if ( ua.indexOf( "mozilla" ) != -1 ) {
1435 if ( ua.indexOf( "firefox" ) != -1 ) {
1436 browserName = "firefox";
1438 browserName = "mozilla";
1449 * Method: getRenderedDimensions
1450 * Renders the contentHTML offscreen to determine actual dimensions for
1451 * popup sizing. As we need layout to determine dimensions the content
1452 * is rendered -9999px to the left and absolute to ensure the
1453 * scrollbars do not flicker
1457 * size - {<OpenLayers.Size>} If either the 'w' or 'h' properties is
1458 * specified, we fix that dimension of the div to be measured. This is
1459 * useful in the case where we have a limit in one dimension and must
1460 * therefore meaure the flow in the other dimension.
1461 * options - {Object}
1462 * displayClass - {String} Optional parameter. A CSS class name(s) string
1463 * to provide the CSS context of the rendered content.
1464 * containerElement - {DOMElement} Optional parameter. Insert the HTML to
1465 * this node instead of the body root when calculating dimensions.
1470 OpenLayers.Util.getRenderedDimensions = function(contentHTML, size, options) {
1474 // create temp container div with restricted size
1475 var container = document.createElement("div");
1476 container.style.visibility = "hidden";
1478 var containerElement = (options && options.containerElement)
1479 ? options.containerElement : document.body;
1481 //fix a dimension, if specified.
1485 container.style.width = w + "px";
1486 } else if (size.h) {
1488 container.style.height = h + "px";
1492 //add css classes, if specified
1493 if (options && options.displayClass) {
1494 container.className = options.displayClass;
1497 // create temp content div and assign content
1498 var content = document.createElement("div");
1499 content.innerHTML = contentHTML;
1501 // we need overflow visible when calculating the size
1502 content.style.overflow = "visible";
1503 if (content.childNodes) {
1504 for (var i=0, l=content.childNodes.length; i<l; i++) {
1505 if (!content.childNodes[i].style) continue;
1506 content.childNodes[i].style.overflow = "visible";
1510 // add content to restricted container
1511 container.appendChild(content);
1513 // append container to body for rendering
1514 containerElement.appendChild(container);
1516 // Opera and IE7 can't handle a node with position:aboslute if it inherits
1517 // position:absolute from a parent.
1518 var parentHasPositionAbsolute = false;
1519 var parent = container.parentNode;
1520 while (parent && parent.tagName.toLowerCase()!="body") {
1521 var parentPosition = OpenLayers.Element.getStyle(parent, "position");
1522 if(parentPosition == "absolute") {
1523 parentHasPositionAbsolute = true;
1525 } else if (parentPosition && parentPosition != "static") {
1528 parent = parent.parentNode;
1531 if(!parentHasPositionAbsolute) {
1532 container.style.position = "absolute";
1535 // calculate scroll width of content and add corners and shadow width
1537 w = parseInt(content.scrollWidth);
1539 // update container width to allow height to adjust
1540 container.style.width = w + "px";
1542 // capture height and add shadow and corner image widths
1544 h = parseInt(content.scrollHeight);
1548 container.removeChild(content);
1549 containerElement.removeChild(container);
1551 return new OpenLayers.Size(w, h);
1555 * APIFunction: getScrollbarWidth
1556 * This function has been modified by the OpenLayers from the original version,
1557 * written by Matthew Eernisse and released under the Apache 2
1560 * http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels
1562 * It has been modified simply to cache its value, since it is physically
1563 * impossible that this code could ever run in more than one browser at
1569 OpenLayers.Util.getScrollbarWidth = function() {
1571 var scrollbarWidth = OpenLayers.Util._scrollbarWidth;
1573 if (scrollbarWidth == null) {
1579 // Outer scrolling div
1580 scr = document.createElement('div');
1581 scr.style.position = 'absolute';
1582 scr.style.top = '-1000px';
1583 scr.style.left = '-1000px';
1584 scr.style.width = '100px';
1585 scr.style.height = '50px';
1586 // Start with no scrollbar
1587 scr.style.overflow = 'hidden';
1589 // Inner content div
1590 inn = document.createElement('div');
1591 inn.style.width = '100%';
1592 inn.style.height = '200px';
1594 // Put the inner div in the scrolling div
1595 scr.appendChild(inn);
1596 // Append the scrolling div to the doc
1597 document.body.appendChild(scr);
1599 // Width of the inner div sans scrollbar
1600 wNoScroll = inn.offsetWidth;
1602 // Add the scrollbar
1603 scr.style.overflow = 'scroll';
1604 // Width of the inner div width scrollbar
1605 wScroll = inn.offsetWidth;
1607 // Remove the scrolling div from the doc
1608 document.body.removeChild(document.body.lastChild);
1610 // Pixel width of the scroller
1611 OpenLayers.Util._scrollbarWidth = (wNoScroll - wScroll);
1612 scrollbarWidth = OpenLayers.Util._scrollbarWidth;
1615 return scrollbarWidth;