Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat: upgrade heatmap layer from mapbox to deckgl (#3372)

Igor Dykhta506e552b4980
diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
index 23416bc0b..46d351e4a 100644
--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx
+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
@@ -319,6 +319,13 @@ export default function LayerConfiguratorFactory(
}
_renderHeatmapLayerConfig({layer, visConfiguratorProps, layerChannelConfigProps}) {
+ const {visConfig} = layer.config;
+ const aggregationOptions = (layer.visConfigSettings.aggregation?.options || []).map(key => ({
+ id: key,
+ label: key.charAt(0) + key.slice(1).toLowerCase()
+ }));
+ const selectedAggregation = aggregationOptions.find(({id}) => id === visConfig.aggregation);
+
return (
<StyledLayerVisualConfigurator>
{/* Color */}
@@ -336,6 +343,11 @@ export default function LayerConfiguratorFactory(
label={false}
/>
</LayerConfigGroup>
+ {/* Intensity & Threshold */}
+ <LayerConfigGroup label={'layer.heatmap'}>
+ <VisConfigSlider {...layer.visConfigSettings.intensity} {...visConfiguratorProps} />
+ <VisConfigSlider {...layer.visConfigSettings.threshold} {...visConfiguratorProps} />
+ </LayerConfigGroup>
{/* Weight */}
<LayerConfigGroup label={'layer.weight'}>
<ChannelByValueSelector
@@ -343,6 +355,23 @@ export default function LayerConfiguratorFactory(
{...layerChannelConfigProps}
/>
</LayerConfigGroup>
+ {/* Aggregation */}
+ <LayerConfigGroup label={'layer.aggregation'}>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id={'layerVisConfigs.weightAggregation'} />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={selectedAggregation}
+ options={aggregationOptions}
+ displayOption="label"
+ getOptionValue="id"
+ multiSelect={false}
+ searchable={false}
+ onChange={value => visConfiguratorProps.onChange({aggregation: value})}
+ />
+ </SidePanelSection>
+ </LayerConfigGroup>
</StyledLayerVisualConfigurator>
);
}
diff --git a/src/deckgl-layers/src/layer-utils/shader-utils.ts b/src/deckgl-layers/src/layer-utils/shader-utils.ts
index 5032a11c3..961ffe14c 100644
--- a/src/deckgl-layers/src/layer-utils/shader-utils.ts
+++ b/src/deckgl-layers/src/layer-utils/shader-utils.ts
@@ -22,3 +22,18 @@ export function editShader(vs: string, type: string, originalText: string, testT
return vs.replace(originalText, testToReplace);
}
+
+export function insertBefore(
+ vs: string,
+ type: string,
+ insertBeforeText: string,
+ textToInsert: string
+) {
+ const at = vs.indexOf(insertBeforeText);
+ if (at < 0) {
+ Console.error(`Cannot edit ${type} layer shader`);
+ return vs;
+ }
+
+ return vs.slice(0, at) + textToInsert + vs.slice(at);
+}
diff --git a/src/layers/package.json b/src/layers/package.json
index ecacd7a8c..823da51b2 100644
--- a/src/layers/package.json
+++ b/src/layers/package.json
@@ -31,6 +31,7 @@
],
"dependencies": {
"@deck.gl-community/editable-layers": "9.2.8",
+ "@deck.gl/aggregation-layers": "^9.2.11",
"@deck.gl/core": "^9.2.11",
"@deck.gl/extensions": "^9.2.11",
"@deck.gl/geo-layers": "^9.2.11",
diff --git a/src/layers/src/heatmap-layer/deck-heatmap-layer.ts b/src/layers/src/heatmap-layer/deck-heatmap-layer.ts
new file mode 100644
index 000000000..0c8e31dbf
--- /dev/null
+++ b/src/layers/src/heatmap-layer/deck-heatmap-layer.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {HeatmapLayer as DeckGLHeatmapLayer} from '@deck.gl/aggregation-layers';
+import {editShader, insertBefore} from '@kepler.gl/deckgl-layers';
+
+/**
+ * Custom deck.gl HeatmapLayer subclass that patches GPU shaders
+ * to match the visual appearance of the previous Mapbox GL heatmap layer.
+ *
+ * These patches ensure that existing saved maps render identically after
+ * the migration from Mapbox heatmap to deck.gl heatmap.
+ *
+ * Two shader patches are applied:
+ *
+ * 1. Weights fragment shader (kernel):
+ * - Divides Gaussian kernel output by 8.5 and clips small values
+ * to remove visible hard edges at the radius boundary.
+ * - Changes the distance input from `2. * dist` to `dist` to
+ * correctly map the kernel falloff to the configured radius.
+ *
+ * 2. Max-weights fragment shader:
+ * - Forces the red channel to 1.0, because Mapbox assumes
+ * a max weight of 1.0 when sampling the color ramp.
+ */
+export default class KeplerHeatmapLayer extends DeckGLHeatmapLayer {
+ getShaders(shaders: any) {
+ const result = super.getShaders(shaders);
+
+ if (result.fs?.includes('gaussianKDE')) {
+ // Weights fragment shader: adjust kernel to match Mapbox heatmap layer
+ let fs = editShader(
+ result.fs,
+ 'fs',
+ 'return pow(2.71828, -u*u/0.05555)/(1.77245385*0.166666);',
+ `float value = pow(2.71828, -u*u/0.05555)/(1.77245385*0.166666) / 8.5;
+ return max(value - 0.00443, 0.0);`
+ );
+ fs = editShader(fs, 'fs', '2. * dist', 'dist');
+ result.fs = fs;
+ } else if (result.fs?.includes('outTexture.r / max(1.0, outTexture.a)')) {
+ // Max-weights fragment shader: force max value to 1.0
+ result.fs = insertBefore(
+ result.fs,
+ 'fs',
+ 'fragColor.g = outTexture.r / max(1.0, outTexture.a);',
+ 'fragColor.r = 1.0;\n '
+ );
+ }
+
+ return result;
+ }
+}
+
+KeplerHeatmapLayer.layerName = 'HeatmapLayer';
diff --git a/src/layers/src/heatmap-layer/heatmap-layer.ts b/src/layers/src/heatmap-layer/heatmap-layer.ts
index a6ad6dded..8de280792 100644
--- a/src/layers/src/heatmap-layer/heatmap-layer.ts
+++ b/src/layers/src/heatmap-layer/heatmap-layer.ts
@@ -1,28 +1,36 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {createSelector} from 'reselect';
+import KeplerHeatmapLayer from './deck-heatmap-layer';
import {CHANNEL_SCALES, ALL_FIELD_TYPES} from '@kepler.gl/constants';
-import MapboxGLLayer, {MapboxLayerGLConfig} from '../mapboxgl-layer';
+import Layer, {LayerBaseConfigPartial, LayerWeightConfig, VisualChannels} from '../base-layer';
import HeatmapLayerIcon from './heatmap-layer-icon';
-import {LayerBaseConfigPartial, LayerWeightConfig, VisualChannels} from '../base-layer';
import {
ColorRange,
VisConfigColorRange,
VisConfigNumber,
+ VisConfigSelection,
HexColor,
+ RGBColor,
Merge,
- LayerColumn
+ LayerColumn,
+ LayerBaseConfig,
+ MapState
} from '@kepler.gl/types';
import {hexToRgb, DataContainerInterface} from '@kepler.gl/utils';
-import {KeplerTable} from '@kepler.gl/table';
+import {notNullorUndefined} from '@kepler.gl/common-utils';
+import {Datasets, KeplerTable} from '@kepler.gl/table';
import {getGeoArrowPointLayerProps, FindDefaultLayerPropsReturnValue} from '../layer-utils';
+import {getFilterDataFunc} from '../aggregation-layer';
export type HeatmapLayerVisConfigSettings = {
opacity: VisConfigNumber;
colorRange: VisConfigColorRange;
radius: VisConfigNumber;
+ intensity: VisConfigNumber;
+ threshold: VisConfigNumber;
+ aggregation: VisConfigSelection;
};
export type HeatmapLayerColumnsConfig = {
@@ -38,11 +46,14 @@ export type HeatmapLayerVisConfig = {
opacity: number;
colorRange: ColorRange;
radius: number;
+ intensity: number;
+ threshold: number;
+ aggregation: string;
};
export type HeatmapLayerVisualChannelConfig = LayerWeightConfig;
export type HeatmapLayerConfig = Merge<
- MapboxLayerGLConfig,
+ LayerBaseConfig,
{columns: HeatmapLayerColumnsConfig; visConfig: HeatmapLayerVisConfig}
> &
HeatmapLayerVisualChannelConfig;
@@ -70,14 +81,47 @@ export const pointColResolver = ({lat, lng, geoarrow}: HeatmapLayerColumnsConfig
return `geoarrow-${geoarrow.fieldIdx}`;
};
+export const HEATMAP_AGGREGATION_TYPES = {
+ SUM: 'SUM',
+ MEAN: 'MEAN'
+} as const;
+
export const heatmapVisConfigs: {
opacity: 'opacity';
colorRange: 'colorRange';
radius: 'heatmapRadius';
+ intensity: VisConfigNumber;
+ threshold: VisConfigNumber;
+ aggregation: VisConfigSelection;
} = {
opacity: 'opacity',
colorRange: 'colorRange',
- radius: 'heatmapRadius'
+ radius: 'heatmapRadius',
+ intensity: {
+ type: 'number',
+ label: 'layerVisConfigs.intensity',
+ defaultValue: 1,
+ isRanged: false,
+ range: [0.001, 20],
+ step: 0.001,
+ property: 'intensity'
+ } as VisConfigNumber,
+ threshold: {
+ type: 'number',
+ label: 'layerVisConfigs.threshold',
+ defaultValue: 0.18,
+ isRanged: false,
+ range: [0.01, 1],
+ step: 0.001,
+ property: 'threshold'
+ } as VisConfigNumber,
+ aggregation: {
+ type: 'select',
+ defaultValue: HEATMAP_AGGREGATION_TYPES.SUM,
+ label: 'layerVisConfigs.weightAggregation',
+ options: Object.keys(HEATMAP_AGGREGATION_TYPES),
+ property: 'aggregation'
+ } as VisConfigSelection
};
export const pointRequiredColumns = ['lat', 'lng'];
@@ -99,32 +143,25 @@ const SUPPORTED_COLUMN_MODES = [
];
const DEFAULT_COLUMN_MODE = COLUMN_MODE_POINTS;
-/**
- *
- * @param colorRange
- * @return [
- * 0, "rgba(33,102,172,0)",
- * 0.2, "rgb(103,169,207)",
- * 0.4, "rgb(209,229,240)",
- * 0.6, "rgb(253,219,199)",
- * 0.8, "rgb(239,138,98)",
- * 1, "rgb(178,24,43)"
- * ]
- */
-const heatmapDensity = (colorRange: ColorRange): (string | number)[] => {
- const colors: HexColor[] = ['#000000', ...colorRange.colors];
-
- const colorDensity: (string | number)[] = [];
- colors.forEach((color, index) => {
- colorDensity.push(index / colors.length);
- colorDensity.push(`rgb(${hexToRgb(color).join(',')})`);
- });
-
- colorDensity[1] = 'rgba(0,0,0,0)';
- return colorDensity;
-};
+function toColorRamp(colors: HexColor[]): RGBColor[] {
+ if (!colors.length) return [];
+ return [colors[0], ...colors, colors[colors.length - 1]].map(hexToRgb);
+}
+
+function interpolateByZoom(
+ currentZoom: number,
+ minZoom: number,
+ valueAtMinZoom: number,
+ maxZoom: number,
+ valueAtMaxZoom: number
+): number {
+ const value =
+ valueAtMinZoom +
+ ((currentZoom - minZoom) / (maxZoom - minZoom)) * (valueAtMaxZoom - valueAtMinZoom);
+ return Math.min(Math.max(value, valueAtMinZoom), valueAtMaxZoom);
+}
-class HeatmapLayer extends MapboxGLLayer {
+class HeatmapLayer extends Layer {
declare visConfigSettings: HeatmapLayerVisConfigSettings;
declare config: HeatmapLayerConfig;
@@ -137,7 +174,6 @@ class HeatmapLayer extends MapboxGLLayer {
case COLUMN_MODE_GEOARROW:
return geoarrowPosAccessor(this.config.columns)(dataContainer);
default:
- // COLUMN_MODE_POINTS
return pointPosAccessor(this.config.columns)(dataContainer);
}
};
@@ -147,10 +183,29 @@ class HeatmapLayer extends MapboxGLLayer {
return 'heatmap';
}
+ get isAggregated(): true {
+ return true;
+ }
+
get supportedColumnModes() {
return SUPPORTED_COLUMN_MODES;
}
+ get columnPairs() {
+ return this.defaultPointColumnPairs;
+ }
+
+ get noneLayerDataAffectingProps() {
+ return [
+ ...super.noneLayerDataAffectingProps,
+ 'colorRange',
+ 'radius',
+ 'intensity',
+ 'threshold',
+ 'aggregation'
+ ];
+ }
+
hasAllColumns() {
const {columns, columnMode} = this.config;
if (columnMode === COLUMN_MODE_GEOARROW) {
@@ -177,8 +232,6 @@ class HeatmapLayer extends MapboxGLLayer {
scale: 'weightScale',
domain: 'weightDomain',
key: 'weight',
- // supportedFieldTypes can be determined by channelScaleType
- // or specified here
defaultMeasure: 'property.density',
supportedFieldTypes: [ALL_FIELD_TYPES.real, ALL_FIELD_TYPES.integer],
channelScaleType: CHANNEL_SCALES.size
@@ -190,6 +243,10 @@ class HeatmapLayer extends MapboxGLLayer {
return HeatmapLayerIcon;
}
+ getHoverData(): null {
+ return null;
+ }
+
getVisualChannelDescription(channel) {
return channel === 'color'
? {
@@ -203,9 +260,6 @@ class HeatmapLayer extends MapboxGLLayer {
}
getDefaultLayerConfig(props: LayerBaseConfigPartial): HeatmapLayerConfig {
- // mapbox heatmap layer color is always based on density
- // no need to set colorField, colorDomain and colorScale
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {colorField, colorDomain, colorScale, ...layerConfig} = {
...super.getDefaultLayerConfig(props),
@@ -222,84 +276,137 @@ class HeatmapLayer extends MapboxGLLayer {
updateLayerMeta(dataset: KeplerTable) {
const {dataContainer} = dataset;
-
const getPosition = this.getPositionAccessor(dataContainer);
const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
- columnsSelector = config => pointColResolver(config.columns, config.columnMode);
- visConfigSelector = config => config.visConfig;
- weightFieldSelector = config => (config.weightField ? config.weightField.name : null);
- weightDomainSelector = config => config.weightDomain;
-
- paintSelector = createSelector(
- this.visConfigSelector,
- this.weightFieldSelector,
- this.weightDomainSelector,
- (visConfig, weightField, weightDomain) => ({
- 'heatmap-weight': weightField
- ? ['interpolate', ['linear'], ['get', weightField], weightDomain[0], 0, weightDomain[1], 1]
- : 1,
- 'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 0, 1, MAX_ZOOM_LEVEL, 3],
- 'heatmap-color': [
- 'interpolate',
- ['linear'],
- ['heatmap-density'],
- ...heatmapDensity(visConfig.colorRange)
- ],
- 'heatmap-radius': [
- 'interpolate',
- ['linear'],
- ['zoom'],
- 0,
- 2,
- MAX_ZOOM_LEVEL,
- visConfig.radius // radius
- ],
- 'heatmap-opacity': visConfig.opacity
- })
- );
-
- computeHeatmapConfiguration = createSelector(
- this.sourceSelector,
- this.filterSelector,
- this.paintSelector,
- (source, filter, paint) => {
- return {
- type: 'heatmap',
- id: this.id,
- source,
- layout: {
- visibility: 'visible'
- },
- paint,
- ...(this.isValidFilter(filter) ? {filter} : {})
- };
+ calculateDataAttribute({filteredIndex}: KeplerTable, getPosition) {
+ const data: {index: number}[] = [];
+
+ for (let i = 0; i < filteredIndex.length; i++) {
+ const index = filteredIndex[i];
+ const pos = getPosition({index});
+
+ if (pos.every(Number.isFinite)) {
+ data.push({index});
+ }
}
- );
- formatLayerData(datasets, oldLayerData) {
- if (this.config.dataId === null) {
+ return data;
+ }
+
+ formatLayerData(datasets: Datasets, oldLayerData: unknown): Record<string, unknown> {
+ const {dataId} = this.config;
+ if (!notNullorUndefined(dataId)) {
return {};
}
- const {weightField} = this.config;
- const {dataContainer} = datasets[this.config.dataId];
+ const dataset = datasets[dataId];
+ const {weightField, weightScale, weightDomain} = this.config as HeatmapLayerConfig & {
+ weightScale: string;
+ weightDomain: number[];
+ };
+ const {gpuFilter, dataContainer} = dataset;
+
+ // Pass oldLayerData with the unfiltered base data so updateData's caching works correctly.
+ // formatLayerData returns GPU-filtered `data`, so oldLayerData.data would be the filtered
+ // subset. We stash the unfiltered array in `_unfiltered` to feed back to updateData.
+ const oldData = oldLayerData as any;
+ const baseOldLayerData = oldData?._unfiltered
+ ? {...oldData, data: oldData._unfiltered}
+ : oldLayerData;
+
+ const {data = []} = this.updateData(datasets, baseOldLayerData);
const getPosition = this.getPositionAccessor(dataContainer);
- const {data} = this.updateData(datasets, oldLayerData);
- // @ts-ignore
- const newConfig = this.computeHeatmapConfiguration(this.config, datasets);
- newConfig.id = this.id;
+ const hasFilter = Object.values(gpuFilter.filterRange).some((arr: any) =>
+ arr.some(v => v !== 0)
+ );
+
+ let filteredData = data;
+ if (hasFilter) {
+ const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)(
+ (d: {index: number}) => d.index,
+ (dc, d, fieldIndex) => dc.valueAt(d.index, fieldIndex)
+ );
+ const filterFunc = getFilterDataFunc(gpuFilter.filterRange, getFilterValue);
+ filteredData = data.filter(filterFunc);
+ }
+
+ let getWeight: ((d: {index: number}) => number) | number = 1;
+ if (weightField) {
+ const weightRange = [0, 1];
+ const scaleFunc = this.getVisChannelScale(weightScale, weightDomain, weightRange);
+ getWeight = (d: {index: number}) =>
+ this.getEncodedChannelValue(scaleFunc || (x => x), d as any, weightField, 0 as any);
+ }
return {
- columns: this.config.columns,
- config: newConfig,
- data,
- weightField,
+ _unfiltered: data,
+ data: filteredData,
+ getWeight,
getPosition
};
}
+
+ getDefaultDeckLayerProps(opts) {
+ const baseProp = super.getDefaultDeckLayerProps(opts);
+ return {
+ ...baseProp,
+ // gpu data filtering via DataFilterExtension is not supported in aggregation layers
+ extensions: [],
+ // heatmap is not pickable
+ pickable: false
+ };
+ }
+
+ renderLayer(opts: {
+ data: any;
+ gpuFilter: any;
+ objectHovered: any;
+ mapState: MapState;
+ layerCallbacks: any;
+ idx: number;
+ visible: boolean;
+ }): KeplerHeatmapLayer[] {
+ const {data, mapState} = opts;
+ const {_unfiltered, ...deckData} = data;
+
+ const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
+ const {visConfig} = this.config;
+ const colorRange = toColorRamp(visConfig.colorRange.colors);
+
+ const intensity = interpolateByZoom(
+ mapState.zoom,
+ 0,
+ visConfig.intensity,
+ MAX_ZOOM_LEVEL,
+ 3 * visConfig.intensity
+ );
+ const radiusPixels = interpolateByZoom(mapState.zoom, 0, 2, MAX_ZOOM_LEVEL, visConfig.radius);
+
+ const updateTriggers = {
+ getPosition: this.config.columns,
+ getWeight: {
+ weightField: this.config.weightField
+ }
+ };
+
+ return [
+ new KeplerHeatmapLayer({
+ ...defaultLayerProps,
+ ...deckData,
+ aggregation: (visConfig.aggregation || 'SUM') as 'SUM' | 'MEAN',
+ radiusPixels,
+ intensity,
+ threshold: visConfig.threshold,
+ updateTriggers,
+ colorRange,
+ weightsTextureSize: 512,
+ debounceTimeout: 0
+ })
+ ];
+ }
}
export default HeatmapLayer;
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index 621fdf3e8..1eabdaeac 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -105,7 +105,9 @@ export default {
'3d': '3D'
},
layerUpdateError:
- "S'ha produït un error durant l'actualització de la capa: {errorMessage}. Assegureu-vos que el format de les dades d’entrada sigui vàlid."
+ "S'ha produït un error durant l'actualització de la capa: {errorMessage}. Assegureu-vos que el format de les dades d’entrada sigui vàlid.",
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
angle: 'Angle',
@@ -130,6 +132,7 @@ export default {
targetColor: 'Color destí',
colorAggregation: 'Agregació de color',
heightAggregation: 'Agregació alçada',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: 'Rang de resolució',
sizeScale: 'Mida escala',
worldUnitSize: 'Mida de la unitat mundial',
@@ -148,6 +151,8 @@ export default {
enablePolygonHeight: 'Activa alçada del polígon',
showWireframe: 'Mostra Wireframe',
weightIntensity: 'Intensitat de pes',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'Escala de zoom',
heightRange: 'Rang alçada',
heightMultiplier: "Multiplicador d'alçada",
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index d55b13adf..a6d8cb24c 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -102,7 +102,9 @@ export default {
trip: 'trip',
s2: 'S2',
'3d': '3D'
- }
+ },
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
angle: '角度',
@@ -124,6 +126,7 @@ export default {
targetColor: '目标颜色',
colorAggregation: '颜色聚合',
heightAggregation: '高度聚合',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: '分辨率范围',
sizeScale: '大小比例',
worldUnitSize: '世界单位大小',
@@ -140,6 +143,8 @@ export default {
enablePolygonHeight: '启用多边形高度',
showWireframe: '显示线框',
weightIntensity: '加权强度',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: '缩放比例',
heightRange: '高度范围',
allowHover: '显示工具提示'
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 049539254..be2248ec7 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -126,7 +126,9 @@ export default {
},
layerUpdateError:
'An error occurred during layer update: {errorMessage}. Make sure the format of the input data is valid.',
- interaction: 'Interaction'
+ interaction: 'Interaction',
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
angle: 'Angle',
@@ -152,6 +154,7 @@ export default {
targetColor: 'Target Color',
colorAggregation: 'Color Aggregation',
heightAggregation: 'Height Aggregation',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: 'Resolution range',
sizeScale: 'Size Scale',
worldUnitSize: 'World Unit Size',
@@ -169,6 +172,8 @@ export default {
enablePolygonHeight: 'Enable Polygon Height',
showWireframe: 'Show Wireframe',
weightIntensity: 'Weight Intensity',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'Zoom Scale',
heightRange: 'Height Range',
heightMultiplier: 'Height Multiplier',
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index a2c96525b..ddcfafe87 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -105,7 +105,9 @@ export default {
'3d': '3D'
},
layerUpdateError:
- 'Se produjo un error durante la actualización de la capa: {errorMessage}. Asegúrese de que el formato de los datos de entrada sea válido.'
+ 'Se produjo un error durante la actualización de la capa: {errorMessage}. Asegúrese de que el formato de los datos de entrada sea válido.',
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
angle: 'Ángulo',
@@ -130,6 +132,7 @@ export default {
targetColor: 'Color destino',
colorAggregation: 'Agregación de color',
heightAggregation: 'Agregación de la altura',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: 'Rango de resolución',
sizeScale: 'Medida de escala',
worldUnitSize: 'Medida de la unidad mundial',
@@ -149,6 +152,8 @@ export default {
enablePolygonHeight: 'Activar la altura del polígono',
showWireframe: 'Muestra esquemàtico',
weightIntensity: 'Intensidad de peso',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'Escala de zoom',
heightRange: 'Rango de alturas',
heightMultiplier: 'Multiplicador de altura',
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index 94b52fe13..6cb9c7465 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -104,7 +104,9 @@ export default {
'3d': '3D'
},
layerUpdateError:
- 'Tason päivityksen aikana tapahtui virhe: {errorMessage}. Varmista, että syötetietojen muoto on kelvollinen.'
+ 'Tason päivityksen aikana tapahtui virhe: {errorMessage}. Varmista, että syötetietojen muoto on kelvollinen.',
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
strokeWidth: 'Viivan paksuus',
@@ -128,6 +130,7 @@ export default {
targetColor: 'Kohteen väri',
colorAggregation: 'Värien aggregointi',
heightAggregation: 'Korkeuden aggregointi',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: 'Resoluution rajat',
sizeScale: 'Koon skaala',
worldUnitSize: 'Yksikkö',
@@ -146,6 +149,8 @@ export default {
enablePolygonHeight: 'Salli polygonien korkeus',
showWireframe: 'Näytä rautalankamalli',
weightIntensity: 'Painotuksen intensiteetti',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'Zoomausskaala',
heightRange: 'Korkeuden rajat',
heightMultiplier: 'Korkeuskerroin',
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index 5f385df52..9b991a352 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -103,7 +103,9 @@ export default {
trip: 'trip',
s2: 'S2',
'3d': '3D'
- }
+ },
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
angle: '角度',
@@ -128,6 +130,7 @@ export default {
targetColor: 'Targetの色',
colorAggregation: '色の集計',
heightAggregation: '高さの集計',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: '解像度の範囲',
sizeScale: 'サイズのスケール',
worldUnitSize: 'World Unit Size',
@@ -145,6 +148,8 @@ export default {
enablePolygonHeight: 'ポリゴンの高さを有効にする',
showWireframe: 'ワイヤーフレームを表示',
weightIntensity: '重みづけの強さ',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'ズームのスケール',
heightRange: '高さの範囲',
heightMultiplier: '高さ乗数',
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index 8534c41fc..526570f8e 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -104,7 +104,9 @@ export default {
'3d': '3D'
},
layerUpdateError:
- 'Ocorreu um erro ao atualizar a camada: {errorMessage}. Certifique-se de que o formato dos dados de entrada seja válido.'
+ 'Ocorreu um erro ao atualizar a camada: {errorMessage}. Certifique-se de que o formato dos dados de entrada seja válido.',
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
strokeWidth: 'Largura do Traço',
@@ -128,6 +130,7 @@ export default {
targetColor: 'Cor de destino',
colorAggregation: 'Agregação da Cor',
heightAggregation: 'Agregação da Altura',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: 'Alcance da Resolução',
sizeScale: 'Escala de tamanho',
worldUnitSize: 'Tamanho unitário do mundo',
@@ -147,6 +150,8 @@ export default {
enablePolygonHeight: 'Habilitar Altura de Polígono',
showWireframe: 'Mostrar Wireframe',
weightIntensity: 'Intensidade da Espessura',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'Escala do Zoom',
heightRange: 'Alcance da Altura',
heightMultiplier: 'Multiplicador de altura',
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index 19cef46db..a48791da4 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -102,10 +102,11 @@ export default {
trip: 'пути',
s2: 'S2',
'3d': '3D'
- }
+ },
+ heatmap: 'Heatmap',
+ aggregation: 'Aggregation'
},
layerVisConfigs: {
- angle: 'Угол',
strokeWidth: 'Ширина штриха (в пикселях)',
strokeWidthRange: 'Диапазон ширины штриха',
radius: 'Радиус',
@@ -125,6 +126,7 @@ export default {
targetColor: 'Целевой цвет',
colorAggregation: 'Цветовая агрегация',
heightAggregation: 'Агрегация по высоте',
+ weightAggregation: 'Weight Aggregation',
resolutionRange: 'Диапазон разрешения',
sizeScale: 'Шкала размеров',
worldUnitSize: 'Мировые ед.изм.',
@@ -143,6 +145,8 @@ export default {
enablePolygonHeight: 'Включить высоту многоугольника',
showWireframe: 'Показать каркас',
weightIntensity: 'Вес Интенсивность',
+ intensity: 'Intensity',
+ threshold: 'Threshold',
zoomScale: 'Масштаб увеличения',
heightRange: 'Диапазон высоты',
heightMultiplier: 'Множитель высоты',
diff --git a/test/browser/layer-tests/heatmap-layer-specs.js b/test/browser/layer-tests/heatmap-layer-specs.js
index 56941c882..2ff78a5ba 100644
--- a/test/browser/layer-tests/heatmap-layer-specs.js
+++ b/test/browser/layer-tests/heatmap-layer-specs.js
@@ -12,7 +12,7 @@ import {
import {StateWFiles, testCsvDataId} from 'test/helpers/mock-state';
import {gpsPointBounds} from 'test/fixtures/test-csv-data';
-import {MAX_ZOOM_LEVEL, KeplerGlLayers} from '@kepler.gl/layers';
+import {KeplerGlLayers} from '@kepler.gl/layers';
import {copyTableAndUpdate} from '@kepler.gl/table';
const {HeatmapLayer} = KeplerGlLayers;
@@ -32,7 +32,6 @@ test('#HeatmapLayer -> contructor', t => {
label: 'test heatmap layer'
},
test: layer => {
- // test constructor
t.equal(layer.config.visConfig.radius, 20, 'Heatmap default radius should be 20');
t.ok(layer.config.dataId === 'taro', 'heatmaplayer dataId should be correct');
t.ok(layer.type === 'heatmap', 'type should be heatmap');
@@ -51,39 +50,6 @@ test('#HeatmapLayer -> contructor', t => {
test('#Heatmaplayer -> formatLayerData -> w/ GpuFilter', t => {
const filteredIndex = [0, 2, 4];
- const expectedConfig = {
- type: 'heatmap',
- id: 'heatmap-test-1',
- source: `${dataId}-points-1-2--1`,
- layout: {visibility: 'visible'},
- filter: ['all', ['>=', 'gpu:utc_timestamp', 39000], ['<=', 'gpu:utc_timestamp', 552000]],
- paint: {
- 'heatmap-weight': ['interpolate', ['linear'], ['get', 'id'], 1, 0, 345, 1],
- 'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 0, 1, 18, 3],
- 'heatmap-color': [
- 'interpolate',
- ['linear'],
- ['heatmap-density'],
- 0,
- 'rgba(0,0,0,0)',
- 0.14285714285714285,
- 'rgb(76,0,53)',
- 0.2857142857142857,
- 'rgb(136,0,48)',
- 0.42857142857142855,
- 'rgb(183,47,21)',
- 0.5714285714285714,
- 'rgb(214,97,10)',
- 0.7142857142857143,
- 'rgb(239,145,0)',
- 0.8571428571428571,
- 'rgb(255,195,0)'
- ],
- 'heatmap-radius': ['interpolate', ['linear'], ['zoom'], 0, 2, 18, 20],
- 'heatmap-opacity': 0.8
- }
- };
-
const TEST_CASES = [
{
name: 'Heatmap gps point.1',
@@ -92,7 +58,7 @@ test('#Heatmaplayer -> formatLayerData -> w/ GpuFilter', t => {
id: 'heatmap-test-1',
config: {
dataId,
- label: 'mapbox heatmap',
+ label: 'deck.gl heatmap',
isVisible: true,
columns,
weightField: {
@@ -107,65 +73,14 @@ test('#Heatmaplayer -> formatLayerData -> w/ GpuFilter', t => {
assert: result => {
const {layerData, layer} = result;
- const expectedLayerData = {
- columns: {
- lat: {value: 'lat', fieldIdx: 1},
- lng: {value: 'lng', fieldIdx: 2},
- geoarrow: {value: null, fieldIdx: -1}
- },
- config: expectedConfig,
- data: {
- type: 'FeatureCollection',
- features: [
- {
- type: 'Feature',
- properties: {
- index: 0,
- 'gpu:utc_timestamp': Number.MIN_SAFE_INTEGER,
- id: 1
- },
- geometry: {type: 'Point', coordinates: [-122.39096, 37.778564]}
- },
- {
- type: 'Feature',
- properties: {
- index: 4,
- 'gpu:utc_timestamp': 184000,
- id: 5
- },
- geometry: {type: 'Point', coordinates: [-122.136795, 37.456535]}
- }
- ]
- },
- weightField: null,
- getPosition: () => {}
- };
-
- t.deepEqual(
- Object.keys(layerData).sort(),
- Object.keys(expectedLayerData).sort(),
- 'lheatmap ayerData should have correct keys'
- );
- t.deepEqual(
- layerData.columns,
- expectedLayerData.columns,
- 'should format correct heatmap layerData.columns'
- );
-
- // test data
- t.deepEqual(
- layerData.data,
- expectedLayerData.data,
- 'should format correct heatmap layerData.data'
- );
+ t.ok(Array.isArray(layerData.data), 'layerData.data should be an array');
+ t.ok(typeof layerData.getPosition === 'function', 'should have getPosition accessor');
+ t.ok(typeof layerData.getWeight === 'function', 'should have getWeight accessor');
- // test columns,
- expectedLayerData.config.id = layer.id;
- // test config
- t.deepEqual(
- layerData.config,
- expectedLayerData.config,
- 'should format correct heatmap layerData.config'
+ // data items should have {index} shape for deck.gl aggregation
+ t.ok(
+ layerData.data.every(d => typeof d.index === 'number'),
+ 'data items should have numeric index'
);
// test layer.meta
@@ -185,32 +100,6 @@ test('#Heatmaplayer -> formatLayerData -> w/o GpuFilter', t => {
lng: 'gps_data.lng'
};
- const expectedConfig = {
- type: 'heatmap',
- id: 'heatmap-test-1',
- source: `${testCsvDataId}-points-1-2--1`,
- layout: {visibility: 'visible'},
- paint: {
- 'heatmap-weight': 1,
- 'heatmap-intensity': ['interpolate', ['linear'], ['zoom'], 0, 1, MAX_ZOOM_LEVEL, 3],
- 'heatmap-color': [
- 'interpolate',
- ['linear'],
- ['heatmap-density'],
- 0,
- 'rgba(0,0,0,0)',
- 0.25,
- 'rgb(1,1,1)',
- 0.5,
- 'rgb(2,2,2)',
- 0.75,
- 'rgb(3,3,3)'
- ],
- 'heatmap-radius': ['interpolate', ['linear'], ['zoom'], 0, 2, MAX_ZOOM_LEVEL, 100],
- 'heatmap-opacity': 0.2
- }
- };
-
const TEST_CASES = [
{
name: 'Heatmap gps point.1',
@@ -219,7 +108,7 @@ test('#Heatmaplayer -> formatLayerData -> w/o GpuFilter', t => {
id: 'heatmap-test-1',
config: {
dataId: testCsvDataId,
- label: 'mapbox heatmap',
+ label: 'deck.gl heatmap',
isVisible: true,
columns: gpsColumns,
visConfig: {
@@ -234,52 +123,23 @@ test('#Heatmaplayer -> formatLayerData -> w/o GpuFilter', t => {
datasets: StateWFiles.visState.datasets,
assert: result => {
const {layerData, layer} = result;
-
- const expectedLayerData = {
- columns: {
- lat: {value: 'gps_data.lat', fieldIdx: 1},
- lng: {value: 'gps_data.lng', fieldIdx: 2},
- geoarrow: {value: null, fieldIdx: -1}
- },
- config: expectedConfig,
- weightField: null,
- getPosition: () => {}
- };
const expectedLayerMeta = {bounds: gpsPointBounds};
- // test columns,
- t.deepEqual(
- layerData.columns,
- expectedLayerData.columns,
- 'should format correct heatmap layerData.columns'
- );
-
- // test data
+ t.ok(Array.isArray(layerData.data), 'layerData.data should be an array');
t.equal(
- layerData.data.features.length,
+ layerData.data.length,
testData.dataContainer.numRows(),
- 'should have same number of features'
+ 'should have same number of data points'
);
- t.deepEqual(
- layerData.data.features[0],
- {
- type: 'Feature',
- properties: {
- index: 0
- },
- geometry: {type: 'Point', coordinates: [31.2590542, 29.9900937]}
- },
- 'should format correct feature 0'
- );
- // test id
- expectedLayerData.config.id = layer.id;
+ t.ok(typeof layerData.getPosition === 'function', 'should have getPosition accessor');
+ t.equal(typeof layerData.getWeight, 'number', 'getWeight should be 1 when no weight field');
+ t.equal(layerData.getWeight, 1, 'getWeight should default to 1');
- // test config
- t.deepEqual(
- layerData.config,
- expectedLayerData.config,
- 'should format correct heatmap layerData.config'
+ // data items should have {index} shape
+ t.ok(
+ layerData.data.every(d => typeof d.index === 'number'),
+ 'data items should have numeric index'
);
// test layer.meta
diff --git a/yarn.lock b/yarn.lock
index bf4969c62..f462ccfc3 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5224,6 +5224,7 @@ __metadata:
resolution: "@kepler.gl/layers@workspace:src/layers"
dependencies:
"@deck.gl-community/editable-layers": "npm:9.2.8"
+ "@deck.gl/aggregation-layers": "npm:^9.2.11"
"@deck.gl/core": "npm:^9.2.11"
"@deck.gl/extensions": "npm:^9.2.11"
"@deck.gl/geo-layers": "npm:^9.2.11"