Skip to content

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

feat(layers): point count labels and min cluster size for aggregation layers (#3814)

Igor Dykhta2134184194c1
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 826e89980..152fd5b84 100644
--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx
+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx
@@ -4,6 +4,7 @@
/* eslint-disable complexity */
import {FormattedMessage} from '@kepler.gl/localization';
import React, {Component, useCallback, useRef, useState} from 'react';
+import {useIntl} from 'react-intl';
import styled from 'styled-components';
import ItemSelector from '../../common/item-selector/item-selector';
@@ -45,7 +46,8 @@ import {
Layer,
LayerBaseConfig,
VisualChannel,
- COLUMN_MODE_GEOJSON
+ COLUMN_MODE_GEOJSON,
+ createPointCountLabelField
} from '@kepler.gl/layers';
import {matchDatasetType, Datasets} from '@kepler.gl/table';
@@ -436,6 +438,18 @@ export default function LayerConfiguratorFactory(
RasterTileLayerConfigurator: ReturnType<typeof RasterTileLayerConfiguratorFactory>,
ScenegraphModelSelector: ReturnType<typeof ScenegraphModelSelectorFactory>
): React.ComponentType<LayerConfiguratorProps> {
+ const AggregationTextLabelPanel: React.FC<
+ Omit<React.ComponentProps<typeof TextLabelPanel>, 'fields'>
+ > = props => {
+ const intl = useIntl();
+ return (
+ <TextLabelPanel
+ {...props}
+ fields={[createPointCountLabelField(intl.formatMessage({id: 'property.pointCount'}))]}
+ />
+ );
+ };
+
class LayerConfigurator extends Component<LayerConfiguratorProps> {
_renderPointLayerConfig(props) {
return this._renderScatterplotLayerConfig(props, true);
@@ -598,8 +612,18 @@ export default function LayerConfiguratorFactory(
<VisConfigSlider {...layer.visConfigSettings.clusterRadius} {...visConfiguratorProps} />
<ConfigGroupCollapsibleContent>
<VisConfigSlider {...layer.visConfigSettings.radiusRange} {...visConfiguratorProps} />
+ <VisConfigSlider
+ {...layer.visConfigSettings.minClusterSize}
+ {...visConfiguratorProps}
+ />
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
+
+ <AggregationTextLabelPanel
+ id={layer.id}
+ updateLayerTextLabel={this.props.updateLayerTextLabel}
+ textLabel={layer.config.textLabel}
+ />
</StyledLayerVisualConfigurator>
);
}
@@ -767,6 +791,12 @@ export default function LayerConfiguratorFactory(
</ConfigGroupCollapsibleContent>
</LayerConfigGroup>
) : null}
+
+ <AggregationTextLabelPanel
+ id={layer.id}
+ updateLayerTextLabel={this.props.updateLayerTextLabel}
+ textLabel={layer.config.textLabel}
+ />
</StyledLayerVisualConfigurator>
);
}
diff --git a/src/components/src/side-panel/layer-panel/text-label-panel.tsx b/src/components/src/side-panel/layer-panel/text-label-panel.tsx
index 0b68c6ab6..bfecf5c5a 100644
--- a/src/components/src/side-panel/layer-panel/text-label-panel.tsx
+++ b/src/components/src/side-panel/layer-panel/text-label-panel.tsx
@@ -85,7 +85,7 @@ function TextLabelPanelFactory(
</SwitchWrapper>
</SidePanelSection>
{textLabel.map((tl, idx) => (
- <div key={tl.field ? tl.field.name : `null-${idx}`}>
+ <div key={`${tl.field ? tl.field.name : 'null'}-${idx}`}>
<PanelLabel>
<FormattedMessage id={'panel.text.labelWithId'} values={{labelId: idx + 1}} />
</PanelLabel>
diff --git a/src/components/src/side-panel/layer-panel/vis-config-slider.tsx b/src/components/src/side-panel/layer-panel/vis-config-slider.tsx
index 76698d5d7..8a2c71394 100644
--- a/src/components/src/side-panel/layer-panel/vis-config-slider.tsx
+++ b/src/components/src/side-panel/layer-panel/vis-config-slider.tsx
@@ -47,6 +47,7 @@ const InputWrapper = styled.div`
display: flex;
line-height: 12px;
margin-bottom: 12px;
+ width: 100%;
`;
const LabelRow = styled.div`
@@ -66,8 +67,7 @@ const CustomInputLabel = styled.label`
padding-right: 15px;
&:last-child {
- position: absolute;
- right: 0;
+ margin-left: auto;
padding: 0;
}
`;
diff --git a/src/constants/src/layers.ts b/src/constants/src/layers.ts
index dcf813abe..a31a5739b 100644
--- a/src/constants/src/layers.ts
+++ b/src/constants/src/layers.ts
@@ -222,6 +222,18 @@ export const LAYER_VIS_CONFIGS: LayerVisConfigSettings = {
property: 'radiusRange',
allowCustomValue: true
},
+ minClusterSize: {
+ type: 'number',
+ label: 'layerVisConfigs.minClusterSize',
+ description: 'layerVisConfigs.minClusterSizeDescription',
+ defaultValue: 1,
+ isRanged: false,
+ range: [1, 100],
+ step: 1,
+ group: PROPERTY_GROUPS.radius,
+ property: 'minClusterSize',
+ allowCustomValue: false
+ },
opacity: {
type: 'number',
defaultValue: DEFAULT_LAYER_OPACITY,
diff --git a/src/deckgl-layers/src/cluster-layer/cluster-layer.ts b/src/deckgl-layers/src/cluster-layer/cluster-layer.ts
index 8d4b17c48..0a5cfcfb8 100644
--- a/src/deckgl-layers/src/cluster-layer/cluster-layer.ts
+++ b/src/deckgl-layers/src/cluster-layer/cluster-layer.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {CompositeLayer, GetPickingInfoParams, PickingInfo} from '@deck.gl/core';
+import {CompositeLayer, GetPickingInfoParams, LayersList, PickingInfo} from '@deck.gl/core';
import {ScatterplotLayer} from '@deck.gl/layers';
import geoViewport from '@mapbox/geo-viewport';
@@ -20,6 +20,7 @@ import {RGBAColor} from '@kepler.gl/types';
const defaultRadius = LAYER_VIS_CONFIGS.clusterRadius.defaultValue;
const defaultRadiusRange = LAYER_VIS_CONFIGS.clusterRadiusRange.defaultValue;
+const defaultMinPointCount = LAYER_VIS_CONFIGS.minClusterSize.defaultValue;
const defaultGetColorValue = (points: Record<string, unknown>[]) => points.length;
const defaultGetRadiusValue = (cell: {filteredPoints?: unknown[]; points: unknown[]}) =>
@@ -37,12 +38,13 @@ function processGeoJSON(this: CPUAggregator, step, props, aggregation, {viewport
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getClusters(this: CPUAggregator, step, props, aggregation, {viewport}) {
const {geoJSON, clusterBuilder} = this.state;
- const {clusterRadius, zoom, width, height} = props;
+ const {clusterRadius, zoom, width, height, minPointCount} = props;
const {longitude, latitude} = viewport;
// zoom needs to be an integer for the different map utils. Also helps with cache key.
const bbox = geoViewport.bounds([longitude, latitude], zoom, [width, height]);
- const clusters = clusterBuilder?.clustersAtZoom({bbox, clusterRadius, geoJSON, zoom}) ?? [];
+ const clusters =
+ clusterBuilder?.clustersAtZoom({bbox, clusterRadius, geoJSON, zoom, minPointCount}) ?? [];
this.setState({
layerData: {data: clusters}
@@ -92,6 +94,9 @@ export const clusterAggregation: AggregationType = {
},
height: {
prop: 'height'
+ },
+ minPointCount: {
+ prop: 'minPointCount'
}
},
updater: getClusters
@@ -148,6 +153,7 @@ const clusterLayerDimensions: [DimensionType<RGBAColor>, DimensionType<number>]
const defaultProps = {
clusterRadius: defaultRadius,
+ minPointCount: defaultMinPointCount,
colorDomain: null,
colorRange: DEFAULT_COLOR_RANGE,
colorScaleType: SCALE_TYPES.quantize,
@@ -155,7 +161,11 @@ const defaultProps = {
radiusRange: defaultRadiusRange,
getPosition: {type: 'accessor', value: x => x.position},
getColorValue: {type: 'accessor', value: defaultGetColorValue},
- getRadiusValue: {type: 'accessor', value: defaultGetRadiusValue}
+ getRadiusValue: {type: 'accessor', value: defaultGetRadiusValue},
+ // Supplied by kepler's ClusterLayer when a point-count label is on.
+ // compare: false so a new callback identity does not recluster.
+ renderCountLabels: {type: 'function', value: null, compare: false, optional: true},
+ countLabelConfig: {type: 'object', value: null, compare: true, optional: true}
};
interface ClusterLayerState {
@@ -238,10 +248,11 @@ export default class ClusterLayer extends CompositeLayer {
const distanceScale = getDistanceScales(this.context.viewport);
const metersPerPixel = distanceScale.metersPerPixel[0];
+ const clusters = cpuAggregator.state.layerData.data;
// return props to the sublayer constructor
- return new ScatterplotLayer({
+ const scatterplot = new ScatterplotLayer({
id: `${id}-cluster`,
- data: cpuAggregator.state.layerData.data,
+ data: clusters,
radiusScale: metersPerPixel * radiusScale,
visible,
opacity,
@@ -254,7 +265,48 @@ export default class ClusterLayer extends CompositeLayer {
},
...accessors
});
+
+ const renderCountLabels = (
+ this.props as {
+ renderCountLabels?: (data: {position: [number, number]; count: number}[]) => LayersList;
+ }
+ ).renderCountLabels;
+ if (typeof renderCountLabels !== 'function') {
+ return scatterplot;
+ }
+ const labelData = clusterCountLabels(clusters);
+ const labels = renderCountLabels(labelData) ?? [];
+ return labels.length ? [scatterplot, ...labels] : scatterplot;
+ }
+}
+
+function clusterCountLabels(
+ clusters:
+ | {points?: unknown[]; filteredPoints?: unknown[] | null; position?: number[]}[]
+ | null
+ | undefined
+): {position: [number, number]; count: number}[] {
+ if (!clusters) {
+ return [];
+ }
+ const labels: {position: [number, number]; count: number}[] = [];
+ for (const cluster of clusters) {
+ const count = cluster.filteredPoints
+ ? cluster.filteredPoints.length
+ : cluster.points?.length ?? 0;
+ const position = cluster.position;
+ if (
+ count > 0 &&
+ Array.isArray(position) &&
+ Number.isFinite(position[0]) &&
+ Number.isFinite(position[1])
+ ) {
+ // Ground position only. Extruded columns are not a cluster feature, and
+ // GeoJSON labels likewise stay at the feature base.
+ labels.push({position: [position[0], position[1]], count});
+ }
}
+ return labels;
}
ClusterLayer.layerName = 'ClusterLayer';
diff --git a/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts b/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts
index 6d2847847..c86235c5e 100644
--- a/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts
+++ b/src/deckgl-layers/src/grid-layer/enhanced-cpu-grid-layer.ts
@@ -37,7 +37,11 @@ interface GridPickingObject {
export default class ScaleEnhancedGridLayer extends GridLayer<any> {
static defaultProps = {
...GridLayer.defaultProps,
- gpuAggregation: false
+ gpuAggregation: false,
+ // Supplied by kepler's AggregationLayer when a point-count label is on.
+ // compare: false so a new callback identity does not re-aggregate.
+ renderCountLabels: {type: 'function', value: null, compare: false, optional: true},
+ countLabelConfig: {type: 'object', value: null, compare: true, optional: true}
};
// HACK: deck.gl 9's _onAggregationUpdate is private and its onSetColorDomain
diff --git a/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts b/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts
index 9fcc67fc5..3a0d12697 100644
--- a/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts
+++ b/src/deckgl-layers/src/hexagon-layer/enhanced-hexagon-layer.ts
@@ -4,6 +4,7 @@
import {HexagonLayer, HexagonLayerPickingInfo} from '@deck.gl/aggregation-layers';
import {GetPickingInfoParams, Layer, PickingInfo, Viewport} from '@deck.gl/core';
import {enrichedAggregationUpdate, enrichedRenderLayers} from '../layer-utils/aggregation-utils';
+import {getHexbinCentroid} from '../layer-utils/aggregation-count-labels';
import {
makeGlobeCellLayerClass,
runBinOptionsWithMercatorViewport
@@ -15,12 +16,6 @@ const HexbinVertices = Array.from({length: 6}, (_, i) => {
return [Math.sin(angle), -Math.cos(angle)];
});
-function getHexbinCentroid(id: [number, number], radius: number): [number, number] {
- const DIST_X = 2 * Math.sin(THIRD_PI);
- const DIST_Y = 1.5;
- return [(id[0] + (id[1] & 1) / 2) * radius * DIST_X, id[1] * radius * DIST_Y];
-}
-
interface HexInternalState {
radiusCommon?: number;
hexOriginCommon?: [number, number];
@@ -48,7 +43,11 @@ interface HexPickingObject {
export default class ScaleEnhancedHexagonLayer extends HexagonLayer<any> {
static defaultProps = {
...HexagonLayer.defaultProps,
- gpuAggregation: false
+ gpuAggregation: false,
+ // Supplied by kepler's AggregationLayer when a point-count label is on.
+ // compare: false so a new callback identity does not re-aggregate.
+ renderCountLabels: {type: 'function', value: null, compare: false, optional: true},
+ countLabelConfig: {type: 'object', value: null, compare: true, optional: true}
};
// HACK: deck.gl 9's _onAggregationUpdate is private and its onSetColorDomain
diff --git a/src/deckgl-layers/src/layer-utils/aggregation-count-labels.spec.ts b/src/deckgl-layers/src/layer-utils/aggregation-count-labels.spec.ts
new file mode 100644
index 000000000..50e46fa0b
--- /dev/null
+++ b/src/deckgl-layers/src/layer-utils/aggregation-count-labels.spec.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {
+ aggregationBinIsDrawn,
+ collectGridCountLabels,
+ collectHexagonCountLabels,
+ getHexbinCentroid
+} from './aggregation-count-labels';
+
+describe('aggregationBinIsDrawn', () => {
+ test('hides bins outside the cell shader cutoff', () => {
+ const colors = {domain: [0, 10] as [number, number], cutoff: [2, 8] as [number, number]};
+ const elevations = {domain: [0, 10] as [number, number], cutoff: null};
+ expect(aggregationBinIsDrawn(1, 5, colors, elevations, [0, 10], [0, 10])).toBe(false);
+ expect(aggregationBinIsDrawn(2, 5, colors, elevations, [0, 10], [0, 10])).toBe(true);
+ expect(aggregationBinIsDrawn(Number.NaN, 5, colors, elevations, [0, 10], [0, 10])).toBe(false);
+ });
+});
+
+describe('collectHexagonCountLabels', () => {
+ test('places the count at the hex centroid and drops filtered-out points', () => {
+ const radius = 10;
+ const origin: [number, number] = [5, 7];
+ const [cx, cy] = getHexbinCentroid([1, 0], radius);
+ const layer = fakeLayer({
+ radiusCommon: radius,
+ hexOriginCommon: origin,
+ unprojectFlat: xy => [xy[0] / 100, xy[1] / 100],
+ bins: [
+ {id: [1, 0], count: 2, pointIndices: [0, 1], color: 4, elevation: 4},
+ {id: [2, 0], count: 1, pointIndices: [2], color: 0, elevation: 4}
+ ],
+ colorCutoff: [2, 10],
+ filterData: point => point.index !== 0
+ });
+
+ expect(collectHexagonCountLabels(layer)).toEqual([
+ {count: 1, position: [(cx + origin[0]) / 100, (cy + origin[1]) / 100]}
+ ]);
+ });
+});
+
+describe('collectGridCountLabels', () => {
+ test('places the count at the cell center', () => {
+ const layer = fakeLayer({
+ cellOriginCommon: [100, 200],
+ cellSizeCommon: [10, 20],
+ unprojectFlat: xy => xy,
+ bins: [{id: [0, 1], count: 3, pointIndices: [0], color: 3, elevation: 3}]
+ });
+
+ expect(collectGridCountLabels(layer)).toEqual([{count: 3, position: [105, 230]}]);
+ });
+});
+
+function fakeLayer({
+ bins,
+ unprojectFlat,
+ radiusCommon,
+ hexOriginCommon,
+ cellOriginCommon,
+ cellSizeCommon,
+ colorCutoff = null,
+ filterData
+}: {
+ bins: {id: number[]; count: number; pointIndices: number[]; color: number; elevation: number}[];
+ unprojectFlat: (xy: number[]) => number[];
+ radiusCommon?: number;
+ hexOriginCommon?: [number, number];
+ cellOriginCommon?: [number, number];
+ cellSizeCommon?: [number, number];
+ colorCutoff?: [number, number] | null;
+ filterData?: (point: any) => boolean;
+}) {
+ const data = bins.flatMap(bin => bin.pointIndices.map(index => ({index})));
+ return {
+ state: {
+ radiusCommon,
+ hexOriginCommon,
+ cellOriginCommon,
+ cellSizeCommon,
+ aggregatorViewport: {unprojectFlat},
+ aggregator: {
+ binCount: bins.length,
+ getBin: (index: number) => bins[index] ?? null,
+ getResultDomain: () => [0, 10] as [number, number]
+ },
+ colors: {
+ attribute: {value: bins.map(bin => bin.color)},
+ domain: [0, 10] as [number, number],
+ cutoff: colorCutoff
+ },
+ elevations: {
+ attribute: {value: bins.map(bin => bin.elevation)},
+ domain: [0, 10] as [number, number],
+ cutoff: null
+ }
+ },
+ props: {
+ data,
+ colorDomain: null,
+ elevationDomain: null,
+ _filterData: filterData
+ }
+ };
+}
diff --git a/src/deckgl-layers/src/layer-utils/aggregation-count-labels.ts b/src/deckgl-layers/src/layer-utils/aggregation-count-labels.ts
new file mode 100644
index 000000000..e0c5e4795
--- /dev/null
+++ b/src/deckgl-layers/src/layer-utils/aggregation-count-labels.ts
@@ -0,0 +1,215 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+const THIRD_PI = Math.PI / 3;
+
+export type AggregationCountLabel = {
+ position: [number, number];
+ count: number;
+};
+
+type ScaledChannel = {
+ attribute?: {value?: ArrayLike<number>};
+ domain?: [number, number] | null;
+ cutoff?: [number, number] | null;
+};
+
+type CountLabelLayer = {
+ state: {
+ aggregator?: {
+ binCount: number;
+ getBin: (index: number) => {
+ id: number[];
+ count: number;
+ pointIndices?: number[];
+ } | null;
+ getResultDomain: (channel: number) => [number, number];
+ };
+ colors?: ScaledChannel;
+ elevations?: ScaledChannel;
+ radiusCommon?: number;
+ hexOriginCommon?: [number, number];
+ cellOriginCommon?: [number, number];
+ cellSizeCommon?: [number, number];
+ aggregatorViewport?: {unprojectFlat?: (xy: number[]) => number[]};
+ };
+ props: {
+ data?: unknown;
+ colorDomain?: [number, number] | null;
+ elevationDomain?: [number, number] | null;
+ _filterData?: (point: any) => boolean;
+ renderCountLabels?: (data: AggregationCountLabel[]) => unknown;
+ };
+};
+
+/**
+ * Hide a label when the cell shader would discard the bin (percentile cutoff
+ * or a non-finite aggregated value). Thresholds match hexagon-cell-layer and
+ * grid-cell-layer: values outside colorDomain.zw / elevationDomain.zw.
+ */
+export function aggregationBinIsDrawn(
+ colorValue: number,
+ elevationValue: number,
+ colors: ScaledChannel,
+ elevations: ScaledChannel,
+ colorDomain: [number, number],
+ elevationDomain: [number, number]
+): boolean {
+ return (
+ valueInChannel(colorValue, colors, colorDomain) &&
+ valueInChannel(elevationValue, elevations, elevationDomain)
+ );
+}
+
+function valueInChannel(
+ value: number,
+ scaled: ScaledChannel,
+ fallbackDomain: [number, number]
+): boolean {
+ if (!Number.isFinite(value)) {
+ return false;
+ }
+ const domain = scaled.domain || fallbackDomain;
+ if (!domain || !Number.isFinite(domain[0]) || !Number.isFinite(domain[1])) {
+ return true;
+ }
+ const cutoff = scaled.cutoff || [-Infinity, Infinity];
+ const low = Math.max(domain[0] - 1, cutoff[0]);
+ const high = Math.min(domain[1] + 1, cutoff[1]);
+ return value >= low && value <= high;
+}
+
+/** Same centroid deck.gl's hexagon cell shader uses, before the common-space origin. */
+export function getHexbinCentroid(id: [number, number], radius: number): [number, number] {
+ const distX = 2 * Math.sin(THIRD_PI);
+ const distY = 1.5;
+ return [(id[0] + (id[1] & 1) / 2) * radius * distX, id[1] * radius * distY];
+}
+
+export function collectHexagonCountLabels(layer: CountLabelLayer): AggregationCountLabel[] {
+ return collectBinCountLabels(layer, (col, row) => {
+ const {radiusCommon, hexOriginCommon, aggregatorViewport} = layer.state;
+ if (!radiusCommon || !aggregatorViewport?.unprojectFlat) {
+ return null;
+ }
+ const centroid = getHexbinCentroid([col, row], radiusCommon);
+ const lngLat = aggregatorViewport.unprojectFlat([
+ centroid[0] + (hexOriginCommon?.[0] ?? 0),
+ centroid[1] + (hexOriginCommon?.[1] ?? 0)
+ ]);
+ return finiteLngLat(lngLat);
+ });
+}
+
+export function collectGridCountLabels(layer: CountLabelLayer): AggregationCountLabel[] {
+ return collectBinCountLabels(layer, (col, row) => {
+ const {cellOriginCommon, cellSizeCommon, aggregatorViewport} = layer.state;
+ if (!cellOriginCommon || !cellSizeCommon || !aggregatorViewport?.unprojectFlat) {
+ return null;
+ }
+ const lngLat = aggregatorViewport.unprojectFlat([
+ (col + 0.5) * cellSizeCommon[0] + cellOriginCommon[0],
+ (row + 0.5) * cellSizeCommon[1] + cellOriginCommon[1]
+ ]);
+ return finiteLngLat(lngLat);
+ });
+}
+
+export function appendAggregationCountLabels(
+ layer: CountLabelLayer,
+ layerName: string,
+ rendered: unknown
+): unknown {
+ const renderCountLabels = layer.props?.renderCountLabels;
+ if (typeof renderCountLabels !== 'function') {
+ return rendered;
+ }
+ const labels =
+ layerName === 'GridLayer'
+ ? collectGridCountLabels(layer)
+ : layerName === 'HexagonLayer'
+ ? collectHexagonCountLabels(layer)
+ : [];
+ const textLayers = renderCountLabels(labels) || [];
+ if (!Array.isArray(textLayers) || textLayers.length === 0) {
+ return rendered;
+ }
+ const cells = rendered == null ? [] : Array.isArray(rendered) ? rendered : [rendered];
+ return [...cells, ...textLayers];
+}
+
+function collectBinCountLabels(
+ layer: CountLabelLayer,
+ getPosition: (col: number, row: number) => [number, number] | null
+): AggregationCountLabel[] {
+ const {aggregator, colors, elevations} = layer.state;
+ if (!aggregator || aggregator.binCount <= 0 || !colors?.attribute || !elevations?.attribute) {
+ return [];
+ }
+ const colorValues = colors.attribute.value;
+ const elevationValues = elevations.attribute.value;
+ if (!colorValues || !elevationValues) {
+ return [];
+ }
+ const colorDomain = colors.domain || layer.props.colorDomain || aggregator.getResultDomain(0);
+ const elevationDomain =
+ elevations.domain || layer.props.elevationDomain || aggregator.getResultDomain(1);
+
+ const labels: AggregationCountLabel[] = [];
+ for (let i = 0; i < aggregator.binCount; i++) {
+ const bin = aggregator.getBin(i);
+ if (!bin || bin.id.length < 2) {
+ continue;
+ }
+ if (
+ !aggregationBinIsDrawn(
+ colorValues[i],
+ elevationValues[i],
+ colors,
+ elevations,
+ colorDomain,
+ elevationDomain
+ )
+ ) {
+ continue;
+ }
+ const count = filteredBinCount(layer, bin);
+ if (count <= 0) {
+ continue;
+ }
+ const position = getPosition(bin.id[0], bin.id[1]);
+ if (!position) {
+ continue;
+ }
+ labels.push({position, count});
+ }
+ return labels;
+}
+
+function filteredBinCount(
+ layer: CountLabelLayer,
+ bin: {count: number; pointIndices?: number[]}
+): number {
+ const filterData = layer.props._filterData;
+ const data = layer.props.data;
+ if (typeof filterData !== 'function' || !bin.pointIndices || !Array.isArray(data)) {
+ return bin.count;
+ }
+ let count = 0;
+ for (const index of bin.pointIndices) {
+ const point = data[index];
+ if (point != null && filterData(point)) {
+ count += 1;
+ }
+ }
+ return count;
+}
+
+function finiteLngLat(lngLat: number[] | null | undefined): [number, number] | null {
+ if (!lngLat || !Number.isFinite(lngLat[0]) || !Number.isFinite(lngLat[1])) {
+ return null;
+ }
+ // Labels stay on the ground. Extruded GeoJSON does the same: the label is
+ // placed at the base, and the text layer draws on top of the extrusion.
+ return [lngLat[0], lngLat[1]];
+}
diff --git a/src/deckgl-layers/src/layer-utils/aggregation-utils.ts b/src/deckgl-layers/src/layer-utils/aggregation-utils.ts
index ce60b1792..cf18e32d5 100644
--- a/src/deckgl-layers/src/layer-utils/aggregation-utils.ts
+++ b/src/deckgl-layers/src/layer-utils/aggregation-utils.ts
@@ -3,6 +3,7 @@
import type {AggregatedBin, ColorMap} from '@kepler.gl/types';
import {naturalBreaks} from '@kepler.gl/utils';
+import {appendAggregationCountLabels} from './aggregation-count-labels';
type JenksColorMapCache = {
source: Float32Array;
@@ -218,5 +219,6 @@ export function enrichedRenderLayers(layer: any, ParentClass: any): any {
classifyBinsByCustomBreaks(colors, aggregator.binCount, cache.colorMap, rawColorBinValues);
}
}
- return (ParentClass.prototype as any).renderLayers.call(layer);
+ const rendered = (ParentClass.prototype as any).renderLayers.call(layer);
+ return appendAggregationCountLabels(layer, ParentClass.layerName, rendered);
}
diff --git a/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts b/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts
new file mode 100644
index 000000000..771be01b0
--- /dev/null
+++ b/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import ClusterBuilder, {getGeoJSON} from './cluster-utils';
+
+const WORLD_BBOX: [number, number, number, number] = [-180, -85, 180, 85];
+
+// Three points at the same spot cluster together, the fourth stays on its own.
+const data = [
+ {index: 0, position: [-122.1, 37.4]},
+ {index: 1, position: [-122.1001, 37.4001]},
+ {index: 2, position: [-122.1002, 37.4]},
+ {index: 3, position: [20, -10]}
+];
+
+function clusterSizes(minPointCount?: number) {
+ const geoJSON = getGeoJSON(data, d => d.position, null);
+ const clusters = new ClusterBuilder().clustersAtZoom({
+ bbox: WORLD_BBOX,
+ clusterRadius: 40,
+ geoJSON,
+ zoom: 4,
+ minPointCount
+ });
+ return {
+ sizes: clusters.map(c => c.points.length).sort(),
+ indices: clusters.map(c => c.index)
+ };
+}
+
+describe('ClusterBuilder.clustersAtZoom', () => {
+ test('keeps every cluster without a cutoff', () => {
+ expect(clusterSizes()).toEqual({sizes: [1, 3], indices: [0, 1]});
+ });
+
+ test('drops clusters below the cutoff and keeps indices contiguous', () => {
+ expect(clusterSizes(2)).toEqual({sizes: [3], indices: [0]});
+ });
+
+ test('a cutoff above every cluster leaves nothing to draw', () => {
+ expect(clusterSizes(4)).toEqual({sizes: [], indices: []});
+ });
+});
diff --git a/src/deckgl-layers/src/layer-utils/cluster-utils.ts b/src/deckgl-layers/src/layer-utils/cluster-utils.ts
index dec5d7b35..b47d79ab3 100644
--- a/src/deckgl-layers/src/layer-utils/cluster-utils.ts
+++ b/src/deckgl-layers/src/layer-utils/cluster-utils.ts
@@ -55,25 +55,38 @@ export default class ClusterBuilder {
bbox,
clusterRadius,
geoJSON,
- zoom
+ zoom,
+ minPointCount = 1
}: {
bbox: BBox;
clusterRadius: number;
geoJSON;
zoom: number;
+ /** Drop clusters holding fewer points than this, so sparse noise is not drawn. */
+ minPointCount?: number;
}): {
points: any;
position: Position;
index: number;
}[] {
const clusterer = this.clusterer({clusterRadius, geoJSON});
+ const cutoff = Number.isFinite(minPointCount) ? minPointCount : 1;
- // map clusters to formatted bins to be passed to deck.gl bin-sorter
- const clusters = clusterer.getClusters(bbox, zoom).map((c, i) => ({
- points: c.properties.points,
- position: c.geometry.coordinates,
- index: i
- }));
+ // map clusters to formatted bins to be passed to deck.gl bin-sorter.
+ // `index` must stay the position in the returned array: the bin sorter and
+ // picking both look cells up by it.
+ const clusters: {points: any; position: Position; index: number}[] = [];
+ for (const c of clusterer.getClusters(bbox, zoom)) {
+ const points = c.properties.points;
+ if (points.length < cutoff) {
+ continue;
+ }
+ clusters.push({
+ points,
+ position: c.geometry.coordinates,
+ index: clusters.length
+ });
+ }
return clusters;
}
diff --git a/src/layers/src/aggregation-count-label.spec.ts b/src/layers/src/aggregation-count-label.spec.ts
new file mode 100644
index 000000000..9a4264e4e
--- /dev/null
+++ b/src/layers/src/aggregation-count-label.spec.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {
+ formatPointCount,
+ isPointCountLabel,
+ createPointCountLabelField
+} from './aggregation-count-label';
+
+describe('formatPointCount', () => {
+ test('keeps small counts and abbreviates thousands and millions', () => {
+ expect(formatPointCount(0)).toBe('0');
+ expect(formatPointCount(1)).toBe('1');
+ expect(formatPointCount(999)).toBe('999');
+ expect(formatPointCount(1000)).toBe('1k');
+ expect(formatPointCount(1499)).toBe('1.5k');
+ expect(formatPointCount(9940)).toBe('9.9k');
+ expect(formatPointCount(9950)).toBe('10k');
+ expect(formatPointCount(15000)).toBe('15k');
+ expect(formatPointCount(1_500_000)).toBe('1.5m');
+ expect(formatPointCount(12_000_000)).toBe('12m');
+ expect(formatPointCount(Number.NaN)).toBe('');
+ });
+});
+
+describe('isPointCountLabel', () => {
+ test('matches only the synthetic point-count field', () => {
+ expect(isPointCountLabel({field: createPointCountLabelField()})).toBe(true);
+ expect(isPointCountLabel({field: {name: 'pointCount', fieldIdx: 3}})).toBe(false);
+ expect(isPointCountLabel({field: null})).toBe(false);
+ });
+});
diff --git a/src/layers/src/aggregation-count-label.ts b/src/layers/src/aggregation-count-label.ts
new file mode 100644
index 000000000..f3b9911fe
--- /dev/null
+++ b/src/layers/src/aggregation-count-label.ts
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {DEFAULT_TEXT_LABEL} from '@kepler.gl/constants';
+import {Field, LayerTextLabel} from '@kepler.gl/types';
+
+/** Synthetic text-label field. Not a dataset column: it reads the bin point count. */
+export const POINT_COUNT_FIELD_NAME = 'pointCount';
+
+export const AGGREGATION_COUNT_LAYER_TYPES = new Set(['cluster', 'hexagon', 'grid']);
+
+export const POINT_COUNT_CHARACTER_SET = [
+ '0',
+ '1',
+ '2',
+ '3',
+ '4',
+ '5',
+ '6',
+ '7',
+ '8',
+ '9',
+ '.',
+ 'k',
+ 'm'
+];
+
+export type AggregationCountLabel = {
+ position: [number, number];
+ count: number;
+};
+
+export function createPointCountLabelField(displayName = 'Point Count'): Field {
+ return {
+ name: POINT_COUNT_FIELD_NAME,
+ displayName,
+ type: 'integer',
+ fieldIdx: -1,
+ format: '',
+ analyzerType: 'INT',
+ // Bin counts are read from aggregated cells, not from a dataset row.
+ valueAccessor: () => null
+ };
+}
+
+export function isPointCountLabel(
+ textLabel: {field?: {name?: string; fieldIdx?: number} | null} | null | undefined
+): boolean {
+ const field = textLabel?.field;
+ return Boolean(field && field.name === POINT_COUNT_FIELD_NAME && field.fieldIdx === -1);
+}
+
+/**
+ * New cluster, hexbin, and grid layers label each shape with its point count.
+ * Collision is on so a dense grid hides overlapping numbers. Anchor and
+ * alignment center the number on the shape.
+ */
+export function defaultAggregationCountLabel(): LayerTextLabel {
+ return {
+ ...DEFAULT_TEXT_LABEL,
+ field: createPointCountLabelField(),
+ anchor: 'middle',
+ alignment: 'center',
+ collisionEnabled: true,
+ // White glyphs need a halo to stay readable on both light and dark cells.
+ outlineWidth: 1,
+ outlineColor: [0, 0, 0, 255]
+ };
+}
+
+/** Abbreviate like a cluster bubble: 999, 1.2k, 15k, 1.2m. */
+export function formatPointCount(count: number): string {
+ if (!Number.isFinite(count)) {
+ return '';
+ }
+ const n = Math.round(count);
+ const abs = Math.abs(n);
+ if (abs < 1000) {
+ return String(n);
+ }
+ if (abs < 10000) {
+ return `${trimTrailingZero(Math.round(n / 100) / 10)}k`;
+ }
+ if (abs < 1000000) {
+ return `${Math.round(n / 1000)}k`;
+ }
+ if (abs < 10000000) {
+ return `${trimTrailingZero(Math.round(n / 100000) / 10)}m`;
+ }
+ return `${Math.round(n / 1000000)}m`;
+}
+
+function trimTrailingZero(value: number): string {
+ const text = String(value);
+ return text.endsWith('.0') ? text.slice(0, -2) : text;
+}
diff --git a/src/layers/src/aggregation-layer.ts b/src/layers/src/aggregation-layer.ts
index e2b158896..121101fa3 100644
--- a/src/layers/src/aggregation-layer.ts
+++ b/src/layers/src/aggregation-layer.ts
@@ -22,6 +22,13 @@ import {
GEOARROW_METADATA_KEY,
SCALE_TYPES
} from '@kepler.gl/constants';
+import {
+ AggregationCountLabel,
+ defaultAggregationCountLabel,
+ formatPointCount,
+ isPointCountLabel,
+ POINT_COUNT_CHARACTER_SET
+} from './aggregation-count-label';
import {ColorRange, Field, LayerColumn, Merge} from '@kepler.gl/types';
import {KeplerTable, Datasets} from '@kepler.gl/table';
import {DATA_TYPES} from 'type-analyzer';
@@ -241,10 +248,67 @@ export default class AggregationLayer extends Layer {
getDefaultLayerConfig(props: LayerBaseConfigPartial) {
return {
...super.getDefaultLayerConfig(props),
- columnMode: props?.columnMode ?? DEFAULT_COLUMN_MODE
+ columnMode: props?.columnMode ?? DEFAULT_COLUMN_MODE,
+ // Show the point count on each shape. Collision is on so dense grids
+ // hide overlapping numbers. Clearing the label field turns this off.
+ textLabel: [defaultAggregationCountLabel()]
};
}
+ getCountLabelProps(opts) {
+ const hasCountLabel = (this.config.textLabel || []).some(textLabel =>
+ isPointCountLabel(textLabel)
+ );
+ if (!hasCountLabel) {
+ return {};
+ }
+ return {
+ renderCountLabels: (data: AggregationCountLabel[]) => this.renderCountLabelLayers(data, opts),
+ // Compared by the deck layer so font, color, and collision changes redraw.
+ countLabelConfig: this.config.textLabel
+ };
+ }
+
+ /**
+ * Draw point-count labels the way extruded GeoJSON does: at the shape's base,
+ * not at the top of the column. renderTextLabelLayer disables the depth test
+ * in flat mode, so the glyphs paint on top of extruded hexes and grids.
+ */
+ renderCountLabelLayers(labelData: AggregationCountLabel[], opts) {
+ const textLabels = (this.config.textLabel || []).map(textLabel =>
+ isPointCountLabel(textLabel)
+ ? {
+ getText: (d: AggregationCountLabel) => formatPointCount(d.count),
+ characterSet: POINT_COUNT_CHARACTER_SET
+ }
+ : {getText: null, characterSet: []}
+ );
+ if (!textLabels.some(textLabel => textLabel.getText)) {
+ return [];
+ }
+
+ const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
+ return this.renderTextLabelLayer(
+ {
+ getPosition: (d: AggregationCountLabel) => d.position,
+ getPixelOffset: (textLabel: {offset?: [number, number]}) => textLabel.offset || [0, 0],
+ updateTriggers: {},
+ sharedProps: {
+ visible: defaultLayerProps.visible,
+ pickable: false,
+ wrapLongitude: false
+ }
+ },
+ {
+ ...opts,
+ data: {
+ data: labelData,
+ textLabels
+ }
+ }
+ );
+ }
+
getDataUpdateTriggers(dataset: KeplerTable): any {
const triggers = super.getDataUpdateTriggers(dataset);
const {columnMode} = this.config;
diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.ts
index aba2293f5..ef0959ab7 100644
--- a/src/layers/src/base-layer.ts
+++ b/src/layers/src/base-layer.ts
@@ -17,6 +17,7 @@ import React from 'react';
import * as arrow from 'apache-arrow';
import DefaultLayerIcon from './default-layer-icon';
import {diffUpdateTriggers} from './layer-update';
+import {textLabelDeckLayerId} from './layer-text-label';
import {getSatisfiedColumnMode, FindDefaultLayerPropsReturnValue} from './layer-utils';
import {
@@ -1733,9 +1734,11 @@ class Layer implements KeplerLayer {
// previous TextLayer. Matching would keep a stale collisionPriorities
// attribute after the extension is removed, and skip initializeState
// (no collision_texture) when it is added.
- const labelId = `${this.id}-label-${textLabel[i].field?.name}${
- collisionEnabled ? '-collision' : ''
- }`;
+ // Two labels of the same field (Point Count is the only aggregation
+ // choice) must not share an id. CollisionTextLayer appends
+ // -background and -characters, and deck.gl drops the pair when those
+ // sublayer ids collide.
+ const labelId = textLabelDeckLayerId(this.id, textLabel, i, collisionEnabled);
// Glyphs inherit these from the TextLayer. The background sublayer's
// `_subLayerProps.background.parameters` replaces that object, so the
// same depth settings have to be repeated there. Otherwise the box
diff --git a/src/layers/src/cluster-layer/cluster-layer.ts b/src/layers/src/cluster-layer/cluster-layer.ts
index 728a985e7..2abd00c46 100644
--- a/src/layers/src/cluster-layer/cluster-layer.ts
+++ b/src/layers/src/cluster-layer/cluster-layer.ts
@@ -22,6 +22,7 @@ export type ClusterLayerVisConfigSettings = {
clusterRadius: VisConfigNumber;
colorRange: VisConfigColorRange;
radiusRange: VisConfigRange;
+ minClusterSize: VisConfigNumber;
colorAggregation: VisConfigSelection;
};
@@ -30,6 +31,7 @@ export type ClusterLayerVisConfig = {
clusterRadius: number;
colorRange: ColorRange;
radiusRange: [number, number];
+ minClusterSize: number;
colorAggregation: AggregationTypes;
};
@@ -40,12 +42,14 @@ export const clusterVisConfigs: {
clusterRadius: 'clusterRadius';
colorRange: 'colorRange';
radiusRange: 'clusterRadiusRange';
+ minClusterSize: 'minClusterSize';
colorAggregation: 'colorAggregation';
} = {
opacity: 'opacity',
clusterRadius: 'clusterRadius',
colorRange: 'colorRange',
radiusRange: 'clusterRadiusRange',
+ minClusterSize: 'minClusterSize',
colorAggregation: 'colorAggregation'
};
@@ -103,6 +107,7 @@ export default class ClusterLayer extends AggregationLayer {
};
const defaultLayerProps = this.getDefaultDeckLayerProps(opts);
+ const countLabelProps = this.getCountLabelProps(opts);
const {_filterData: filterData, ...clusterData} = data;
const hoveredObject = this.hasHoveredObject(objectHovered);
@@ -117,6 +122,7 @@ export default class ClusterLayer extends AggregationLayer {
radiusScale: 1,
radiusRange: visConfig.radiusRange,
clusterRadius: visConfig.clusterRadius,
+ minPointCount: visConfig.minClusterSize,
// color
colorRange: this.getColorRange(visConfig.colorRange),
@@ -132,7 +138,8 @@ export default class ClusterLayer extends AggregationLayer {
updateTriggers,
// call back from layer after calculate clusters
- onSetColorDomain: layerCallbacks.onSetLayerDomain
+ onSetColorDomain: layerCallbacks.onSetLayerDomain,
+ ...countLabelProps
}),
// hover layer
...(hoveredObject
diff --git a/src/layers/src/grid-layer/grid-layer.ts b/src/layers/src/grid-layer/grid-layer.ts
index e8e915268..cce1f8d35 100644
--- a/src/layers/src/grid-layer/grid-layer.ts
+++ b/src/layers/src/grid-layer/grid-layer.ts
@@ -101,6 +101,7 @@ export default class GridLayer extends AggregationLayer {
const {data, objectHovered, mapState} = opts;
const defaultAggregationLayerProps = this.getDefaultAggregationLayerProp(opts);
+ const countLabelProps = this.getCountLabelProps(opts);
const zoomFactor = this.getZoomFactor(mapState);
const {visConfig} = this.config;
const cellSize = visConfig.worldUnitSize * 1000;
@@ -115,7 +116,8 @@ export default class GridLayer extends AggregationLayer {
...defaultAggregationLayerProps,
...data,
wrapLongitude: false,
- cellSize
+ cellSize,
+ ...countLabelProps
}),
// render an outline of each cell if not extruded
diff --git a/src/layers/src/hexagon-layer/hexagon-layer.ts b/src/layers/src/hexagon-layer/hexagon-layer.ts
index ff7f7a74f..aad0f4cba 100644
--- a/src/layers/src/hexagon-layer/hexagon-layer.ts
+++ b/src/layers/src/hexagon-layer/hexagon-layer.ts
@@ -109,6 +109,7 @@ export default class HexagonLayer extends AggregationLayer {
const {data, objectHovered, mapState} = opts;
const defaultAggregationLayerProps = this.getDefaultAggregationLayerProp(opts);
+ const countLabelProps = this.getCountLabelProps(opts);
const zoomFactor = this.getZoomFactor(mapState);
const {visConfig} = this.config;
const radius = visConfig.worldUnitSize * 1000;
@@ -123,7 +124,8 @@ export default class HexagonLayer extends AggregationLayer {
...defaultAggregationLayerProps,
...data,
wrapLongitude: false,
- radius
+ radius,
+ ...countLabelProps
}),
// render an outline of each hexagon if not extruded
diff --git a/src/layers/src/index.ts b/src/layers/src/index.ts
index b990f4ba6..9e6428e02 100644
--- a/src/layers/src/index.ts
+++ b/src/layers/src/index.ts
@@ -204,6 +204,12 @@ export const EditorLayerUtils = {
};
export {getFilterDataFunc} from './aggregation-layer';
+export {
+ AGGREGATION_COUNT_LAYER_TYPES,
+ createPointCountLabelField,
+ isPointCountLabel,
+ POINT_COUNT_FIELD_NAME
+} from './aggregation-count-label';
export * from './layer-update';
export * from './layer-utils';
diff --git a/src/layers/src/layer-text-label.spec.ts b/src/layers/src/layer-text-label.spec.ts
index 5cd1eec65..7ecc2c469 100644
--- a/src/layers/src/layer-text-label.spec.ts
+++ b/src/layers/src/layer-text-label.spec.ts
@@ -4,7 +4,34 @@
import KeplerTable from '@kepler.gl/table';
import {ALL_FIELD_TYPES, DEFAULT_TEXT_LABEL} from '@kepler.gl/constants';
import PointLayer from './point-layer/point-layer';
-import {formatTextLabelData, getSingleTextLabelValue} from './layer-text-label';
+import {
+ formatTextLabelData,
+ getSingleTextLabelValue,
+ textLabelDeckLayerId
+} from './layer-text-label';
+
+describe('textLabelDeckLayerId', () => {
+ const pointCount = {field: {name: 'pointCount'}};
+
+ test('keeps the single-label id used by collision sublayers', () => {
+ expect(textLabelDeckLayerId('jaca149', [pointCount], 0, true)).toBe(
+ 'jaca149-label-pointCount-collision'
+ );
+ expect(textLabelDeckLayerId('jaca149', [pointCount], 0, false)).toBe(
+ 'jaca149-label-pointCount'
+ );
+ });
+
+ test('suffixes the index when the same field is labeled twice', () => {
+ const labels = [pointCount, pointCount];
+ expect(textLabelDeckLayerId('jaca149', labels, 0, true)).toBe(
+ 'jaca149-label-pointCount-0-collision'
+ );
+ expect(textLabelDeckLayerId('jaca149', labels, 1, true)).toBe(
+ 'jaca149-label-pointCount-1-collision'
+ );
+ });
+});
async function makeTable() {
const table = new KeplerTable({color: [255, 0, 0]} as any);
diff --git a/src/layers/src/layer-text-label.ts b/src/layers/src/layer-text-label.ts
index 73c4bb316..5990ab6cd 100644
--- a/src/layers/src/layer-text-label.ts
+++ b/src/layers/src/layer-text-label.ts
@@ -215,3 +215,21 @@ export const getArrowTextVector = (
return new arrow.Vector(input);
};
+
+/**
+ * deck.gl layer id for one text label. A repeated field name gets the label
+ * index so CollisionTextLayer's -background and -characters sublayers stay unique.
+ */
+export function textLabelDeckLayerId(
+ layerId: string,
+ textLabel: {field?: {name?: string} | null}[],
+ index: number,
+ collisionEnabled: boolean
+): string {
+ const fieldName = textLabel[index]?.field?.name;
+ const duplicateFieldName =
+ Boolean(fieldName) && textLabel.filter(label => label.field?.name === fieldName).length > 1;
+ return `${layerId}-label-${fieldName}${duplicateFieldName ? `-${index}` : ''}${
+ collisionEnabled ? '-collision' : ''
+ }`;
+}
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index 18024d7bf..fd695c3e6 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -151,6 +151,9 @@ export default {
radiusRange: 'Rang de radi',
clusterRadius: 'Radi Cluster en Pixels',
radiusRangePixels: 'Rang del radi en pixels',
+ minClusterSize: 'Mínim de punts per clúster',
+ minClusterSizeDescription:
+ 'Amaga els clústers amb menys punts que aquest valor, p. ex. 2 elimina els d’un sol punt',
billboard: 'Mode de cartellera',
billboardDescription: 'Orientar la geometria cap a la càmera',
fadeTrail: 'Rastre de desvaniment',
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index 2d3dc34c9..762e2e7cd 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -149,6 +149,8 @@ export default {
radiusRange: '半径范围',
clusterRadius: '聚类半径',
radiusRangePixels: '半径范围[像素]',
+ minClusterSize: '每个聚类的最少点数',
+ minClusterSizeDescription: '隐藏点数少于该值的聚类,例如设为 2 可移除单点聚类',
billboard: '公告板模式',
billboardDescription: '将几何体朝向相机',
fadeTrail: '渐隐轨迹',
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index cdfe7500e..cca7702b1 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -180,6 +180,9 @@ export default {
radiusRange: 'Radius Range',
clusterRadius: 'Cluster Radius in Pixels',
radiusRangePixels: 'Radius Range in pixels',
+ minClusterSize: 'Min Points per Cluster',
+ minClusterSizeDescription:
+ 'Hide clusters that contain fewer points than this, e.g. 2 removes single-point clusters',
billboard: 'Billboard',
billboardDescription: 'Orient geometry towards the camera',
fadeTrail: 'Fade trail',
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index bf5026be7..073b9d543 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -151,6 +151,9 @@ export default {
radiusRange: 'Rango de radio',
clusterRadius: 'Radio del cluster en píxeles',
radiusRangePixels: 'Rango del radio en píxeles',
+ minClusterSize: 'Mínimo de puntos por clúster',
+ minClusterSizeDescription:
+ 'Oculta los clústeres con menos puntos que este valor, p. ej. 2 elimina los de un solo punto',
billboard: 'Modo cartelera',
billboardDescription: 'Oriente la geometría hacia la cámara',
fadeTrail: 'Sendero de desvanecimiento',
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index f7e3fb7e8..85cdd43b3 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -150,6 +150,9 @@ export default {
radiusRange: 'Säteen rajat',
clusterRadius: 'Klusterien säde pikseleinä',
radiusRangePixels: 'Säteen rajat pikseleinä',
+ minClusterSize: 'Pisteiden vähimmäismäärä klusterissa',
+ minClusterSizeDescription:
+ 'Piilota klusterit, joissa on tätä vähemmän pisteitä, esim. 2 poistaa yhden pisteen klusterit',
billboard: 'Billboard -tila',
billboardDescription: 'Suuntaa geometria kameraa kohti',
fadeTrail: 'Häipyvä polku',
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index c85880f5f..49a1c10d1 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -151,6 +151,9 @@ export default {
radiusRange: '半径の範囲',
clusterRadius: 'クラスターの範囲[ピクセル]',
radiusRangePixels: '半径の範囲[ピクセル]',
+ minClusterSize: 'クラスターあたりの最小ポイント数',
+ minClusterSizeDescription:
+ 'これより少ないポイント数のクラスターを非表示にします。例: 2 で単一ポイントのクラスターを除外',
billboard: 'ビルボードモード',
billboardDescription: 'ジオメトリをカメラに向けます',
fadeTrail: 'フェージングパス',
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index e203a47a8..025883225 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -151,6 +151,9 @@ export default {
radiusRange: 'Alcance do Raio',
clusterRadius: 'Raio do Agrupamento em pixels',
radiusRangePixels: 'Alcance do Raio em pixels',
+ minClusterSize: 'Mínimo de pontos por cluster',
+ minClusterSizeDescription:
+ 'Oculta clusters com menos pontos do que este valor, por exemplo, 2 remove os de um só ponto',
billboard: 'Câmera de rosto',
billboardDescription: 'Oriente a geometria em direção à câmera',
fadeTrail: 'Fade trilha',
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index 9cbcc4ddc..3b1a06b75 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -152,6 +152,9 @@ export default {
radiusRange: 'Диапазон радиуса',
clusterRadius: 'Радиус кластера в пикселях',
radiusRangePixels: 'Диапазон радиуса в пикселях',
+ minClusterSize: 'Мин. точек в кластере',
+ minClusterSizeDescription:
+ 'Скрывать кластеры, в которых меньше точек, например 2 убирает кластеры из одной точки',
billboard: 'Режим билборда',
billboardDescription: 'Ориентировать геометрию на камеру',
fadeTrail: 'Затухающий след',
diff --git a/src/reducers/src/vis-state-merger-text-label.spec.ts b/src/reducers/src/vis-state-merger-text-label.spec.ts
new file mode 100644
index 000000000..849f7ea56
--- /dev/null
+++ b/src/reducers/src/vis-state-merger-text-label.spec.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {DEFAULT_TEXT_LABEL} from '@kepler.gl/constants';
+import {KeplerGlLayers} from '@kepler.gl/layers';
+
+import {fallbackTextLabelForLoadedLayer, validateSavedTextLabel} from './vis-state-merger';
+
+const aggregationTextLabelDefaults = () =>
+ new KeplerGlLayers.HexagonLayer({id: 'hexagon'}).config.textLabel;
+
+describe('validateSavedTextLabel point count', () => {
+ test('restores the synthetic field and keeps collision disabled', () => {
+ const defaults = aggregationTextLabelDefaults();
+ const saved = [
+ {
+ ...defaults[0],
+ field: {name: 'pointCount', type: 'integer'},
+ collisionEnabled: false,
+ anchor: 'start'
+ }
+ ];
+
+ const [label] = validateSavedTextLabel([], defaults, saved, {
+ layerType: 'hexagon',
+ throwOnError: true
+ });
+
+ expect(label.field).toMatchObject({name: 'pointCount', fieldIdx: -1});
+ expect(label.collisionEnabled).toBe(false);
+ expect(label.anchor).toBe('start');
+ });
+
+ test('binds a real pointCount column on non-aggregation layers', () => {
+ const datasetField = {
+ name: 'pointCount',
+ type: 'integer',
+ fieldIdx: 4,
+ valueAccessor: () => 1
+ };
+ const saved = [{...DEFAULT_TEXT_LABEL, field: {name: 'pointCount', type: 'integer'}}];
+
+ const [label] = validateSavedTextLabel([datasetField], [DEFAULT_TEXT_LABEL], saved, {
+ layerType: 'point',
+ throwOnError: true
+ });
+
+ expect(label.field).toBe(datasetField);
+ });
+
+ test('omitted textLabel on a hexagon stays unlabeled', () => {
+ const labels = fallbackTextLabelForLoadedLayer('hexagon', aggregationTextLabelDefaults());
+
+ expect(labels).toHaveLength(1);
+ expect(labels[0].field).toBeNull();
+ expect(labels[0].collisionEnabled).toBe(false);
+ });
+
+ test('omitted textLabel on a point layer keeps the layer default', () => {
+ const defaults = [DEFAULT_TEXT_LABEL];
+
+ expect(fallbackTextLabelForLoadedLayer('point', defaults)).toBe(defaults);
+ });
+});
diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.ts
index c9d35e056..c2888962d 100644
--- a/src/reducers/src/vis-state-merger.ts
+++ b/src/reducers/src/vis-state-merger.ts
@@ -16,11 +16,18 @@ import {
isPlainObject
} from '@kepler.gl/utils';
-import {Layer, migrateLegacyScenegraphVisConfig} from '@kepler.gl/layers';
+import {
+ AGGREGATION_COUNT_LAYER_TYPES,
+ Layer,
+ createPointCountLabelField,
+ migrateLegacyScenegraphVisConfig,
+ POINT_COUNT_FIELD_NAME
+} from '@kepler.gl/layers';
import {createEffect} from '@kepler.gl/effects';
import {notNullorUndefined} from '@kepler.gl/common-utils';
import {
AGGREGATION_TYPES,
+ DEFAULT_TEXT_LABEL,
LAYER_BLENDINGS,
OVERLAY_BLENDINGS,
isAnnotationKind,
@@ -186,7 +193,8 @@ function insertItemBasedOnPreservedOrder(
export function createLayerFromConfig(state: VisState, layerConfig: any): Layer | null {
// check if the layer config is parsed
- const parsedLayerConfig = isSavedLayerConfigV1(layerConfig)
+ const savedLayerConfig = isSavedLayerConfigV1(layerConfig);
+ const parsedLayerConfig = savedLayerConfig
? parseLayerConfig(state.schema, layerConfig)
: layerConfig;
@@ -198,7 +206,7 @@ export function createLayerFromConfig(state: VisState, layerConfig: any): Layer
state.datasets,
state.layerClasses,
[parsedLayerConfig],
- {allowEmptyColumn: true}
+ {allowEmptyColumn: true, keepUnlabeledAggregationTextLabel: savedLayerConfig}
);
if (failed?.length || !validated.length) {
@@ -292,7 +300,8 @@ export function mergeLayers<S extends VisState>(
const {validated: mergedLayer, failed} = validateLayersByDatasets(
state.datasets,
state.layerClasses,
- toMerge
+ toMerge,
+ {keepUnlabeledAggregationTextLabel: true}
);
unmerged.push(...failed);
// put new layers in front of current layers
@@ -1072,19 +1081,29 @@ export function validateColumn(
*/
export function validateSavedTextLabel(
fields,
- [layerTextLabel],
+ layerTextLabels: any[],
savedTextLabel,
- options: {throwOnError?: boolean} = {}
-) {
+ options: {throwOnError?: boolean; layerType?: string | null} = {}
+): any[] {
+ const layerTextLabel = layerTextLabels[0];
const savedTextLabels = Array.isArray(savedTextLabel) ? savedTextLabel : [savedTextLabel];
+ const countLabelLayer = Boolean(
+ options.layerType && AGGREGATION_COUNT_LAYER_TYPES.has(options.layerType)
+ );
// validate field
return savedTextLabels.map(textLabel => {
- const field = textLabel.field
- ? fields.find(fd =>
- Object.keys(textLabel.field).every(key => textLabel.field[key] === fd[key])
- )
- : null;
+ let field = null;
+ if (textLabel.field) {
+ // Cluster, hexbin, and grid persist a synthetic point-count field that
+ // is not one of the dataset columns.
+ field =
+ countLabelLayer && textLabel.field.name === POINT_COUNT_FIELD_NAME
+ ? createPointCountLabelField()
+ : fields.find(fd =>
+ Object.keys(textLabel.field).every(key => textLabel.field[key] === fd[key])
+ );
+ }
if (field === undefined && options.throwOnError) {
throw new Error(`Layer has invalid text label field: ${JSON.stringify(textLabel.field)}`);
@@ -1093,13 +1112,30 @@ export function validateSavedTextLabel(
return Object.keys(layerTextLabel).reduce(
(accu, key) => ({
...accu,
- [key]: key === 'field' ? field : textLabel[key] || layerTextLabel[key]
+ // Keep explicit false / 0. `||` would replace a saved collisionEnabled
+ // of false with the aggregation default of true.
+ [key]: key === 'field' ? field : textLabel[key] ?? layerTextLabel[key]
}),
{}
);
});
}
+/**
+ * Maps saved before count labels omit `textLabel`. Those cluster, hexbin, and
+ * grid layers stay unlabeled. New layers still get the point-count default
+ * from `getDefaultLayerConfig`.
+ */
+export function fallbackTextLabelForLoadedLayer(
+ layerType: string | null | undefined,
+ newLayerTextLabel: any[]
+): any[] {
+ if (layerType && AGGREGATION_COUNT_LAYER_TYPES.has(layerType)) {
+ return [{...DEFAULT_TEXT_LABEL}];
+ }
+ return newLayerTextLabel;
+}
+
/**
* Saved visual channel field/scale may live in any of:
* - `config[key]` after schema parse (VisualChannelSchemaV1 folds channels into config)
@@ -1163,6 +1199,9 @@ export function validateSavedVisualChannels(
type ValidateLayerOption = {
allowEmptyColumn?: boolean;
throwOnError?: boolean;
+ // Saved maps that omit textLabel predate count labels and stay unlabeled.
+ // A new layer config omits it too, and should keep the layer default.
+ keepUnlabeledAggregationTextLabel?: boolean;
};
export function validateLayersByDatasets(
@@ -1296,12 +1335,12 @@ export function validateLayerWithData(
const textLabel =
savedLayer.config.textLabel && newLayer.config.textLabel
- ? validateSavedTextLabel(
- fields,
- newLayer.config.textLabel,
- savedLayer.config.textLabel,
- options
- )
+ ? validateSavedTextLabel(fields, newLayer.config.textLabel, savedLayer.config.textLabel, {
+ ...options,
+ layerType: savedLayer.type
+ })
+ : options.keepUnlabeledAggregationTextLabel
+ ? fallbackTextLabelForLoadedLayer(savedLayer.type, newLayer.config.textLabel)
: newLayer.config.textLabel;
// copy visConfig over to emptyLayer to make sure it has all the props
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index e298870b5..b244a5bd2 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -134,7 +134,13 @@ import {
getDatasetRefreshIntervalMs,
getRemoteSourceFormat
} from '@kepler.gl/constants';
-import {LAYER_ID_LENGTH, Layer, LayerClasses} from '@kepler.gl/layers';
+import {
+ AGGREGATION_COUNT_LAYER_TYPES,
+ isPointCountLabel,
+ LAYER_ID_LENGTH,
+ Layer,
+ LayerClasses
+} from '@kepler.gl/layers';
import {
apply_,
compose_,
@@ -561,7 +567,8 @@ export function applyLayerConfigUpdater(
const {oldLayerId, newLayerConfig, layerIndex} = action;
// Saved configs have a visualChannels sibling; parsed/editor JSON folds those
// fields into config. Re-parsing the latter drops colorField and resets the scale.
- const newParsedLayer = isSavedLayerConfigV1(newLayerConfig)
+ const savedLayerConfig = isSavedLayerConfigV1(newLayerConfig);
+ const newParsedLayer = savedLayerConfig
? parseLayerConfig(state.schema, newLayerConfig)
: newLayerConfig;
const oldLayer = state.layers.find(l => l.id === oldLayerId);
@@ -577,7 +584,9 @@ export function applyLayerConfigUpdater(
return state;
}
// Make sure the layer is valid and convert it to Layer
- const newLayer = validateLayerWithData(dataset, newParsedLayer, state.layerClasses);
+ const newLayer = validateLayerWithData(dataset, newParsedLayer, state.layerClasses, {
+ keepUnlabeledAggregationTextLabel: savedLayerConfig
+ });
if (!newLayer) {
return state;
}
@@ -854,12 +863,21 @@ function addOrRemoveTextLabels(newFields, textLabel, defaultTextLabel = DEFAULT_
const currentFields = textLabel.map(tl => tl.field && tl.field.name).filter(d => d);
- const addFields = newFields.filter(f => !currentFields.includes(f.name));
+ const addFields = newFields.filter(
+ (field, index) =>
+ field &&
+ field.name &&
+ !currentFields.includes(field.name) &&
+ newFields.findIndex(other => other && other.name === field.name) === index
+ );
const deleteFields = currentFields.filter(f => !newFields.find(fd => fd.name === f));
// delete
newTextLabel = newTextLabel.filter(tl => tl.field && !deleteFields.includes(tl.field.name));
- newTextLabel = !newTextLabel.length ? [defaultTextLabel] : newTextLabel;
+ // Aggregation defaults already name Point Count. Using that object as the
+ // empty placeholder, then appending the field just picked, inserts the same
+ // label twice. deck.gl then rejects the duplicate collision layer ids.
+ newTextLabel = !newTextLabel.length ? [{...defaultTextLabel, field: null}] : newTextLabel;
// add
newTextLabel = [
@@ -918,6 +936,9 @@ export function layerTextLabelChangeUpdater(
...textLabel,
{
...defaultTextLabel,
+ // The slot is empty until a field is picked. Aggregation defaults already
+ // carry Point Count, and copying that field would add a second label.
+ field: null,
collisionEnabled: Boolean(textLabel[0]?.collisionEnabled)
}
];
@@ -1134,6 +1155,14 @@ export function layerTypeChangeUpdater(
state.datasets,
defaultLayerProps
);
+ if (!AGGREGATION_COUNT_LAYER_TYPES.has(newType)) {
+ const textLabel = newLayer.config.textLabel.filter(label => !isPointCountLabel(label));
+ if (textLabel.length !== newLayer.config.textLabel.length) {
+ newLayer.updateLayerConfig({
+ textLabel: textLabel.length ? textLabel : [{...DEFAULT_TEXT_LABEL}]
+ });
+ }
+ }
newLayer.updateLayerDomain(state.datasets);
}
diff --git a/src/types/layers.d.ts b/src/types/layers.d.ts
index 0267e048f..52cbdfda5 100644
--- a/src/types/layers.d.ts
+++ b/src/types/layers.d.ts
@@ -339,6 +339,7 @@ export type LayerVisConfigSettings = {
radiusRange: VisConfigRange;
clusterRadius: VisConfigNumber;
clusterRadiusRange: VisConfigRange;
+ minClusterSize: VisConfigNumber;
opacity: VisConfigNumber;
coverage: VisConfigNumber;
outline: VisConfigBoolean;
diff --git a/test/browser/components/side-panel/layer-configurator-test.js b/test/browser/components/side-panel/layer-configurator-test.js
index ce6379eb6..0495c7075 100644
--- a/test/browser/components/side-panel/layer-configurator-test.js
+++ b/test/browser/components/side-panel/layer-configurator-test.js
@@ -12,6 +12,7 @@ import {
LayerColumnModeConfigFactory,
LayerColumnConfigFactory,
LayerConfigGroupFactory,
+ TextLabelPanelFactory,
FieldSelectorFactory,
ColumnSelectorFactory,
appInjector,
@@ -31,6 +32,7 @@ import {
} from 'test/helpers/component-utils';
import {act} from 'react-dom/test-utils';
import {STYLED_COMPONENTS_DUPLICATED_ENTRIES} from '../../../helpers/utils';
+import {KeplerGlLayers} from '@kepler.gl/layers';
// components
const LayerConfigurator = appInjector.get(LayerConfiguratorFactory);
@@ -39,6 +41,7 @@ const LayerColumnConfig = appInjector.get(LayerColumnConfigFactory);
const LayerConfigGroup = appInjector.get(LayerConfigGroupFactory);
const ColumnSelector = appInjector.get(ColumnSelectorFactory);
const FieldSelector = appInjector.get(FieldSelectorFactory);
+const TextLabelPanel = appInjector.get(TextLabelPanelFactory);
// components
const openModal = () => {};
@@ -144,6 +147,22 @@ test('Components -> LayerConfigurator.mount -> default prop 1', t => {
t.end();
});
+test('Components -> LayerConfigurator localizes the aggregation count label', t => {
+ const layer = new KeplerGlLayers.ClusterLayer({id: 'cluster', dataId: testCsvDataId});
+ const wrapper = mountWithTheme(
+ <IntlWrapper locale="es">
+ <LayerConfigurator {...defaultProps} layer={layer} />
+ </IntlWrapper>
+ );
+
+ t.ok(
+ wrapper.find(TextLabelPanel).text().includes('Recuento de puntos'),
+ 'should render the localized Point Count field name'
+ );
+
+ t.end();
+});
+
test('Components -> LayerConfigurator.mount -> LayerColumnConfig', t => {
// mount
const updateLayerConfigSpy = sinon.spy();
diff --git a/test/browser/layer-tests/cluster-layer-specs.js b/test/browser/layer-tests/cluster-layer-specs.js
index c46a51482..8007c585c 100644
--- a/test/browser/layer-tests/cluster-layer-specs.js
+++ b/test/browser/layer-tests/cluster-layer-specs.js
@@ -238,8 +238,8 @@ test('#ClusterLayer -> renderLayer', t => {
assert: (deckLayers, layer) => {
t.deepEqual(
deckLayers.map(l => l.id),
- ['test_layer_1', 'test_layer_1-cluster'],
- 'Should create 2 deck.gl layers'
+ ['test_layer_1', 'test_layer_1-cluster', 'test_layer_1-label-pointCount-collision'],
+ 'Should create the cluster layer, bubbles, and count labels'
);
const [clusterLayer, scatterplotLayer] = deckLayers;
const {props} = clusterLayer;
@@ -308,6 +308,29 @@ test('#ClusterLayer -> renderLayer', t => {
'should pass correct data to cluster layer'
);
+ const labelLayer = deckLayers.find(l => l.id === 'test_layer_1-label-pointCount-collision');
+ t.equal(
+ labelLayer.constructor.layerName,
+ 'CollisionTextLayer',
+ 'count labels use collision'
+ );
+ t.equal(labelLayer.props.collisionEnabled, true, 'collision is on by default');
+ t.equal(labelLayer.props.getTextAnchor, 'middle', 'count is centered on the bubble');
+ t.equal(labelLayer.props.getAlignmentBaseline, 'center', 'count is centered on the bubble');
+ t.equal(
+ labelLayer.props.parameters.depthTest,
+ false,
+ 'labels draw on top of geometry, like geojson text'
+ );
+ t.deepEqual(
+ labelLayer.props.data.map(d => ({
+ position: labelLayer.props.getPosition(d),
+ text: labelLayer.props.getText(d)
+ })),
+ expectedScatterplotData.map(d => ({position: d.position, text: '1'})),
+ 'each bubble is labeled with its point count'
+ );
+
const expectedColorDomain = {
domain: [1, 1, 1],
aggregatedBins: {
@@ -347,3 +370,130 @@ test('#ClusterLayer -> renderLayer', t => {
testRenderLayerCases(t, ClusterLayer, TEST_CASES);
t.end();
});
+
+test('#ClusterLayer -> minClusterSize hides small clusters', t => {
+ // zoom 8 merges rows 4 and 5 into one cluster and leaves row 7 on its own
+ const renderArgs = {
+ mapState: {...INITIAL_MAP_STATE, zoom: 8},
+ layerCallbacks: {onSetLayerDomain: () => {}}
+ };
+ const datasets = {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex: [0, 1, 2, 4, 5, 7]
+ }
+ };
+ const clusterConfig = minClusterSize => ({
+ type: 'cluster',
+ id: `test_cutoff_${minClusterSize}`,
+ config: {
+ dataId,
+ label: 'cluster cutoff',
+ columns,
+ color: [1, 2, 3],
+ visConfig: {
+ minClusterSize,
+ colorRange: {
+ colors: ['#080808', '#090909', '#070707']
+ }
+ }
+ }
+ });
+ const clusterCounts = deckLayers => {
+ const scatterplot = deckLayers.find(l => l.id.endsWith('-cluster'));
+ return scatterplot.props.data.map(d => d.points.length);
+ };
+
+ testRenderLayerCases(t, ClusterLayer, [
+ {
+ name: 'cluster without a cutoff',
+ layer: clusterConfig(1),
+ datasets,
+ renderArgs,
+ assert: deckLayers => {
+ t.deepEqual(
+ clusterCounts(deckLayers).sort(),
+ [1, 2],
+ 'the default keeps the single point cluster'
+ );
+ }
+ },
+ {
+ name: 'cluster with a cutoff of 2',
+ layer: clusterConfig(2),
+ datasets,
+ renderArgs,
+ assert: deckLayers => {
+ const clusterLayer = deckLayers[0];
+ t.equal(clusterLayer.props.minPointCount, 2, 'should pass the cutoff to the deck layer');
+
+ const scatterplot = deckLayers.find(l => l.id.endsWith('-cluster'));
+ t.deepEqual(
+ scatterplot.props.data.map(d => ({count: d.points.length, index: d.index})),
+ [{count: 2, index: 0}],
+ 'should drop the single point cluster and reindex the rest'
+ );
+
+ const labelLayer = deckLayers.find(l => l.id.includes('-label-'));
+ t.deepEqual(
+ labelLayer.props.data.map(labelLayer.props.getText),
+ ['2'],
+ 'only the remaining cluster is labeled'
+ );
+ }
+ },
+ {
+ name: 'cluster with a cutoff above every cluster',
+ layer: clusterConfig(10),
+ datasets,
+ renderArgs,
+ assert: deckLayers => {
+ t.deepEqual(clusterCounts(deckLayers), [], 'should render nothing instead of failing');
+ }
+ }
+ ]);
+ t.end();
+});
+
+test('#ClusterLayer -> count labels follow the text label field', t => {
+ testRenderLayerCases(t, ClusterLayer, [
+ {
+ name: 'cluster without a count label',
+ layer: {
+ type: 'cluster',
+ id: 'test_layer_nolabel',
+ config: {
+ dataId,
+ label: 'no labels',
+ columns,
+ color: [1, 2, 3],
+ textLabel: [
+ {
+ field: null,
+ collisionEnabled: true
+ }
+ ],
+ visConfig: {
+ colorRange: {
+ colors: ['#080808', '#090909', '#070707']
+ }
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex: [0, 1, 2, 4, 5, 7]
+ }
+ },
+ assert: deckLayers => {
+ t.deepEqual(
+ deckLayers.map(l => l.id),
+ ['test_layer_nolabel', 'test_layer_nolabel-cluster'],
+ 'clearing the label field removes the count text'
+ );
+ }
+ }
+ ]);
+ t.end();
+});
diff --git a/test/browser/layer-tests/grid-layer-specs.js b/test/browser/layer-tests/grid-layer-specs.js
index 1a0d0a4c9..02cfbd536 100644
--- a/test/browser/layer-tests/grid-layer-specs.js
+++ b/test/browser/layer-tests/grid-layer-specs.js
@@ -279,8 +279,8 @@ test('#GridLayer -> renderLayer', t => {
assert: (deckLayers, layer) => {
t.deepEqual(
deckLayers.map(l => l.id),
- ['test_layer_1', 'test_layer_1-cells'],
- 'Should create 2 deck.gl layers'
+ ['test_layer_1', 'test_layer_1-cells', 'test_layer_1-label-pointCount-collision'],
+ 'Should create the grid layer, cells, and count labels'
);
const [cpuGridLayer, gridCellLayer] = deckLayers;
const {props} = cpuGridLayer;
@@ -466,8 +466,8 @@ test('#GridLayer -> renderLayer', t => {
assert: deckLayers => {
t.deepEqual(
deckLayers.map(l => l.id),
- ['test_layer_2', 'test_layer_2-cells'],
- 'Should create 2 deck.gl layers'
+ ['test_layer_2', 'test_layer_2-cells', 'test_layer_2-label-pointCount-collision'],
+ 'Should create the grid layer, cells, and count labels'
);
const [cpuGridLayer, gridCellLayer] = deckLayers;
const {props} = cpuGridLayer;
diff --git a/test/browser/layer-tests/hexagon-layer-specs.js b/test/browser/layer-tests/hexagon-layer-specs.js
index b41d34447..a7533d598 100644
--- a/test/browser/layer-tests/hexagon-layer-specs.js
+++ b/test/browser/layer-tests/hexagon-layer-specs.js
@@ -279,12 +279,19 @@ test('#HexagonLayer -> renderLayer', t => {
assert: (deckLayers, layer) => {
t.deepEqual(
deckLayers.map(l => l.id),
- ['test_layer_1', 'test_layer_1-cells'],
- 'Should create 2 deck.gl layers'
+ ['test_layer_1', 'test_layer_1-cells', 'test_layer_1-label-pointCount-collision'],
+ 'Should create the hexagon layer, cells, and count labels'
);
const [deckHexLayer, hexCellLayer] = deckLayers;
const {props} = deckHexLayer;
+ const labelLayer = deckLayers.find(l => l.id === 'test_layer_1-label-pointCount-collision');
+ t.equal(labelLayer.props.collisionEnabled, true, 'hexagon count labels collide by default');
+ t.equal(labelLayer.props.parameters.depthTest, false, 'labels paint on top of the cells');
+ labelLayer.props.data.forEach(d => {
+ t.equal(labelLayer.props.getPosition(d).length, 2, 'count sits at the cell base');
+ t.equal(labelLayer.props.getText(d), String(d.count), 'label text is the point count');
+ });
const expectedProps = {
coverage: layer.config.visConfig.coverage,
@@ -467,8 +474,8 @@ test('#HexagonLayer -> renderLayer', t => {
assert: deckLayers => {
t.deepEqual(
deckLayers.map(l => l.id),
- ['test_layer_1', 'test_layer_1-cells'],
- 'Should create 2 deck.gl layers'
+ ['test_layer_1', 'test_layer_1-cells', 'test_layer_1-label-pointCount-collision'],
+ 'Should create the hexagon layer, cells, and count labels'
);
const [deckHexLayer, hexCellLayer] = deckLayers;
@@ -695,6 +702,71 @@ test('#HexagonLayer -> renderHover', t => {
t.end();
});
+test('#HexagonLayer -> extruded count labels stay at the cell base', t => {
+ testRenderLayerCases(t, HexagonLayer, [
+ {
+ name: 'extruded hexagon count labels',
+ layer: {
+ type: 'hexagon',
+ id: 'test_layer_extruded',
+ config: {
+ dataId,
+ label: 'extruded hexes',
+ columns,
+ visConfig: {
+ worldUnitSize: 20,
+ enable3d: true,
+ colorRange: {
+ colors: ['#010101', '#020202', '#030303']
+ }
+ }
+ }
+ },
+ datasets: {
+ [dataId]: {
+ ...preparedDataset,
+ filteredIndex
+ }
+ },
+ renderArgs: {
+ layerCallbacks: {
+ onSetLayerDomain: () => {}
+ }
+ },
+ assert: deckLayers => {
+ const labelLayer = deckLayers.find(
+ l => l.id === 'test_layer_extruded-label-pointCount-collision'
+ );
+ t.deepEqual(
+ deckLayers.map(l => l.id),
+ [
+ 'test_layer_extruded',
+ 'test_layer_extruded-cells',
+ 'test_layer_extruded-label-pointCount-collision'
+ ],
+ 'extruded hexagon still draws count labels'
+ );
+ if (!labelLayer) {
+ return;
+ }
+ t.ok(labelLayer.props.data.length > 0, 'extruded hexagon has counts to draw');
+ // GeoJSON labels sit at the polygon base and disable the depth test so
+ // they draw on top of the extrusion. Count labels follow that.
+ t.equal(labelLayer.props.parameters.depthTest, false, 'labels are not buried in columns');
+ labelLayer.props.data.forEach(d => {
+ t.deepEqual(
+ labelLayer.props.getPosition(d),
+ d.position,
+ 'extruded cell label has no elevation'
+ );
+ t.equal(d.position.length, 2, 'label position is lng/lat only');
+ });
+ }
+ }
+ ]);
+ t.end();
+});
+
test('#HexagonLayer -> updateLayerVisualChannel jenks', t => {
const layer = new HexagonLayer({dataId: 'blue'});
const binValues = [1, 1, 1, 50, 51, 52, 1000, 1001, 1002];
diff --git a/test/helpers/mock-state.js b/test/helpers/mock-state.js
index 72ddf49c3..c6b4d0804 100644
--- a/test/helpers/mock-state.js
+++ b/test/helpers/mock-state.js
@@ -794,6 +794,17 @@ function mockStateWithLayerStyling() {
return prepareState;
}
+// Schema stores the label field as {name, type}. New hexagon layers label point counts.
+const SAVED_AGGREGATION_COUNT_TEXT_LABEL = {
+ ...DEFAULT_TEXT_LABEL,
+ field: {name: 'pointCount', type: 'integer'},
+ anchor: 'middle',
+ alignment: 'center',
+ collisionEnabled: true,
+ outlineWidth: 1,
+ outlineColor: [0, 0, 0, 255]
+};
+
// saved hexagon layer
export const expectedSavedLayer0 = {
id: 'hexagon-2',
@@ -826,7 +837,7 @@ export const expectedSavedLayer0 = {
sizeAggregation: 'count',
enable3d: false
},
- textLabel: [DEFAULT_TEXT_LABEL]
+ textLabel: [SAVED_AGGREGATION_COUNT_TEXT_LABEL]
},
visualChannels: {
colorField: null,
@@ -872,7 +883,7 @@ export const expectedLoadedLayer0 = {
colorScale: 'quantile',
sizeField: null,
sizeScale: 'linear',
- textLabel: [DEFAULT_TEXT_LABEL]
+ textLabel: [SAVED_AGGREGATION_COUNT_TEXT_LABEL]
}
};
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index f5d05b23c..8624ba591 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -27,7 +27,12 @@ import {
} from '@kepler.gl/reducers';
import {processCsvData, processGeojson, remoteDatasetFromUrl} from '@kepler.gl/processors';
-import {Layer, KeplerGlLayers, COLUMN_MODE_TABLE} from '@kepler.gl/layers';
+import {
+ Layer,
+ KeplerGlLayers,
+ COLUMN_MODE_TABLE,
+ createPointCountLabelField
+} from '@kepler.gl/layers';
import {copyTableAndUpdate, maybeToDate} from '@kepler.gl/table';
import {
createDataContainer,
@@ -1284,6 +1289,71 @@ test('#visStateReducer -> LAYER_TEXT_LABEL_CHANGE', t => {
t.end();
});
+test('#visStateReducer -> LAYER_TEXT_LABEL_CHANGE -> cluster point count is added once', t => {
+ const initialState = StateWFiles.visState;
+ const pointLayer = initialState.layers.find(l => l.type === 'point');
+ const resetState = reducer(
+ initialState,
+ VisStateActions.layerConfigChange(pointLayer, {
+ textLabel: [{...DEFAULT_TEXT_LABEL}]
+ })
+ );
+ const resetPoint = resetState.layers.find(l => l.id === pointLayer.id);
+ const clusterState = reducer(resetState, VisStateActions.layerTypeChange(resetPoint, 'cluster'));
+ const clusterLayer = clusterState.layers.find(l => l.type === 'cluster');
+
+ t.equal(clusterLayer.config.textLabel.length, 1, 'type change keeps one label slot');
+ t.equal(clusterLayer.config.textLabel[0].field, null, 'copied point label has no field');
+
+ const pointCountField = createPointCountLabelField();
+ const selectedState = reducer(
+ clusterState,
+ VisStateActions.layerTextLabelChange(clusterLayer, 'all', 'fields', [pointCountField])
+ );
+ const selectedLayer = selectedState.layers.find(l => l.type === 'cluster');
+ const selected = selectedLayer.config.textLabel;
+
+ t.equal(selected.length, 1, 'picking Point Count adds one label');
+ t.equal(selected[0].field.name, 'pointCount');
+ t.equal(selected[0].field.fieldIdx, -1);
+ t.equal(selected[0].anchor, 'middle');
+ t.equal(selected[0].alignment, 'center');
+ t.equal(selected[0].collisionEnabled, true);
+ t.equal(selected[0].outlineWidth, 1);
+
+ const again = reducer(
+ selectedState,
+ VisStateActions.layerTextLabelChange(selectedLayer, 'all', 'fields', [pointCountField])
+ );
+ t.equal(
+ again.layers.find(l => l.type === 'cluster').config.textLabel.length,
+ 1,
+ 'picking Point Count again keeps one label'
+ );
+
+ const added = reducer(
+ selectedState,
+ VisStateActions.layerTextLabelChange(selectedLayer, selected.length)
+ );
+ const addedLabels = added.layers.find(l => l.type === 'cluster').config.textLabel;
+ t.equal(addedLabels.length, 2, 'add more label appends a slot');
+ t.equal(addedLabels[1].field, null, 'the extra slot does not clone Point Count');
+
+ const pointState = reducer(
+ selectedState,
+ VisStateActions.layerTypeChange(selectedLayer, 'point')
+ );
+ const convertedPointLayer = pointState.layers.find(l => l.type === 'point');
+ t.equal(convertedPointLayer.config.textLabel.length, 1, 'type change keeps one label slot');
+ t.equal(
+ convertedPointLayer.config.textLabel[0].field,
+ null,
+ 'type change clears the synthetic Point Count field'
+ );
+
+ t.end();
+});
+
test('#visStateReducer -> SET_COLUMN_DISPLAY_FORMAT updates text labels', t => {
const initialState = CloneDeep(StateWFiles.visState);
const otherDataId = 'other-data';