Util

Summary
Util
Functions and Properties
getElementThis is the old $() from prototype
extendCopy all properties of a source object to a destination object.
removeItemRemove an object from an array.
clearArrayDeprecated.
indexOfSeems to exist already in FF, but not in MOZ.
modifyDOMElementModifies many properties of a DOM element all at once.
createDivCreates a new div and optionally set some standard attributes.
createImageCreates an img element with specific attribute values.
setOpacityDeprecated.
onImageLoadBound to image load events.
onImageLoadErrorColor{String} The color tiles with load errors will turn.
IMAGE_RELOAD_ATTEMPTS{Integer} How many times should we try to reload an image before giving up? 
onImageLoadError
alphaHackNeeded{Boolean} true if the png alpha hack is necessary and possible, false otherwise.
alphaHackChecks whether it’s necessary (and possible) to use the png alpha hack which allows alpha transparency for png images under Internet Explorer.
modifyAlphaImageDiv
createAlphaImageDiv
upperCaseObjectCreates a new hashtable and copies over all the keys from the passed-in object, but storing them under an uppercased version of the key at which they were stored.
applyDefaultsTakes an object and copies any properties that don’t exist from another properties, by analogy with OpenLayers.Util.extend() from Prototype.js.
getParameterString
ImgPath{String} Default is ‘’.
getImagesLocation{String} The fully formatted image location string
TryExecute functions until one of them doesn’t throw an error.
getNodesThese could/should be made namespace aware?
_getNodes
getTagText
getXmlNodeValue
mouseLeft
precision{Number} The number of significant digits to retain to avoid floating point precision errors.
toFloatConvenience method to cast an object to a Number, rounded to the desired floating point precision.
rad
distVincentyGiven two objects representing points with geographic coordinates, this calculates the distance between those points on the surface of an ellipsoid.
getParametersParse the parameters from a URL or from the current page itself into a JavaScript Object.
getArgsDeprecated.
lastSeqID{Integer} The ever-incrementing count variable.
createUniqueIDCreate a unique identifier for this session.
Constants
INCHES_PER_UNIT{Object} Constant inches per unit -- borrowed from MapServer mapscale.c derivation of nautical miles from http://en.wikipedia.org/wiki/Nautical_mile Includes the full set of units supported by CS-MAP (http://trac.osgeo.org/csmap/) and PROJ.4 (http://trac.osgeo.org/proj/) The hardcoded table is maintain in a CS-MAP source code module named CSdataU.c The hardcoded table of PROJ.4 units are in pj_units.c.
DOTS_PER_INCH{Integer} 72 (A sensible default)
Functions
normalizeScale
getResolutionFromScale
getScaleFromResolution
safeStopPropagationDeprecated.
pagePositonCalculates the position of an element on the page.
isEquivalentUrlTest two URLs for equivalence.
createUrlObject
removeTailTakes a url and removes everything after the ?
getBrowserName{String} A string which specifies which is the current browser in which we are running.
getRenderedDimensionsRenders the contentHTML offscreen to determine actual dimensions for popup sizing.
getScrollbarWidthThis function has been modified by the OpenLayers from the original version, written by Matthew Eernisse and released under the Apache 2 license here:

Functions and Properties

getElement

OpenLayers.Util.getElement = function()

This is the old $() from prototype

extend

OpenLayers.Util.extend = function(destination,
source)

Copy all properties of a source object to a destination object.  Modifies the passed in destination object.  Any properties on the source object that are set to undefined will not be (re)set on the destination object.

Parameters

destination{Object} The object that will be modified
source{Object} The object with properties to be set on the destination

Returns

{Object} The destination object.

removeItem

OpenLayers.Util.removeItem = function(array,
item)

Remove an object from an array.  Iterates through the array to find the item, then removes it.

Parameters

array{Array}
item{Object}

Return {Array} A reference to the array

clearArray

OpenLayers.Util.clearArray = function(array)

Deprecated.  This function will disappear in 3.0.  Please use “array.length = 0” instead.

Parameters

array{Array}

indexOf

OpenLayers.Util.indexOf = function(array,
obj)

Seems to exist already in FF, but not in MOZ.

Parameters

array{Array}
obj{Object}

Returns

{Integer} The index at, which the object was found in the array.  If not found, returns -1.

modifyDOMElement

OpenLayers.Util.modifyDOMElement = function(element,
id,
px,
sz,
position,
border,
overflow,
opacity)

Modifies many properties of a DOM element all at once.  Passing in null to an individual parameter will avoid setting the attribute.

Parameters

id{String} The element id attribute to set.
px{OpenLayers.Pixel} The left and top style position.
sz{OpenLayers.Size} The width and height style attributes.
position{String} The position attribute.  eg: absolute, relative, etc.
border{String} The style.border attribute.  eg: solid black 2px
overflow{String} The style.overview attribute.
opacity{Float} Fractional value (0.0 - 1.0)

createDiv

OpenLayers.Util.createDiv = function(id,
px,
sz,
imgURL,
position,
border,
overflow,
opacity)

Creates a new div and optionally set some standard attributes.  Null may be passed to each parameter if you do not wish to set a particular attribute.  Note - zIndex is NOT set on the resulting div.

Parameters

id{String} An identifier for this element.  If no id is passed an identifier will be created automatically.
px{OpenLayers.Pixel} The element left and top position.
sz{OpenLayers.Size} The element width and height.
imgURL{String} A url pointing to an image to use as a background image.
position{String} The style.position value. eg: absolute, relative etc.
border{String} The the style.border value. eg: 2px solid black
overflow{String} The style.overflow value.  Eg. hidden
opacity{Float} Fractional value (0.0 - 1.0)

Returns

{DOMElement} A DOM Div created with the specified attributes.

createImage

OpenLayers.Util.createImage = function(id,
px,
sz,
imgURL,
position,
border,
opacity,
delayDisplay)

Creates an img element with specific attribute values.

Parameters

id{String} The id field for the img.  If none assigned one will be automatically generated.
px{OpenLayers.Pixel} The left and top positions.
sz{OpenLayers.Size} The style.width and style.height values.
imgURL{String} The url to use as the image source.
position{String} The style.position value.
border{String} The border to place around the image.
opacity{Float} Fractional value (0.0 - 1.0)
delayDisplay{Boolean} If true waits until the image has been loaded.

Returns

{DOMElement} A DOM Image created with the specified attributes.

setOpacity

OpenLayers.Util.setOpacity = function(element,
opacity)

Deprecated.  This function has been deprecated.  Instead, please use <OpenLayers.Util.modifyDOMElement> or <OpenLayers.Util.modifyAlphaImageDiv>

Set the opacity of a DOM Element Note that for this function to work in IE, elements must “have layout” according to: http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/haslayout.asp

Parameters

element{DOMElement} Set the opacity on this DOM element
opacity{Float} Opacity value (0.0 - 1.0)

onImageLoad

OpenLayers.Util.onImageLoad = function()

Bound to image load events.  For all images created with createImage or createAlphaImageDiv, this function will be bound to the load event.

onImageLoadErrorColor

{String} The color tiles with load errors will turn.  Default is “pink”

IMAGE_RELOAD_ATTEMPTS

{Integer} How many times should we try to reload an image before giving up?  Default is 0

onImageLoadError

OpenLayers.Util.onImageLoadError = function()

alphaHackNeeded

{Boolean} true if the png alpha hack is necessary and possible, false otherwise.

alphaHack

OpenLayers.Util.alphaHack = function()

Checks whether it’s necessary (and possible) to use the png alpha hack which allows alpha transparency for png images under Internet Explorer.

Returns

{Boolean} true if the png alpha hack is necessary and possible, false otherwise.

modifyAlphaImageDiv

OpenLayers.Util.modifyAlphaImageDiv = function(div,
id,
px,
sz,
imgURL,
position,
border,
sizing,
opacity)
div{DOMElement} Div containing Alpha-adjusted Image
id{String}
px{OpenLayers.Pixel}
sz{OpenLayers.Size}
imgURL{String}
position{String}
border{String} sizing {String} ‘crop’, ‘scale’, or ‘image’.  Default is “scale”
opacity{Float} Fractional value (0.0 - 1.0)

createAlphaImageDiv

OpenLayers.Util.createAlphaImageDiv = function(id,
px,
sz,
imgURL,
position,
border,
sizing,
opacity,
delayDisplay)
id{String}
px{OpenLayers.Pixel}
sz{OpenLayers.Size}
imgURL{String}
position{String}
border{String}
sizing{String} ‘crop’, ‘scale’, or ‘image’.  Default is “scale”
opacity{Float} Fractional value (0.0 - 1.0)
delayDisplay{Boolean} If true waits until the image has been loaded.

Returns

{DOMElement} A DOM Div created with a DOM Image inside it.  If the hack is needed for transparency in IE, it is added.

upperCaseObject

OpenLayers.Util.upperCaseObject = function (object)

Creates a new hashtable and copies over all the keys from the passed-in object, but storing them under an uppercased version of the key at which they were stored.

Parameters

object{Object}

Returns

{Object} A new Object with all the same keys but uppercased

applyDefaults

OpenLayers.Util.applyDefaults = function (to,
from)

Takes an object and copies any properties that don’t exist from another properties, by analogy with OpenLayers.Util.extend() from Prototype.js.

Parameters

to{Object} The destination object.
from{Object} The source object.  Any properties of this object that are undefined in the to object will be set on the to object.

Returns

{Object} A reference to the to object.  Note that the to argument is modified in place and returned by this function.

getParameterString

OpenLayers.Util.getParameterString = function(params)

Parameters

params{Object}

Returns

{String} A concatenation of the properties of an object in http parameter notation.  (ex.  <i>”key1=value1&key2=value2&key3=value3”</i>) If a parameter is actually a list, that parameter will then be set to a comma-seperated list of values (foo,bar) instead of being URL escaped (foo%3Abar).

ImgPath

{String} Default is ‘’.

getImagesLocation

OpenLayers.Util.getImagesLocation = function()

Returns

{String} The fully formatted image location string

Try

OpenLayers.Util.Try = function()

Execute functions until one of them doesn’t throw an error.  Capitalized because “try” is a reserved word in JavaScript.  Taken directly from OpenLayers.Util.Try()

Parameters

[*]{Function} Any number of parameters may be passed to Try() It will attempt to execute each of them until one of them successfully executes.  If none executes successfully, returns null.

Returns

{*} The value returned by the first successfully executed function.

getNodes

OpenLayers.Util.getNodes=function(p,
tagName)

These could/should be made namespace aware?

Parameters

p{}
tagName{String}

Returns

{Array}

_getNodes

OpenLayers.Util._getNodes=function(nodes,
tagName)

Parameters

nodes{Array}
tagName{String}

Returns

{Array}

getTagText

OpenLayers.Util.getTagText = function (parent,
item,
index)

Parameters

parent{}
item{String}
index{Integer}

Returns

{String}

getXmlNodeValue

OpenLayers.Util.getXmlNodeValue = function(node)

Parameters

node{XMLNode}

Returns

{String} The text value of the given node, without breaking in firefox or IE

mouseLeft

OpenLayers.Util.mouseLeft = function (evt,
div)

Parameters

evt{Event}
div{HTMLDivElement}

Returns

{Boolean}

precision

{Number} The number of significant digits to retain to avoid floating point precision errors.

We use 14 as a “safe” default because, although IEEE 754 double floats (standard on most modern operating systems) support up to about 16 significant digits, 14 significant digits are sufficient to represent sub-millimeter accuracy in any coordinate system that anyone is likely to use with OpenLayers.

If DEFAULT_PRECISION is set to 0, the original non-truncating behavior of OpenLayers <2.8 is preserved.  Be aware that this will cause problems with certain projections, e.g. spherical Mercator.

toFloat

OpenLayers.Util.toFloat = function (number,
precision)

Convenience method to cast an object to a Number, rounded to the desired floating point precision.

Parameters

number{Number} The number to cast and round.
precision{Number} An integer suitable for use with Number.toPrecision().  Defaults to OpenLayers.Util.DEFAULT_PRECISION.  If set to 0, no rounding is performed.

Returns

{Number} The cast, rounded number.

rad

OpenLayers.Util.rad = function(x)

Parameters

x{Float}

Returns

{Float}

distVincenty

OpenLayers.Util.distVincenty=function(p1,
p2)

Given two objects representing points with geographic coordinates, this calculates the distance between those points on the surface of an ellipsoid.

Parameters

p1{OpenLayers.LonLat} (or any object with both .lat, .lon properties)
p2{OpenLayers.LonLat} (or any object with both .lat, .lon properties)

Returns

{Float} The distance (in km) between the two input points as measured on an ellipsoid.  Note that the input point objects must be in geographic coordinates (decimal degrees) and the return distance is in kilometers.

getParameters

OpenLayers.Util.getParameters = function(url)

Parse the parameters from a URL or from the current page itself into a JavaScript Object.  Note that parameter values with commas are separated out into an Array.

Parameters

url{String} Optional url used to extract the query string.  If null, query string is taken from page location.

Returns

{Object} An object of key/value pairs from the query string.

getArgs

OpenLayers.Util.getArgs = function(url)

Deprecated.  Will be removed in 3.0.  Please use instead <OpenLayers.Util.getParameters>

Parameters

url{String} Optional url used to extract the query string.  If null, query string is taken from page location.

Returns

{Object} An object of key/value pairs from the query string.

lastSeqID

{Integer} The ever-incrementing count variable.  Used for generating unique ids.

createUniqueID

OpenLayers.Util.createUniqueID = function(prefix)

Create a unique identifier for this session.  Each time this function is called, a counter is incremented.  The return will be the optional prefix (defaults to “id_”) appended with the counter value.

Parameters

prefix {String} Optionsal string to prefix unique id.  Default is “id_”.

Returns

{String} A unique id string, built on the passed in prefix.

Constants

INCHES_PER_UNIT

{Object} Constant inches per unit -- borrowed from MapServer mapscale.c derivation of nautical miles from http://en.wikipedia.org/wiki/Nautical_mile Includes the full set of units supported by CS-MAP (http://trac.osgeo.org/csmap/) and PROJ.4 (http://trac.osgeo.org/proj/) The hardcoded table is maintain in a CS-MAP source code module named CSdataU.c The hardcoded table of PROJ.4 units are in pj_units.c.

DOTS_PER_INCH

{Integer} 72 (A sensible default)

Functions

normalizeScale

OpenLayers.Util.normalizeScale = function (scale)

Parameters

scale{float}

Returns

{Float} A normalized scale value, in 1 / X format.  This means that if a value less than one ( already 1/x) is passed in, it just returns scale directly.  Otherwise, it returns 1 / scale

getResolutionFromScale

OpenLayers.Util.getResolutionFromScale = function (scale,
units)

Parameters

scale{Float}
units{String} Index into OpenLayers.INCHES_PER_UNIT hashtable.  Default is degrees

Returns

{Float} The corresponding resolution given passed-in scale and unit parameters.

getScaleFromResolution

OpenLayers.Util.getScaleFromResolution = function (resolution,
units)

Parameters

resolution{Float}
units{String} Index into OpenLayers.INCHES_PER_UNIT hashtable.  Default is degrees

Returns

{Float} The corresponding scale given passed-in resolution and unit parameters.

safeStopPropagation

OpenLayers.Util.safeStopPropagation = function(evt)

Deprecated.  This function has been deprecated.  Please use directly OpenLayers.Event.stop passing ‘true’ as the 2nd argument (preventDefault)

Safely stop the propagation of an event without preventing the default browser action from occurring.

Parameter

evt{Event}

pagePositon

Calculates the position of an element on the page.

Parameters

forElement{DOMElement}

Returns

{Array} two item array, L value then T value.

isEquivalentUrl

OpenLayers.Util.isEquivalentUrl = function(url1,
url2,
options)

Test two URLs for equivalence.

Setting ‘ignoreCase’ allows for case-independent comparison.

Comparison is based on

  • Protocol
  • Host (evaluated without the port)
  • Port (set ‘ignorePort80’ to ignore “80” values)
  • Hash ( set ‘ignoreHash’ to disable)
  • Pathname (for relative <-> absolute comparison)
  • Arguments (so they can be out of order)

Parameters

url1{String}
url2{String}
options{Object} Allows for customization of comparison:
’ignoreCase’Default is True
’ignorePort80’Default is True
’ignoreHash’Default is True

Returns

{Boolean} Whether or not the two URLs are equivalent

createUrlObject

OpenLayers.Util.createUrlObject = function(url,
options)

Parameters

url{String}
options{Object} A hash of options.  Can be one of: ignoreCase: lowercase url, ignorePort80: don’t include explicit port if port is 80, ignoreHash: Don’t include part of url after the hash (#).

Returns

{Object} An object with separate url, a, port, host, and args parsed out and ready for comparison

removeTail

OpenLayers.Util.removeTail = function(url)

Takes a url and removes everything after the ? and #

Parameters

url{String} The url to process

Returns

{String} The string with all queryString and Hash removed

getBrowserName

OpenLayers.Util.getBrowserName = function()

Returns

{String} A string which specifies which is the current browser in which we are running.

Currently-supported browser detection and codes

  • ’opera’ -- Opera
  • ’msie’ -- Internet Explorer
  • ’safari’ -- Safari
  • ’firefox’ -- FireFox
  • ’mozilla’ -- Mozilla

If we are unable to property identify the browser, we return an empty string.

getRenderedDimensions

OpenLayers.Util.getRenderedDimensions = function(contentHTML,
size,
options)

Renders the contentHTML offscreen to determine actual dimensions for popup sizing.  As we need layout to determine dimensions the content is rendered -9999px to the left and absolute to ensure the scrollbars do not flicker

Parameters

contentHTML size - {OpenLayers.Size} If either the ‘w’ or ‘h’ properties is specified, we fix that dimension of the div to be measured.  This is useful in the case where we have a limit in one dimension and must therefore meaure the flow in the other dimension. options - {Object} displayClass - {String} Optional parameter.  A CSS class name(s) string to provide the CSS context of the rendered content. containerElement - {DOMElement} Optional parameter.  Insert the HTML to this node instead of the body root when calculating dimensions.

Returns

{OpenLayers.Size}

getScrollbarWidth

OpenLayers.Util.getScrollbarWidth = function()

This function has been modified by the OpenLayers from the original version, written by Matthew Eernisse and released under the Apache 2 license here:

http://www.fleegix.org/articles/2006/05/30/getting-the-scrollbar-width-in-pixels

It has been modified simply to cache its value, since it is physically impossible that this code could ever run in more than one browser at once.

Returns

{Integer}

OpenLayers.Util.getElement = function()
This is the old $() from prototype
OpenLayers.Util.extend = function(destination,
source)
Copy all properties of a source object to a destination object.
OpenLayers.Util.removeItem = function(array,
item)
Remove an object from an array.
OpenLayers.Util.clearArray = function(array)
Deprecated.
OpenLayers.Util.indexOf = function(array,
obj)
Seems to exist already in FF, but not in MOZ.
OpenLayers.Util.modifyDOMElement = function(element,
id,
px,
sz,
position,
border,
overflow,
opacity)
Modifies many properties of a DOM element all at once.
OpenLayers.Util.createDiv = function(id,
px,
sz,
imgURL,
position,
border,
overflow,
opacity)
Creates a new div and optionally set some standard attributes.
OpenLayers.Util.createImage = function(id,
px,
sz,
imgURL,
position,
border,
opacity,
delayDisplay)
Creates an img element with specific attribute values.
OpenLayers.Util.setOpacity = function(element,
opacity)
Deprecated.
OpenLayers.Util.onImageLoad = function()
Bound to image load events.
OpenLayers.Util.onImageLoadError = function()
OpenLayers.Util.alphaHack = function()
Checks whether it’s necessary (and possible) to use the png alpha hack which allows alpha transparency for png images under Internet Explorer.
OpenLayers.Util.modifyAlphaImageDiv = function(div,
id,
px,
sz,
imgURL,
position,
border,
sizing,
opacity)
OpenLayers.Util.createAlphaImageDiv = function(id,
px,
sz,
imgURL,
position,
border,
sizing,
opacity,
delayDisplay)
OpenLayers.Util.upperCaseObject = function (object)
Creates a new hashtable and copies over all the keys from the passed-in object, but storing them under an uppercased version of the key at which they were stored.
OpenLayers.Util.applyDefaults = function (to,
from)
Takes an object and copies any properties that don’t exist from another properties, by analogy with OpenLayers.Util.extend() from Prototype.js.
OpenLayers.Util.getParameterString = function(params)
OpenLayers.Util.getImagesLocation = function()
{String} The fully formatted image location string
OpenLayers.Util.Try = function()
Execute functions until one of them doesn’t throw an error.
OpenLayers.Util.getNodes=function(p,
tagName)
These could/should be made namespace aware?
OpenLayers.Util._getNodes=function(nodes,
tagName)
OpenLayers.Util.getTagText = function (parent,
item,
index)
OpenLayers.Util.getXmlNodeValue = function(node)
OpenLayers.Util.mouseLeft = function (evt,
div)
OpenLayers.Util.toFloat = function (number,
precision)
Convenience method to cast an object to a Number, rounded to the desired floating point precision.
OpenLayers.Util.rad = function(x)
OpenLayers.Util.distVincenty=function(p1,
p2)
Given two objects representing points with geographic coordinates, this calculates the distance between those points on the surface of an ellipsoid.
OpenLayers.Util.getParameters = function(url)
Parse the parameters from a URL or from the current page itself into a JavaScript Object.
OpenLayers.Util.getArgs = function(url)
Deprecated.
OpenLayers.Util.createUniqueID = function(prefix)
Create a unique identifier for this session.
OpenLayers.Util.normalizeScale = function (scale)
OpenLayers.Util.getResolutionFromScale = function (scale,
units)
OpenLayers.Util.getScaleFromResolution = function (resolution,
units)
OpenLayers.Util.safeStopPropagation = function(evt)
Deprecated.
OpenLayers.Util.isEquivalentUrl = function(url1,
url2,
options)
Test two URLs for equivalence.
OpenLayers.Util.createUrlObject = function(url,
options)
OpenLayers.Util.removeTail = function(url)
Takes a url and removes everything after the ?
OpenLayers.Util.getBrowserName = function()
{String} A string which specifies which is the current browser in which we are running.
OpenLayers.Util.getRenderedDimensions = function(contentHTML,
size,
options)
Renders the contentHTML offscreen to determine actual dimensions for popup sizing.
OpenLayers.Util.getScrollbarWidth = function()
This function has been modified by the OpenLayers from the original version, written by Matthew Eernisse and released under the Apache 2 license here:
This class represents a screen coordinate, in x and y coordinates
Instances of this class represent a width/height pair
This class represents a longitude and latitude pair
stop: function(event,
allowDefault)
Stops an event from propagating.
Close