Contains utility classes and methods used by geojs.
Classes
Type Definitions
-
geo.util.cssColorConversionRecordobject
-
Properties:
Name Type Description name
string The name of the color conversion.
regex
RegExp 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'sexec
function. It outputs ageo.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
andrgba
are aliases of each other, as arehsl
andhsla
.Properties:
Name Type Description cssColorConversions
Array.<geo.util.cssColorConversionRecord> -
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
, andowner
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
istrue
. 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.centerFromPerimeter(coor){geo.geoPosition|undefined}
-
Return the coordinate associated with the center of the perimeter formed from a list of points. This averages all of the vertices in the perimeter weighted by the line length on either side of each point. Functionally, this is the same as the average of all the points of the lines of the perimeter.
Name Type Description coor
geo.geoPolygon An array of coordinates. This can also be a polygon object with an
outer
element with an array of coordinates.Returns:
Type Description geo.geoPosition | undefined The position for the center, or undefined
if no such position exists. -
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 multiplied 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 defineda
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.crossedLineSegmentPolygon2d(pt1, pt2, poly){boolean}
-
Determine if a line segment crosses any line segments of a polygon.
Name Type Description pt1
geo.geoPosition One endpoint of the line.
pt2
geo.geoPosition The other endpoint of the line.
poly
geo.polygonObject The polygon.
Returns:
Type Description boolean True if the segment cross any segment of the polygon. -
staticgeo.util.crossedLineSegments2d(seg1pt1, seg1pt2, seg2pt1, seg2pt2){boolean}
-
Determine if two line segments cross. They are not considered crossing if they share a vertex. They are crossing if either of one segment's vertices are collinear with the other segment.
Name Type Description seg1pt1
geo.geoPosition One endpoint of the first segment.
seg1pt2
geo.geoPosition The other endpoint of the first segment.
seg2pt1
geo.geoPosition One endpoint of the second segment.
seg2pt2
geo.geoPosition The other endpoint of the second segment.
Returns:
Type Description boolean True if the segments cross. -
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 XDebounced with
at_begin
specified as true: ||||||||||||||||||||||||| (pause) ||||||||||||||||||||||||| X XThe 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 fordelay
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, tocallback
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 | HTMLElement The element that receives 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.distance2dToLineSquared(pt, line1, line2){number}
-
Get the square of the Euclidean 2D distance between a point and a line segment.
Name Type Description pt
geo.geoPosition The point.
line1
geo.geoPosition One end of the line.
line2
geo.geoPosition The other end of the line.
Returns:
Type Description number The distance squared. -
staticgeo.util.distanceToPolygon2d(pt, poly, onlySign){number}
-
Get the signed Euclidean 2D distance between a point and a polygon. The distance is positive if the point is inside of the polygon.
Name Type Description pt
geo.geoPosition The point.
poly
geo.polygonObject The polygon.
onlySign
boolean optional If truthy, only the sign of the answer is significant.
Returns:
Type Description number The signed distance. -
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 returnsf
. -
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.getMinMaxValues(values, min, max, limit){object}
-
Given an array, return the minimum and maximum values within the array. If a numeric value is specified for one or the other, return that instead.
Name Type Default Description values
Array.<number> An array of numeric values.
min
number optional If specified, use this instead of calculating the minimum.
max
number optional If specified, use this instead of calculating the maximum.
limit
boolean false optional If truthy, if
min
is specified, the returnedmin
will be the larger of the specified value and the computed value, and ifmax
is specified, the returned value will be the smaller of the specified value and the computed value.Returns:
Type Description object An object with min
andmax
, both numbers. If the array is empty,undefined
may be returned for themin
andmax
. -
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
, andowner
match. Anull
orundefined
value will match all actions. If using ageo.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.htmlToImageSupported(){boolean|jQuery.Deferred}
-
Check if the current browser supports covnerting html to an image via an svg foreignObject and canvas. If this has not been checked before, it returns a Deferred that resolves to a boolean (never rejects). If the check has been done before, it returns a boolean.
Returns:
Type Description boolean | jQuery.Deferred -
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.isObject(value){boolean}
-
Test if an item is an object. This uses typeof not instanceof, since instanceof will return false for some things that we expect to be objects.
Name Type Description value
* The item to test.
Returns:
Type Description boolean True if the tested item is an object. -
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 video 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, whereasmat3
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, whereasmat4
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
, andz
properties. -
staticgeo.util.pixelCoordinateParams(node, width, height, tileWidth, tileHeight){object}
-
Return recommended defaults for map parameters and osm or tile layer parameters 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 nullable 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
andlayer
properties.map
is an object that can be passed togeo.map
, andlayer
is an object that can be passed tomap.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. The point and polygon must be in the same coordinate system. A point exactly on the edge is not considered inside.
Name Type Description point
geo.point2D The test point.
outer
Array.<geo.point2D> | geo.polygonObject The outer boundary of the polygon or a polygon object that has both the inner and outer boundaries.
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.pointToTriangleBasis2d(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.range(start, end, step){Array.<number>}
-
Create an integer array contains elements from one integer to another integer.
Name Type Default Description start
number The start integer.
end
number The end integer.
step
number 1 optional The step.
Returns:
Type Description Array.<number> An array of integers. -
staticgeo.util.rdpLineSimplify(pts, tolerance, closed, noCrossLines){Array.<geo.geoPosition>}
-
Remove vertices from a chain of 2d line segments so that it is simpler but is close to the original overall shape within some tolerance limit. This is the Ramer–Douglas–Peucker algorithm. The first and last points will always remain the same for open lines. For closed lines (polygons), this picks an point that likely to be significant and then reduces it, possibly returning a single point.
Name Type Description pts
Array.<geo.geoPosition> A list of points forming the line or polygon.
tolerance
number The maximum variation allowed. A value of zero will only remove perfectly collinear points.
closed
boolean optional If true, this is a polygon rather than an open line. In this case, it is possible to get back a single point.
noCrossLines
Array.<Array.<geo.geoPosition>> optional nullable A falsy value to allow the resultant line to cross itself, an empty array (
[]
) to prevent self-crossing, or an array of line segments to prevent self-crossing and disallow crossing any line segment in the list. Each entry in the list is an open line (with one segment less than the number of vertices). If self-crossing is prohibited, the resultant point set might not be as simplified as it could be.Returns:
Type Description Array.<geo.geoPosition> The new point set. -
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.segmentCrossesLineList2d(pt1, pt2, lineList){boolean}
-
Check if a line segment crosses any segment from a list of lines. The segment is considered crossing it it touches a line segment, unless that line segment shares a vertex with the segment.
Name Type Description pt1
geo.geoPosition One end of the line segment.
pt2
geo.geoPosition The other end of the line segment.
lineList
Array.<Array.<geo.geoPosition>> A list of open lines. Each line is a list of vertices. The line segment is checked against each segment of each line in this list.
Returns:
Type Description boolean True if the segment crosses any line segment. -
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 fordelay
milliseconds, the internal counter is reset)callback
function optional A function to be executed after
delay
milliseconds. Thethis
context and all arguments are passed through, as-is, tocallback
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 thegeo.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 viatimeFunctionReport('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.triangleTwiceSignedArea2d(pt1, pt2, pt3){number}
-
Get twice the signed area of a 2d triangle.
Name Type Description pt1
geo.geoPosition A vertex.
pt2
geo.geoPosition A vertex.
pt3
geo.geoPosition A vertex.
Returns:
Type Description number Twice the signed area. -
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, whereasvec3
defaults to 32-bit floats.Returns:
Type Description array Zeroed-out vec3 compatible array. -
staticgeo.util.wrapAngle(value){number}
-
Given a value in radians, return a value wrapped to the range [-PI, PI).
Name Type Description value
number A value in radians.
Returns:
Type Description number The wrapped value.