Namespace: util

geo. util

Contains utility classes and methods used by geojs.

Classes

ClusterGroup
ClusterTree
DistanceGrid

Type Definitions

geo.util.cssColorConversionRecordobject

Properties:
Name Type Description
name string

The name of the color conversion.

regex RegEx

A regex that, if it matches the color string, will cause the process function to be invoked.

process function

A function that takes (color, match) with the original color string and the results of matching the regex using the regex's exec function. It outputs a geo.geoColorObject color object or the original color string if there is still a parsing failure.

Static Members

staticgeo.util.cssAngleUnitsBase

A dictionary of conversion factors for angular CSS measurements.

staticgeo.util.cssColorConversions

A list of regex and processing functions for color conversions to rgb objects. Each entry is a geo.util.cssColorConversionRecord. In general, these conversions are somewhat more forgiving than the css specification (see https://drafts.csswg.org/css-color/) in that percentages may be mixed with numbers, and that floating point values are accepted for all numbers. Commas are optional. As per the latest draft standard, rgb and rgba are aliases of each other, as are hsl and hsla.

Properties:
Name Type Description
cssColorConversions

staticgeo.util.cssNumberRegex

A regular expression string that will parse a number (integer or floating point) for CSS properties.

staticgeo.util.radiusEarth

Radius of the earth in meters, from the equatorial radius of SRID 4326.

Static Methods

staticgeo.util.actionMatch(inputs, modifiers, actions){geo.actionRecord}

Determine if the current inputs and modifiers match a known action.

Name Type Description
inputs object

Aan object where each input that is currently active is truthy. Common inputs are left, right, middle, wheel, pan, rotate.

modifiers object

An object where each currently applied modifier is truthy. Common modifiers are shift, ctrl, alt, meta.

actions Array.<geo.actionRecord>

A list of actions to compare to the inputs and modifiers. The first action that matches will be returned.

Returns:
Type Description
geo.actionRecord A matching action or undefined.

staticgeo.util.addAction(actions, action, toEnd)

Add an action to the list of handled actions.

Name Type Description
actions Array.<geo.actionRecord>

An array of actions to adjust as needed.

action geo.actionRecord

An object defining the action. Use action, name, and owner to make this entry distinct if it will need to be removed later.

toEnd boolean

The action is added at the beginning of the actions list unless toEnd is true. Earlier actions prevent later actions with the similar input and modifiers.

staticgeo.util.adjustActions(actions)

Ensure that the input and modifiers properties of all actions are objects, not plain strings.

Name Type Description
actions Array.<geo.actionRecord>

An array of actions to adjust as needed.

staticgeo.util.compareArrays(a1, a2){boolean}

Compare two arrays and return if their contents are equal.

Name Type Description
a1 array

First array to compare.

a2 array

Second array to compare.

Returns:
Type Description
boolean true if the contents of the arrays are equal.

staticgeo.util.convertColor(color){geo.geoColorObject}

Convert a color to a standard rgb object. Allowed inputs:

  • rgb object with optional 'a' (alpha) value.
  • css color name
  • #rrggbb, #rrggbbaa, #rgb, #rgba hexadecimal colors
  • rgb(), rgba(), hsl(), and hsla() css colors
  • transparent The output object always contains r, g, b on a scale of [0-1]. If an alpha value is specified, the output will also contain an 'a' value on a scale of [0-1]. Objects already in rgb format are not checked to make sure that all parameters are in the range of [0-1], but string inputs are so validated.
Name Type Description
color geo.geoColor

Any valid color input.

Returns:
Type Description
geo.geoColorObject An rgb color object, possibly with an 'a' value. If the input cannot be converted to a valid color, the input value is returned.

staticgeo.util.convertColorAndOpacity(color, opacity, defaultColor){geo.geoColorObject}

Convert a color (possibly with opacity) and an optional opacity value to a color object that always has opacity. The opacity is guaranteed to be within [0-1]. A valid color object is always returned.

Name Type Default Description
color geo.geoColor optional

Any valid color input. If an invalid value or no value is supplied, the defaultColor is used.

opacity number 1 optional

A value from [0-1]. This is multipled with the opacity from color.

defaultColor geo.geoColorObject {r: 0, g: 0, b: 0} optional

The color to use if an invalid color is supplied.

Returns:
Type Description
geo.geoColorObject An rgba color object.

staticgeo.util.convertColorToHex(color, allowAlpha){string}

Convert a color to a six or eight digit hex value prefixed with #.

Name Type Description
color geo.geoColorObject

The color object to convert.

allowAlpha boolean optional

If truthy and color has a defined a value, include the alpha channel in the output. If 'needed', only include the alpha channel if it is set and not 1.

Returns:
Type Description
string A color string.

staticgeo.util.convertColorToRGBA(color){string}

Convert a color to a css rgba() value.

Name Type Description
color geo.geoColorObject

The color object to convert.

Returns:
Type Description
string A color string.

staticgeo.util.debounce(delay, at_begin, callback, accumulator){function}

Debounce execution of a function. Debouncing, unlike throttling, guarantees that a function is only executed a single time, either at the very beginning of a series of calls, or at the very end. If you want to simply rate-limit execution of a function, see the <jQuery.throttle> method.

In this visualization, | is a debounced-function call and X is the actual callback execution:

::

Debounced with at_begin specified as false or unspecified: ||||||||||||||||||||||||| (pause) ||||||||||||||||||||||||| X X

Debounced with at_begin specified as true: ||||||||||||||||||||||||| (pause) ||||||||||||||||||||||||| X X

The bulk of the work is handled by the geo.util.throttle function.

Name Type Default Description
delay number

A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.

at_begin boolean false optional

If at_begin is false or unspecified, callback will only be executed delay milliseconds after the last debounced-function call. If at_begin is true, callback will be executed only at the first debounced-function call. (After the throttled-function has not been called for delay milliseconds, the internal counter is reset)

callback function

A function to be executed after delay milliseconds. The this context and all arguments are passed through, as-is, to callback when the debounced-function is executed.

accumulator function optional

A function to be executed (synchronously) during each call to the wrapped function. Typically, this this method is used to accumulate values that the callback uses when it finally executes.

Returns:
Type Description
function A new, debounced, function.
Example
var debounced = geo.util.debounce( delay, [ at_begin, ] callback );
$('selector').bind( 'someevent', debounced );
$('selector').unbind( 'someevent', debounced );

staticgeo.util.dereferenceCssUrls(css, styleElem, styleDefer, styleKey, baseUrl)

Check css text. Any url(http[s]...) references are dereferenced and stored as local base64 urls.

Name Type Description
css string

The css to parse for urls.

styleElem jQuery.selector | DOMElement

The element that receivs the css text after dereferencing or the DOM element that has style that will be updated.

styleDefer jQuery.Deferred

A Deferred to resolve once dereferencing is complete.

styleKey string optional

If unset, styleElem is a header element. If set, styleElem is a DOM element and the named style will be updated.

baseUrl string optional

If present, this is the base for relative urls.

staticgeo.util.dereferenceElements(elem){Array.<jQuery.Deferred>}

Check svg image and html img tags. If the source is set, load images explicitly and convert them to local data:image references.

Name Type Description
elem jQuery.selector

A jQuery selector or element set that may contain images.

Returns:
Type Description
Array.<jQuery.Deferred> A list of deferred objects that resolve when images are dereferenced.

staticgeo.util.ensureFunction(f){function}

Return a function. If the supplied object is a function, return it. Otherwise, return a function that returns the argument.

Name Type Description
f object

An object that might be a function.

Returns:
Type Description
function A function. Either f or a function that returns f.

staticgeo.util.escapeUnicodeHTML(text){string}

Escape any character in a string that has a code point >= 127.

Name Type Description
text string

The string to escape.

Returns:
Type Description
string The escaped string.

staticgeo.util.getGeomBuffer(geom, srcName, len, allowLarger, allocateLarger){Float32Array}

Get a buffer for a vgl geometry source. If a buffer already exists and is the correct size, return it. Otherwise, allocate a new buffer; any data in an old buffer is discarded.

Name Type Default Description
geom vgl.geometryData

The geometry to reference and modify.

srcName string

The name of the source.

len number

The number of elements for the array.

allowLarger number 0.2 optional

If the existing buffer is larger than requested, don't reallocate it unless it exceeds the size of len * (1 + allowLarger).

allocateLarger number 0.1 optional

If reallocating an existing buffer, allocate len * (1 + allocateLarger) to reduce the need to reallocate on subsequent calls. If this is the first allocation (the previous size was 0), len is allocated.

Returns:
Type Description
Float32Array A buffer for the named source.

staticgeo.util.hasAction(actions, action, name, owner){geo.actionRecord}

Check if an action is in the actions list. An action matches if the action, name, and owner match. A null or undefined value will match all actions. If using a geo.actionRecord object, this is the same as passing (action.action, action.name, action.owner).

Name Type Description
actions Array.<geo.actionRecord>

An array of actions to search.

action geo.actionRecord | string

Either an action object or the name of an action.

name string optional

Optional name associated with the action.

owner string optional

Optional owner associated with the action.

Returns:
Type Description
geo.actionRecord The first matching action or null.

staticgeo.util.htmlToImage(elem, parents){jQuery.Deferred}

Convert an html element to an image. This attempts to localize any images within the element. If there are other external references, the image may not work due to security considerations.

Name Type Description
elem jQuery.selector

Either a jquery selector or an HTML element. This may contain multiple elements. The direct parent and grandparent of the element are used for class information.

parents number optional

Number of layers up to travel to get class information.

Returns:
Type Description
jQuery.Deferred A jquery deferred object which receives an HTML Image element when resolved.

staticgeo.util.isFunction(f){boolean}

Test if an object is a function.

Name Type Description
f object

An object that might be a function.

Returns:
Type Description
boolean true if the object is a function.

staticgeo.util.isReadyImage(img, allowFailedImage){boolean}

Check if an object an HTML Image element that is fully loaded.

Name Type Description
img object

An object that might be an HTML Image element.

allowFailedImage boolean optional

If true, an image element that has a source and has failed to load is also considered 'ready' in the sense that it isn't expected to change to a better state.

Returns:
Type Description
boolean true if this is an image that is ready.

staticgeo.util.isReadyVideo(vid, allowFailedVideo){boolean}

Check if an object an HTMLVideoElement element that is loaded.

Name Type Description
vid object

An object that might be an HTMLVideoElement.

allowFailedVideo boolean optional

If true, an viedo element that has a source and has failed to load is also considered 'ready' in the sense that it isn't expected to change to a better state.

Returns:
Type Description
boolean true if this is a video that is ready.

staticgeo.util.mat3AsArray(){array}

Create a mat3 that is always an array. This should only be used if it will not be used in a WebGL context. Plain arrays usually use 64-bit float values, whereas mat3 defaults to 32-bit floats.

Returns:
Type Description
array Identity mat3 compatible array.

staticgeo.util.mat4AsArray(){array}

Create a mat4 that is always an array. This should only be used if it will not be used in a WebGL context. Plain arrays usually use 64-bit float values, whereas mat4 defaults to 32-bit floats.

Returns:
Type Description
array Identity mat4 compatible array.

staticgeo.util.mockWebglRenderer(supported)

Replace webgl.renderer with a mocked version for testing in a non-webGL state. Use restoreWebglRenderer to unmock. Call vgl.mockCounts() to get the number of times different webGL functions have been called.

Name Type Default Description
supported boolean true optional

If false, then the webgl renderer will indicate that this is an unsupported browser environment.

staticgeo.util.normalizeCoordinates(p){geo.geoPosition}

Normalize a coordinate object into geo.geoPosition form. The input can be a 2 or 3 element array or an object with a variety of properties.

Name Type Description
p object | array

The point to convert.

Returns:
Type Description
geo.geoPosition The point as an object with x, y, and z properties.

staticgeo.util.pixelCoordinateParams(node, width, height, tileWidth, tileHeight){object}

Return recommended defaults for map parameters and osm or tile layer paramaters where the expected intent is to use the map in pixel coordinates (upper left is (0, 0), lower right is (width, height).

Name Type Description
node string optional

DOM selector for the map container.

width number

Width of the whole map contents in pixels.

height number

Height of the whole map contents in pixels.

tileWidth number optional

If an osm or tile layer is going to be used, the width of a tile.

tileHeight number optional

If an osm or tile layer is going to be used, the height of a tile.

Returns:
Type Description
object An object with map and layer properties. map is an object that can be passed to geo.map, and layer is an object that can be passed to map.createLayer.
Example

The returned objects can be modified or extended.

var results = pixelCoordinateParams('#map', 10000, 9000);
var map = geo.map($.extend(results.map, {clampZoom: false}));
map.createLayer('osm', results.layer);

staticgeo.util.pointInPolygon(point, outer, inner, range){boolean}

Check if a point is inside of a polygon. Algorithm description: http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html The point and polygon must be in the same coordinate system.

Name Type Description
point geo.point2D

The test point.

outer Array.<geo.point2D>

The outer boundary of the polygon.

inner Array.<Array.<geo.point2D>> optional

A list of inner boundaries (holes).

range object optional

If specified, this is the extent of the outer polygon and is used for early detection.

Name Type Description
min geo.point2D

The minimum value of coordinates in the outer polygon.

max geo.point2D

The maximum value of coordinates in the outer polygon.

Returns:
Type Description
boolean true if the point is inside or on the border of the polygon.

staticgeo.util.pointTo2DTriangleBasis(point, vert0, vert1, vert2){geo.point2D}

Return a point in the basis of the triangle. If the point is located on a vertex of the triangle, it will be at vert0: (0, 0), vert1: (1, 0), vert2: (0, 1). If it is within the triangle, its coordinates will be 0 <= x <= 1, 0 <= y <= 1, x + y <= 1. The point and vertices must be in the same coordinate system.

Name Type Description
point geo.point2D

The point to convert.

vert0 geo.point2D

Vertex 0 of the triangle.

vert1 geo.point2D

Vertex 1 (x direction) of the triangle.

vert2 geo.point2D

Vertex 2 (y direction) of the triangle.

Returns:
Type Description
geo.point2D The point in the triangle basis, or undefined if the triangle is degenerate.

staticgeo.util.randomString(n){string}

Return a random string of length n || 8. The string consists of mixed-case ASCII alphanumerics.

Name Type Default Description
n number 8 optional

The length of the string to return.

Returns:
Type Description
string A string of random characters.

staticgeo.util.removeAction(actions, action, name, owner){number}

Remove all matching actions. Actions are matched as with hasAction.

Name Type Description
actions Array.<geo.actionRecord>

An array of actions to adjust as needed.

action geo.actionRecord | string

Either an action object or the name of an action.

name string optional

Optional name associated with the action.

owner string optional

Optional owner associated with the action.

Returns:
Type Description
number The number of actions that were removed.

staticgeo.util.restoreWebglRenderer()

Unmock the vgl renderer.

staticgeo.util.throttle(delay, no_trailing, callback, accumulator, debounce_mode){function}

Throttle execution of a function. Especially useful for rate limiting execution of handlers on events like resize and scroll. If you want to rate-limit execution of a function to a single time see geo.util.debounce.

In this visualization, | is a throttled-function call and X is the actual callback execution:

Throttled with `no_trailing` specified as false or unspecified:
||||||||||||||||||||||||| (pause) |||||||||||||||||||||||||
X    X    X    X    X    X        X    X    X    X    X    X

Throttled with `no_trailing` specified as true:
||||||||||||||||||||||||| (pause) |||||||||||||||||||||||||
X    X    X    X    X             X    X    X    X    X

This is also used to handle debouncing a function.

Name Type Default Description
delay number

A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.

no_trailing boolean false optional

If no_trailing is true, callback will only execute every delay milliseconds while the throttled-function is being called. If no_trailing is false or unspecified, callback will be executed one final time after the last throttled-function call. (After the throttled-function has not been called for delay milliseconds, the internal counter is reset)

callback function

A function to be executed after delay milliseconds. The this context and all arguments are passed through, as-is, to callback when the throttled-function is executed.

accumulator function optional

A function to be executed (synchronously) during each call to the wrapped function. Typically, this this method is used to accumulate values that the callback uses when it finally executes.

debounce_mode boolean optional

See the at_begin parameter of the geo.util.debounce function.

Returns:
Type Description
function The throttled version of callback.
Example
var throttled = geo.util.throttle( delay, [ no_trailing, ] callback );
$('selector').bind( 'someevent', throttled );
$('selector').unbind( 'someevent', throttled );

staticgeo.util.timeFunctionStart(name, reset)

Note the start time of a function (or any other section of code). This should be paired with timeFunctionStop, which will collect statistics on the amount of time spent in a function.

Name Type Description
name string

Name to use for tracking the timing.

reset boolean

If true, clear old tracking data for this named tracker.

staticgeo.util.timeFunctionStop(name)

Note the stop time of a function (or any other section of code). This should be paired with timeFunctionStart.

Name Type Description
name string

Name to use for tracking the timing.

staticgeo.util.timeReport(name){object}

Report on one or all of the tracked timings.

Name Type Description
name string optional

A name to report on, or undefined to report all.

Returns:
Type Description
object An object with timing information, or an object with properties for all tracked timings, each of which contains timing information.

staticgeo.util.timeRequestAnimationFrame(stop, reset, threshold, keep)

Start or stop tracking the time spent in requestAnimationFrame. If tracked, the results can be fetched via timeFunctionReport('requestAnimationFrame').

Name Type Default Description
stop boolean optional

Falsy to start tracking, truthy to start tracking.

reset boolean optional

If truthy, reset the statistics.

threshold number 15 optional

If present, set the threshold in milliseconds used in tracking slow callbacks.

keep number 200 optional

If present, set the number of recent frame times to track.

staticgeo.util.vec3AsArray(){array}

Create a vec3 that is always an array. This should only be used if it will not be used in a WebGL context. Plain arrays usually use 64-bit float values, whereas vec3 defaults to 32-bit floats.

Returns:
Type Description
array Zeroed-out vec3 compatible array.