Atlaslog
Atlaslog / deck.gl / API / Layer
deck.gl · API reference

Layer

Quick answer

The Layer class is the base class of all deck.gl layers, and it provides a number of base properties available in all layers.

Last verified 2026-11-03 · deck.gl 9.0 · Cite this page
Runnable examplesChinese noteAll API topics

The Layer class is the base class of all deck.gl layers, and it provides a number of base properties available 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. See prop types.

Constructor​

new Layer(...props);

Parameters:

Notes:

Properties​

Basic Properties​

id (string, optional)​

The id must be unique among all your layers at a given time. It is highly recommended to set id explicitly. If more than one instance of a specific type of layer exist at the same time, they will require different ids for deck.gl to properly distinguish them.

Remarks:

data (Iterable | string | Promise | AsyncIterable | object, optional)​

deck.gl layers typically expect data to be one of the following types:

data.attributes​

When using a non-iterable data object, the object may optionally contain a field attributes, if the application wishes to supply binary buffers directly to the layer. This use case is discussed in detail in the performance developer guide.

The keys in data.attributes correspond to the accessor name that the binary should replace, for example getPosition, getColor. See each layer's documentation for available accessor props.

Each value in data.attributes may be one of the following formats:

Remarks

visible (boolean, optional)​

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, optional)​

The opacity of the layer.

Remarks:

extensions (LayerExtension[], optional)​

Add additional functionalities to this layer. See the list of available extensions.

onError (Function, optional)​

Called when this layer encounters an error, with the following arguments:

If this callback is supplied and returns true, the error is marked as handled and will not bubble up to the onError callback of the Deck instance.

Interaction Properties​

Layers can be interacted with using these properties.

pickable (boolean | '3d', optional)​

Whether the layer responds to mouse pointer picking events.

When set to true, the layer can be picked and the picking info will contain 2D coordinates (assuming z=0).

When set to '3d', the layer can be picked with depth picking enabled. The coordinate field in the picking info object will be a 3D point, unprojected onto the actual picked geometry. This is useful for getting accurate 3D coordinates in layers with elevation or 3D models, but comes with a performance overhead.

onHover (Function, optional)​

This callback will be called when the mouse enters/leaves an object of this deck.gl layer with the following parameters:

If this callback returns a truthy value, the hover event is marked as handled and will not bubble up to the onHover 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 the following parameters:

If this callback returns a truthy value, the click event is marked as handled and will not bubble up to the onClick callback of the DeckGL canvas.

Requires pickable to be true.

onDragStart (Function, optional)​

This callback will be called when the mouse starts dragging an object of this deck.gl layer with the following parameters:

If this callback returns a truthy value, the dragstart event is marked as handled and will not bubble up to the onDragStart callback of the DeckGL canvas.

Requires pickable to be true.

onDrag (Function, optional)​

This callback will be called when the mouse drags an object of this deck.gl layer with the following parameters:

If this callback returns a truthy value, the drag event is marked as handled and will not bubble up to the onDrag callback of the DeckGL canvas.

Requires pickable to be true.

onDragEnd (Function, optional)​

This callback will be called when the mouse releases an object of this deck.gl layer with the following parameters:

If this callback returns a truthy value, the dragend event is marked as handled and will not bubble up to the onDragEnd callback of the DeckGL canvas.

Requires pickable to be true.

highlightColor (Color | Function, optional)​

RGBA color to blend with the highlighted object (either the hovered over object if autoHighlight: true, or the object at the index specified by highlightedObjectIndex). When the value is a 3 component (RGB) array, a default alpha of 255 is applied.

highlightedObjectIndex (number | null, optional)​

The index of the object in data to highlight. If specified, overrides the effect of autoHighlight.

When set to an integer that corresponds to an object, the object will be highlighted with highlightColor. When set to an integer that does not correspond to an object (e.g. -1), nothing is highlighted.

autoHighlight (boolean, optional)​

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 (string, optional)​

Specifies how layer positions and offsets should be geographically interpreted. One of:

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[3], optional)​

Specifies a reference point for coordinates that are expressed as offsets. Used when the coordinateSystem is set to one of the following modes:

See the article on Coordinate Systems for details.

wrapLongitude (boolean, optional)​

Normalizes geometry longitudes. Only works with the LNGLAT coordinate system.

When enabled on PathLayer, PolygonLayer and GeoJsonLayer, the paths/polygons are interpretted such that the connection between any two neighboring vertices is drawn on the shorter side of the world, and split into two if it crosses the 180th meridian. Note that this introduces CPU overhead at runtime. When working with static data, it is recommend that you preprocess the features offline instead of using this option.

When enabled on layers with position pairs, such as LineLayer and ArcLayer, they will draw the shortest path between source and target positions. If the shortest path crosses the 180th meridian, it is split into two segments.

When enabled on other layers, the effect is applied by moving the anchor point into the [-180, 180] range.

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.

The function receives two arguments:

And should return true if the two values are considered equal (no update needed), or false if the data has changed.

dataTransform (Function, optional)​

Executed to manipulate remote data when it's fetched. This callback applies when data is assigned a value that is either string (URL), Promise or an async iterable.

The function receives two arguments:

And must return a valid data object: an array, an iterable or a non-iterable object that contains a length field. See documentation of the data prop for details.

_dataDiff (Function, optional) Experimental​

This function is called when the data changes, either shallowly when dataComparator is not supplied or because dataComparator returns false, to retrieve the indices of the changed objects. By default, when data changes, the attributes of all objects are recalculated. If this prop is supplied, only the attributes of the specified objects will be updated. This can lead to significant performance improvement if a few rows in a large data table need to change frequently:

let data: DataType[] = [...];

function updateData(index: number, item: DataType) {
// make a shallow copy
data = data.slice();
data[index] = item;
const layers = [
new ScatterplotLayer<DataType>({
data,
// Only update the attributes at `index``
_dataDiff: (newData: DataType[], oldData: DataType[]) => [{startRow: index, endRow: index + 1}],
// ...
})
];
deckInstance.setProps({layers});
}

The function receives two arguments:

And is expected to return an array of "ranges", in the form of {startRow, endRow}:

This feature is experimental and intended for advanced use cases. Note that it only rewrites part of a buffer, not remove or insert, therefore the user of this prop is responsible of making sure that all the unchanged objects remain at the same indices between oldData and newData. This becomes trickier when dealing with data of dynamic lengths, for example PathLayer, PolygonLayer and GeoJsonLayer. Generally speaking, it is not recommended to use this feature when the count of vertices in the paths/polygons may change.

positionFormat ("XYZ"|"XY", optional)​

The format of positions. This prop is currently only effective in PathLayer, SolidPolygonLayer and PolygonLayer.

Default 'XYZ'.

colorFormat ("RGBA"|"RGB", optional)​

The format of colors. Setting it to 'RGB' will make the layer ignore the alpha channel of the colors returned by accessors, and instead assume all objects to be opaque. The layer's overall transparency controlled by opacity is still applied.

Default 'RGBA'.

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:

import {Deck, Color} from '@deck.gl/core';
import {ScatterplotLayer} from '@deck.gl/layers';

type DataType = {
position: [x: number, y: number];
gender: 'M'|'F';
};
const data: DataType[] = [...];
const deckInstance = new Deck({...});

function render({maleColor, femaleColor}: {
maleColor: Color;
femaleColor: Color;
}) {
const layers = [
new ScatterplotLayer<DataType>({
getPosition: (d: DataType) => d.position;
getFillColor: (d: DataType) => d.gender === 'M' ? maleColor : femaleColor
})
];

deckInstance.setProps({layers});
}

In this case, you need to explicitly inform deck.gl to re-evaluate getFillColor for all data items. You do so by defining updateTriggers:

function render({maleColor, femaleColor}: {
maleColor: Color;
femaleColor: Color;
}) {
const layers = [
new ScatterplotLayer<DataType>({
getPosition: (d: DataType) => d.position;
getFillColor: (d: DataType) => d.gender === 'M' ? maleColor : femaleColor,
// getFillColor should be re-evaluated when something in [maleColor, femaleColor] changes
updateTriggers: {
getFillColor: [maleColor, femaleColor]
}
})
];

deckInstance.setProps({layers});
}

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.getFillColor is a list of variables that affect the output of getFillColor. If either value in the array changes, all attributes that depend on getFillColor 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:

loaders (Loader[], optional)​

An array of loaders.gl loaders.

Out of the box, deck.gl supports loading JSON and image files (with ImageLoader), and specific layer implementation such as MVTLayer, TerrainLayer and ScenegraphLayer also include loaders for their targeted formats.

Support for addtional formats can be added by adding loaders to the loaders prop. For example, to load data from CSV files:

import {CSVLoader} from '@loaders.gl/csv';

const layer = new HexagonLayer({
data: './data.csv',
loaders: [CSVLoader]
...
});

loadOptions (object, optional)​

Layers use loaders.gl to load data and other resources. loadOptions is an object to customize the behavior of any loader used during fetching and parsing. The object may contain any of the top-level options, as well as loader-specific options targeting a particular format.

Layers may also include specialized loaders for their own use case, such as images, 3d-tiles, etc. See the documentation of each layer for additional load options that are available.

Find usage examples in the data loading guide.

fetch (Function, optional)​

Called to fetch and parse content from URLs.

The function receives the following arguments:

The function is expected to return a Promise that resolves to loaded data.

onDataLoad (Function, optional)​

Called when remote data is fully loaded. This callback applies when data is assigned a value that is either string (URL), Promise or an async iterable.

The function receives two arguments:

Render Properties​

parameters (object, optional)​

The parameters allows applications to specify values for GPU 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 GPU Parameters documentation on supported parameters and values.

getPolygonOffset (Function, optional)​

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:

transitions (object, optional)​

When a layer prop updates, if the transitions prop is configured, the prop value may animate smoothly from the old value to the new value. Animation parameters are defined per prop by using the prop names as keys:

new ScatterplotLayer({
// ...
transitions: {
getPosition: 600,
getFillColor: {
duration: 300,
easing: d3.easeCubicInOut,
enter: ([r, g, b]) => [r, g, b, 0] // fade in
},
radiusScale: {
type: 'spring',
stiffness: 0.01,
damping: 0.15
}
}
});

Each prop name is mapped to a number or an object that is the transition setting. As a shorthand, if a prop name maps to a number, then the number is assigned to the duration parameter with an interpolation type transition. If an object is supplied, it may contain the following fields:

KeyTypeDefaultDescription
typestring'interpolation'Type of the transition, currently supports 'interpolation' and 'spring'
enterFunctionvalue => valueCallback to get the value that the entering vertices are transitioning from. See attribute backfilling
onStartFunctionnullCallback when the transition is started
onEndFunctionnullCallback when the transition is done
onInterruptFunctionnullCallback when the transition is interrupted

The Animations and Transitions developer guide provides a deeper dive into the behavior and performance considerations of this feature.

Members​

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.

state (object)​

The state object allows a layer to store persistent information cross rendering cycles.

props (object)​

Properties of this layer.

isLoaded (boolean)​

true if all asynchronous assets are loaded.

parent (Layer | null)​

A Layer instance if this layer is rendered by a CompositeLayer

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​

clone​

const updatedLayer = layer.clone(overrideProps);

Create a copy of this layer, optionally change some prop values.

Arguments:

setState​

Used to update the layers state object. Calling this method will also cause the layer to rerender.

setModuleParameters​

Used to update the settings of shader modules.

raiseError​

Used to propagate errors thrown in layers to the deck.gl error handling system. This prevents rendering from being interrupted by exceptions in layers.

raiseError(error, message)

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)

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, changeFlags})

Parameters:

Returns:

Remarks:

updateState​

Called when a layer needs to be updated.

updateState({props, oldProps, context, changeFlags})

Parameters:

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:

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:

Returns:

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 to screen coordinate, using the current viewport settings and the current coordinate system.

Parameters:

Returns:

unproject​

Unprojects a screen coordinate using the current viewport settings.

Parameters:

Returns:

projectPosition​

Projects a map coordinate to world coordinate using the current viewport settings and the current coordinate system. Can be useful to calculate world space angle and distances.

Parameters:

Returns:

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:

Returns:

Note:

encodePickingColor​

Converts a "sub-feature index" number to a color. This color can later be decoded by the layer.decodePickingColor() method.

Parameters:

Returns:

To get a color that does not correspond to any sub-feature, use layer.nullPickingColor().

Notes:

nullPickingColor​

Returns:

Source​

modules/core/src/lib/layer.ts

TutorialsAPI index
English reference text adapted from the official deck.gl documentation, © vis.gl contributors, licensed under MIT.
Original page: https://deck.gl/docs/api-reference/core/layer · Chinese note: /deckgl/api/layer.html
Cite this page

Atlaslog (2026). Layer. https://www.jingweizhi.com/en/deckgl/api/layer.html (accessed 2026-11-03).