Layer Class
The Layer class is the base class of all deck.gl layers, and it provides a number of base properties availabe in all layers.
Static Members
layerName (String, required)
This static property should contain the name of the layer, typically the name of layer's class (it cannot reliably be autodeduced in minified code). It is used as the default Layer id as well as for debugging and profiling.
defaultProps (Object, optional)
All deck.gl layers define a defaultProps static member listing their props and default values. Using defaultProps improves both the code readability and performance during layer instance construction.
Remarks:
- For developer that would like to write new layers, it's highly recommended to follow core deck.gl layers and define
defaultProps. In the future version of deck.gl, a check will be in place to enforce this
Constructor
Parameters:
props- Layer properties.
Basic Properties
id (String, optional)
- Default: layers
layerNamestatic property.
The id must be unique among all your layers at a given time. The default value of id is the Layer's "name". If more than one instance of a specific type of layer exist at the same time, they must possess different id strings for deck.gl to properly distinguish them.
Remarks:
- For React users:
idis similar to thekeyproperty used in React to match components between rendering calls, with the difference that deck.gl requires theidwhereas in React thekeyis optional but recommended. - A layer's name is defined by the
Layer.layerNamestatic member, or inferred from the constructor name (which is not robust in minified code). - Note that for sublayers (generated by composite layers), a composite layer id is generated by appending the sub layer's id to the parent layer's
id, so there are noidcollisions.
data (Array or Iterable, optional)
- Default:
[]
The data prop should contain an iterable JavaScript container, please see JavaScript [Symbol.iterator].
visible (Boolean, optional)
- Default:
true
Whether the layer is visible. Under most circumstances, using visible prop to control the visibility of layers are recommended over doing conditional rendering. Compare:
const layers = [ new MyLayer({data: ..., visible: showMyLayer}) ];
with
const layers = []; if (showMyLayer) { layers.push(new MyLayer({data: ...})); }
In the second example (conditional rendering) the layer state will be destroyed and regenerated every time the showMyLayer flag changes.
opacity (Number, required)
The opacity of the layer. deck.gl automatically applies gamma to the opacity in an attempt to make opacity changes appear linear (i.e. the opacity is visually proportional to the value of the prop)
Remarks
- While it is a recommended convention that all deck.gl layers should support the
opacityprop, it is up to each layer's fragment shader to implement support for opacity.
Interaction Properties
Layers can be interacted with using these properties.
pickable (Boolean, optional)
- Default:
false
Whether the layer responds to mouse pointer picking events.
onHover (Function, optional)
This callback will be called when the mouse enters/leaves an object of this deck.gl layer with a single parameter info.
If this callback returns a truthy value, the hover event is marked as handled and will not bubble up to the onLayerHover callback of the DeckGL canvas.
Requires pickable to be true.
onClick (Function, optional)
This callback will be called when the mouse clicks over an object of this deck.gl layer with a single parameter info.
If this callback returns a truthy value, the hover event is marked as handled and will not bubble up to the onLayerClick callback of the DeckGL canvas.
Requires pickable to be true.
highlightColor (Array, optional)
- Default:
[0, 0, 128, 128]
RGBA color to be used to render highlighted object.
highlightedObjectIndex (Integer, optional)
- Default:
-1
When provided a valid value corresponding object (one instance in instanced rendering or group of primitives with same picking color) will be highlighted with highlightColor.
autoHighlight (Boolean, optional)
- Default:
false
When true, current object pointed by mouse pointer (when hovered over) is highlighted with highlightColor.
Requires pickable to be true.
Coordinate System Properties
Normally only used when the application wants to work with coordinates that are not Web Mercator projected longitudes/latitudes.
coordinateSystem (Number, optional)
Specifies how layer positions and offsets should be geographically interpreted.
The default is to interpret positions as latitude and longitude, however it is also possible to interpret positions as meter offsets added to projection center specified by the coordinateOrigin prop.
See the article on Coordinate Systems for details.
coordinateOrigin ([Number, Number], optional)
Required when the coordinateSystem is set to COORDINATE_SYSTEM.METER_OFFSETS.
Specifies a longitude and a latitude from which meter offsets are calculated. See the article on Coordinate Systems for details
modelMatrix (Number[16], optional)
An optional 4x4 matrix that is multiplied into the affine projection matrices used by shader project GLSL function and the Viewport's project and unproject JavaScript function.
Allows local coordinate system transformations to be applied to a layer, which is useful when composing data from multiple sources that use different coordinate systems.
Note that the matrix projection is applied after the non-linear mercator projection calculations are resolved, so be careful when using model matrices with longitude/latitude encoded coordinates. They normally work best with non-mercator viewports or meter offset based mercator layers
Data Properties
There are a number of additional properties that provide extra control over data iteration, comparison and update.
dataComparator (Function, optional)
This prop causes the data prop to be compared using a custom comparison function. The comparison function is called with the old data and the new data objects, and is expected to return true if they compare equally.
Used to override the default shallow comparison of the data object.
As an illustration, the app could set this to e.g. 'lodash.isequal', enabling deep comparison of the data structure. This particular examples would obviously have considerable performance impact and should only be used as a temporary solution for small data sets until the application can be refactored to avoid the need.
numInstances (Number, optional)
deck.gl automatically derives the number of drawing instances from the data prop by counting the number of objects in data. However, the developer might want to manually override it using this prop.
updateTriggers (Object, optional)
Accessors such as getColor and getPosition are called to retrieve colors and positions when a layer is first added. From then on, to maximize performance, deck.gl does not recalculate colors or positions unless the data prop changes by shallow comparison.
Sometimes data remains the same, but the outcome of an accessor has changed. In the following example, this is caused by changes in the external values maleColor and femaleColor:
const layer = new ScatterplotLayer({
... // Other props
getColor: d => d.male ? maleColor : femaleColor
});
In this case, you need to explicitly inform deck.gl to re-evaluate getColor for all data items. You do so by defining updateTriggers:
const layer = new ScatterplotLayer({
... // Other props
getColor: d => d.male ? maleColor : femaleColor,
updateTriggers: {
getColor: [maleColor, femaleColor]
}
});
updateTriggers expect an object whose keys are names of accessor props of this layer, and values are one or more variables that affect the output of the accessors.
For example, updateTriggers.getColor is a list of variables that affect the output of
getColor. If either value in the array changes, all attributes that depend on
getColor will be updated.
The variables may be numbers, strings, objects or functions. During each rendering cycle, deck.gl shallow-compares them with the previous values.
Note: change of the data prop has higher priority than the updateTriggers. If the app supplies a new data object, then all attributes will be automatically updated, even if the updateTriggers have not changed. To block excessive attribute updates, set the dataComparator prop.
Render Properties
parameters (Function, optional)
The parameters allows applications to specify values for WebGL parameters such as blending mode, depth testing etc. Any parameters will be applied temporarily while rendering this layer only.
Please refer to the luma.gl v4 setParameters API for documentation on supported parameters and values.
getPolygonOffset (Function, optional)
- Default:
({layerIndex}) => [0, -layerIndex * 100]
When multiple layers are rendered on the same plane, z-fighting may create undesirable artifacts. To improve the visual quality of composition, deck.gl allows layers to use gl.polygonOffset to apply an offset to its depth. By default, each layer is offset a small amount by its index so that layers are cleanly stacked from bottom to top.
This accessor takes a single parameter uniform - an object that contains the current render uniforms, and returns an array of two numbers factor and units. Negative values pull layer towards the camera, and positive values push layer away from the camera. For more information, refer to the documentation and FAQ.
If the accessor is assigned a falsy value, polygon offset will be set to [0, 0].
Remarks: While this feature helps mitigate z-fighting, at close up zoom levels the issue might return because of the precision error of 32-bit projection matrices. Try set the fp64 prop to true in this case.
Members
Remarks: Layer members are designed to support the creation of new layers or layer sub-classing and are NOT intended to be used by applications.
context (Object)
The context object stores information that are shared by all layers.
gl(WebGLRenderingContext) - WebGL context of the current canvas.viewport(Viewport) - The current viewport
state (Object)
The state object allows a layer to store persistent information cross rendering cycles.
attributeManager(AttributeManager) - The attribute manager of this layer.
props (Object)
Properties of this layer.
Methods
Layer methods are designed to support the creation of new layers or layer sub-classing and are NOT intended to be called by applications.
General Methods
setState
Used to update the layers state object. Calling this method will also cause the layer to rerender.
Layer Lifecycle Methods
For more information about when these methods are called, see layer lifecycle.
initializeState
This method is called only once for each layer to set up the initial state.
initializeState(context)
context- The layer context is supplied as a parametercontext.gl(WebGLRenderingContext) - gl context- ...
deck.gl will already have created the state object at this time, and added the gl context and the attributeManager state.
shouldUpdateState
Called during each rendering cycle when layer properties or context has been updated and before layers are drawn.
shouldUpdateState({props, oldProps, context, oldContext, changeFlags})
Parameters:
props(Object) - Layer properties from the current rendering cycle.oldProps(Object) - Layer properties from the previous rendering cycle.context(Object) - Layer context from the current rendering cycle.oldContext(Object) - Layer context from the previous rendering cycle.changeFlags: an object that contains the following boolean flags:dataChanged,propChanged,viewportChanged,somethingChanged
Returns:
truethis layer needs to be updated.
Remarks:
- Prop change is determined by shallow comparison.
- Data change is determined by shallow comparison of
props.dataunlessdataComparatoris supplied. - The default implementation returns
trueif any change has been detected in data or props, but ignores viewport changes.
updateState
Called when a layer needs to be updated.
updateState({props, oldProps, context, oldContext, changeFlags})
Parameters:
props(Object) - Layer properties from the current rendering cycle.oldProps(Object) - Layer properties from the previous rendering cycle.context(Object) - Layer context from the current rendering cycle.oldContext(Object) - Layer context from the previous rendering cycle.changeFlags: an object that contains the following boolean flags:dataChanged,propChanged,viewportChanged,somethingChanged
The default implementation will invalidate all attributeManager attributes if the data prop has changed.
draw
Called on a layer to render to the WebGL canvas.
draw({moduleParameters, uniforms, ..., context})
Parameters:
uniforms: an object that contains all the default unforms to be passed to the shaders.context- The layer context is supplied as a parametercontext.gl(WebGLRenderingContext) - gl context- ...
The default implementation looks for a variable model in the layer's state (which is expected to be an instance of the luma.gl Model class) and calls draw on that model with the parameters.
getPickingInfo
Called when a layer is being hovered or clicked, before any user callbacks are called. The layer can override or add additional fields to the info object that will be passed to the callbacks.
Parameters:
pickParams(Object)pickParams.info(Object) - The currentinfoobject. By default it contains the following fields:x(Number) - Mouse position x relative to the viewport.y(Number) - Mouse position y relative to the viewport.lngLat([Number, Number]) - Mouse position in world coordinates. Only applies ifcoordinateSystemisCOORDINATE_SYSTEM.LNGLAT.color(Number[4]) - The color of the pixel that is being picked. It represents a "picking color" that is encoded bylayer.encodePickingColor().index(Number) - The index of the object that is being picked. It is the returned value oflayer.decodePickingColor().picked(Boolean) -trueifindexis not-1.
pickParams.mode(String) - One ofhoverandclick
Returns:
- An
infoobject with optional fields about what was picked. This object will be passed to the layer'sonHoveroronClickcallbacks. null, if the corresponding event should cancelled with no callback functions called.
The default implementation populates the info.object field with the info.index element from the layer's data prop.
finalizeState
This method is called before the layer is being removed. A layer should release all resources created during its life span.
Layer Projection Methods
While most projection is handled "automatically" in the layers vertex shader, it is occasionally useful to be able to work in the projected coordinates in JavaScript while calculating uniforms etc.
project
Projects a map coordinate using the current viewport settings.
Parameters:
coordinates(Array) -[lng, lat, altitude]Passing an altitude is optional.opts(Object)topLeft(Boolean, optional) - Whether projected coords are top left. Default totrue.
Returns:
- A screen coordinates array
[x, y]or[x, y, z]if an altitude was given.
unproject
Unprojects a pixel coordinate using the current viewport settings.
Parameters:
pixels(Array) -[x, y, z]Passing azis optional.opts(Object)topLeft(Boolean, optional) - Whether projected coords are top left. Default totrue.
Returns:
- A map coordinates array
[lng, lat]or[lng, lat, altitude]if azwas given.
projectFlat
Projects a map coordinate using the current viewport settings, ignoring any perspective tilt. Can be useful to calculate screen space distances.
Parameters:
coordinates(Array) -[longitude, latitude]coordinates.scale(Number) - Map zoom scale calculated fromMath.pow(2, zoom).
Returns:
- Screen coordinates in
[x, y].
unprojectFlat
Unrojects a pixel coordinate using the current viewport settings, ignoring any perspective tilt (meaning that the pixel was projected).
Parameters:
pixels(Array) -[x, y]scale(Number) - Map zoom scale calculated fromMath.pow(2, zoom).
Returns:
- Map or world coordinates in
[longitude, latitude].
screenToDevicePixels
Simply multiplies pixels parameter with window.devicePixelRatio if available. Useful to adjust e.g. line widths to get more consistent visuals between low and high resolution displays.
Parameters:
pixels(Number) - The number in screen pixels.
Retures:
- A number in device pixels
Layer Picking Methods
For the usage of these methods, see how picking works.
decodePickingColor
Converts a color to a "sub-feature index" number.
This color is encoded by the layer.encodePickingColor() method.
Parameters:
color(Array) - The color to be decoded in[r, g, b].
Returns:
- A number representing the index of the feature. The null picking color (See
Layer.nullPickingColor) will be decoded as -1.
Note: The null picking color is returned when a pixel is picked that is not covered by the layer, or when they layer has selected to render a pixel using the null picking color to make it unpickable.
encodePickingColor
Converts a "sub-feature index" number to a color. This color can later be decoded by the layer.decodePickingColor() method.
Parameters:
index(Integer) - The index to be encoded.
Returns:
- An array of
[r, g, b].
To get a color that does not correspond to any sub-feature, use layer.nullPickingColor().
Notes:
- indices to be encoded must be integers larger than or equal to 0.
- Picking colors are 24 bit values and can thus encode up to 16 million indices.
nullPickingColor
Returns:
- a "null" picking color which is equal the the color of pixels not covered by the layer. This color is guaranteed not to match any index value greater than or equal to zero.