// SPDX-License-Identifier: MIT // Copyright contributors to the kepler.gl project import {createSelector} from 'reselect'; import KeplerHeatmapLayer from './deck-heatmap-layer'; import {getVisualZoom} from '../layer-zoom'; import { CHANNEL_SCALES, ALL_FIELD_TYPES, GEOJSON_FIELDS, GEOARROW_METADATA_KEY, SCALE_TYPES } from '@kepler.gl/constants'; import Layer, { LayerBaseConfigPartial, LayerColorConfig, LayerWeightConfig, VisualChannel, VisualChannelDomain, VisualChannelScale, VisualChannels } from '../base-layer'; import HeatmapLayerIcon from './heatmap-layer-icon'; import { ColorRange, VisConfigColorRange, VisConfigNumber, VisConfigBoolean, VisConfigSelection, HexColor, RGBColor, Merge, LayerColumn, LayerBaseConfig, MapState } from '@kepler.gl/types'; import {hexToRgb, DataContainerInterface} from '@kepler.gl/utils'; import {notNullorUndefined} from '@kepler.gl/common-utils'; import {Datasets, KeplerTable} from '@kepler.gl/table'; import {DATA_TYPES} from 'type-analyzer'; import {booleanWithin} from '@turf/boolean-within'; import {point as turfPoint} from '@turf/helpers'; import {Feature, Polygon} from 'geojson'; import { getGeoArrowPointLayerProps, FindDefaultLayerPropsReturnValue, getGeoArrowPointCoords } from '../layer-utils'; import {getFilterDataFunc} from '../aggregation-layer'; import { parseGeoJsonRawFeature, getCentroidFromGeometry, getAllPositions } from '../geojson-layer/geojson-utils'; export type HeatmapLayerVisConfigSettings = { opacity: VisConfigNumber; colorRange: VisConfigColorRange; radius: VisConfigNumber; intensity: VisConfigNumber; threshold: VisConfigNumber; aggregation: VisConfigSelection; surfaceEnabled: VisConfigBoolean; surfaceHeight: VisConfigNumber; surfaceLighting: VisConfigBoolean; surfaceContours: VisConfigBoolean; surfaceContourStep: VisConfigNumber; }; export type HeatmapLayerColumnsConfig = { // COLUMN_MODE_POINTS lat: LayerColumn; lng: LayerColumn; // COLUMN_MODE_GEOARROW geoarrow: LayerColumn; // COLUMN_MODE_GEOJSON geojson: LayerColumn; }; export type HeatmapLayerVisConfig = { opacity: number; colorRange: ColorRange; radius: number; intensity: number; threshold: number; aggregation: string; surfaceEnabled: boolean; surfaceHeight: number; surfaceLighting: boolean; surfaceContours: boolean; surfaceContourStep: number; }; export type HeatmapLayerVisualChannelConfig = LayerWeightConfig & LayerColorConfig & { weightDomain: VisualChannelDomain; weightScale: VisualChannelScale; }; export type HeatmapLayerConfig = Merge< LayerBaseConfig, {columns: HeatmapLayerColumnsConfig; visConfig: HeatmapLayerVisConfig} > & HeatmapLayerVisualChannelConfig; export const MAX_ZOOM_LEVEL = 18; // Legend-only: heatmap GPU color is density × colorRange, not a data field. // Keep this off `visualChannels` so layer type change does not copy colorField. const HEATMAP_LEGEND_COLOR_CHANNEL: VisualChannel = { property: 'color', field: 'colorField', scale: 'colorScale', domain: 'colorDomain', range: 'colorRange', key: 'color', channelScaleType: CHANNEL_SCALES.color, defaultMeasure: 'property.density' }; export const pointPosAccessor = ({lat, lng}: HeatmapLayerColumnsConfig) => (dc: DataContainerInterface) => (d: {index: number}): number[] => [dc.valueAt(d.index, lng.fieldIdx), dc.valueAt(d.index, lat.fieldIdx)]; export const geoarrowPosAccessor = ({geoarrow}: HeatmapLayerColumnsConfig) => (dc: DataContainerInterface) => (d: {index: number}): number[] => { const row = dc.valueAt(d.index, geoarrow.fieldIdx); const coords = getGeoArrowPointCoords(row); return [coords[0], coords[1]]; }; export const geojsonAccessor = ({geojson}: HeatmapLayerColumnsConfig) => (dc: DataContainerInterface) => (d: {index: number}) => dc.valueAt(d.index, geojson.fieldIdx); export const pointColResolver = ( {lat, lng, geoarrow, geojson}: HeatmapLayerColumnsConfig, columnMode ) => { if (columnMode === COLUMN_MODE_POINTS) { return `${lat.fieldIdx}-${lng.fieldIdx}`; } if (columnMode === COLUMN_MODE_GEOJSON) { return `geojson-${geojson.fieldIdx}`; } 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; surfaceEnabled: VisConfigBoolean; surfaceHeight: VisConfigNumber; surfaceLighting: VisConfigBoolean; surfaceContours: VisConfigBoolean; surfaceContourStep: VisConfigNumber; } = { surfaceEnabled: { type: 'boolean', defaultValue: false, label: 'layerVisConfigs.heatmap.surface', property: 'surfaceEnabled' } as VisConfigBoolean, surfaceHeight: { type: 'number', defaultValue: 1000, label: 'layerVisConfigs.heatmap.surfaceHeight', description: 'layerVisConfigs.heatmap.surfaceHeightDescription', property: 'surfaceHeight', isRanged: false, range: [0, 100000], step: 10, focusRange: [0, 5000], focusWeight: 0.7 } as VisConfigNumber, surfaceLighting: { type: 'boolean', defaultValue: true, label: 'layerVisConfigs.heatmap.surfaceLighting', property: 'surfaceLighting' } as VisConfigBoolean, surfaceContours: { type: 'boolean', defaultValue: false, label: 'layerVisConfigs.heatmap.surfaceContours', property: 'surfaceContours' } as VisConfigBoolean, surfaceContourStep: { type: 'number', defaultValue: 0.1, label: 'layerVisConfigs.heatmap.surfaceContourStep', description: 'layerVisConfigs.heatmap.surfaceContourStepDescription', property: 'surfaceContourStep', isRanged: false, range: [0.01, 100], step: 0.01, focusRange: [0.01, 1], focusWeight: 0.5 } as VisConfigNumber, opacity: 'opacity', colorRange: 'colorRange', radius: 'heatmapRadius', intensity: { type: 'number', label: 'layerVisConfigs.intensity', defaultValue: 1, isRanged: false, range: [0.001, 20], step: 0.001, property: 'intensity', focusRange: [0.001, 0.5], focusWeight: 0.4 } 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']; export const geoarrowRequiredColumns = ['geoarrow']; export const geojsonRequiredColumns = ['geojson']; export const COLUMN_MODE_POINTS = 'points'; export const COLUMN_MODE_GEOARROW = 'geoarrow'; export const COLUMN_MODE_GEOJSON = 'geojson'; const SUPPORTED_ANALYZER_TYPES = { [DATA_TYPES.GEOMETRY]: true, [DATA_TYPES.GEOMETRY_FROM_STRING]: true, [DATA_TYPES.PAIR_GEOMETRY_FROM_STRING]: true }; const SUPPORTED_COLUMN_MODES = [ { key: COLUMN_MODE_POINTS, label: 'Points', requiredColumns: pointRequiredColumns }, { key: COLUMN_MODE_GEOJSON, label: 'GeoJSON', requiredColumns: geojsonRequiredColumns }, { key: COLUMN_MODE_GEOARROW, label: 'Geoarrow Points', requiredColumns: geoarrowRequiredColumns } ]; const DEFAULT_COLUMN_MODE = COLUMN_MODE_POINTS; 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 Layer { declare visConfigSettings: HeatmapLayerVisConfigSettings; declare config: HeatmapLayerConfig; colorRampSelector = createSelector((colors: HexColor[]) => colors, toColorRamp); dataToFeature: any[] = []; centroids: Array = []; private _geojsonFieldIdx = -1; private _geojsonDataContainer: DataContainerInterface | null = null; private _geojsonDataRevision: number | undefined; private _geojsonBounds: [number, number, number, number] | null = null; constructor(props) { super(props); this.registerVisConfig(heatmapVisConfigs); this.getPositionAccessor = (dataContainer: DataContainerInterface) => { switch (this.config.columnMode) { case COLUMN_MODE_GEOARROW: return geoarrowPosAccessor(this.config.columns)(dataContainer); case COLUMN_MODE_GEOJSON: return geojsonAccessor(this.config.columns)(dataContainer); default: return pointPosAccessor(this.config.columns)(dataContainer); } }; } get type(): 'heatmap' { 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', 'surfaceEnabled', 'surfaceHeight', 'surfaceLighting', 'surfaceContours', 'surfaceContourStep' ]; } hasAllColumns() { const {columns, columnMode} = this.config; if (columnMode === COLUMN_MODE_GEOARROW) { return this.hasColumnValue(columns.geoarrow); } if (columnMode === COLUMN_MODE_GEOJSON) { return this.hasColumnValue(columns.geojson); } return super.hasAllColumns(); } static findDefaultLayerProps(dataset: KeplerTable): FindDefaultLayerPropsReturnValue { const altProps = getGeoArrowPointLayerProps(dataset); const geojsonColumns = dataset.fields .filter( f => (f.type === 'geojson' || f.type === 'geoarrow') && f.analyzerType && SUPPORTED_ANALYZER_TYPES[f.analyzerType] ) .map(f => f.name); const defaultColumns = { geojson: [...(GEOJSON_FIELDS.geojson || []), ...geojsonColumns] }; const foundColumns = this.findDefaultColumnField(defaultColumns, dataset.fields); if (foundColumns?.length) { const {label} = dataset; altProps.push( ...foundColumns.map(columns => ({ label: (typeof label === 'string' && label.replace(/\.[^/.]+$/, '')) || 'heatmap', columns, columnMode: COLUMN_MODE_GEOJSON })) ); } return { props: [], altProps }; } get visualChannels(): VisualChannels { return { // @ts-expect-error weight: { property: 'weight', field: 'weightField', scale: 'weightScale', domain: 'weightDomain', key: 'weight', defaultMeasure: 'property.density', supportedFieldTypes: [ALL_FIELD_TYPES.real, ALL_FIELD_TYPES.integer], channelScaleType: CHANNEL_SCALES.size } }; } getLegendVisualChannels() { const channels: VisualChannels = {color: HEATMAP_LEGEND_COLOR_CHANNEL}; // Show "weight by " when a weight column is selected. Default // density weighting is already represented by the color ramp. if (this.config.weightField) { channels.weight = this.visualChannels.weight; } return channels; } assignConfigToLayer( ...args: Parameters ): ReturnType { super.assignConfigToLayer(...args); // Density legend is not a color-by-field channel. Drop copied colorField / // colorScale / colorDomain from the previous layer type. this.updateLayerConfig({ colorField: null, colorScale: SCALE_TYPES.quantize, colorDomain: [0, 1] }); } get layerIcon() { return HeatmapLayerIcon; } getHoverData(): null { return null; } isInPolygon(data: DataContainerInterface, index: number, polygon: Feature): boolean { if (this.centroids.length === 0 || !this.centroids[index]) { return false; } const point = this.centroids[index]; if (!point) return false; const isRectangleSearchBox = polygon.properties?.shape === 'Rectangle'; if (isRectangleSearchBox && polygon.properties?.bbox) { const [minX, minY, maxX, maxY] = polygon.properties.bbox; return point[0] >= minX && point[0] <= maxX && point[1] >= minY && point[1] <= maxY; } return booleanWithin(turfPoint(point), polygon); } getVisualChannelDescription(channel) { return channel === 'color' ? { label: 'property.color', measure: 'property.density' } : { label: 'property.weight', measure: this.config.weightField ? this.config.weightField.name : 'property.density' }; } getDataUpdateTriggers(dataset: KeplerTable): any { const triggers = super.getDataUpdateTriggers(dataset); const {columnMode} = this.config; return { ...triggers, getData: {...triggers.getData, columnMode}, getMeta: {...triggers.getMeta, columnMode} }; } getDefaultLayerConfig(props: LayerBaseConfigPartial) { // Keep colorScale / colorDomain so the map legend can render the selected // color ramp. colorField stays unused: heatmap color is density, not a field. return { ...super.getDefaultLayerConfig(props), columnMode: props?.columnMode ?? DEFAULT_COLUMN_MODE, colorField: null, colorScale: SCALE_TYPES.quantize, colorDomain: [0, 1] as [number, number], weightField: null, weightDomain: [0, 1] as [number, number], weightScale: SCALE_TYPES.linear }; } updateLayerMeta(dataset: KeplerTable) { const {dataContainer} = dataset; if (this.config.columnMode === COLUMN_MODE_GEOJSON) { const getFeature = this.getPositionAccessor(dataContainer); const geoField = dataset.fields?.[this.config.columns.geojson.fieldIdx]; const encoding = geoField?.metadata && typeof (geoField.metadata as Map).get === 'function' ? (geoField.metadata as Map).get(GEOARROW_METADATA_KEY) : (geoField?.metadata as Record | undefined)?.[GEOARROW_METADATA_KEY]; this._buildGeojsonDataToFeature(dataset, getFeature, encoding); this.updateMeta({bounds: this._geojsonBounds}); } else { this.dataToFeature = []; this.centroids = []; const getPosition = this.getPositionAccessor(dataContainer); const bounds = this.getPointsBounds(dataContainer, getPosition); this.updateMeta({bounds}); } } /** * Parse raw GeoJSON values into Feature objects and store them. * Re-parses when the source container, revision, size or geometry column changes. */ private _buildGeojsonDataToFeature( dataset: KeplerTable, getFeature: any, geoArrowEncoding?: string | null ) { const {dataContainer, dataRevision} = dataset; const fieldIdx = this.config.columns.geojson.fieldIdx; if ( this.dataToFeature.length === dataContainer.numRows() && this._geojsonFieldIdx === fieldIdx && this._geojsonDataContainer === dataContainer && this._geojsonDataRevision === dataRevision ) { return; } this._geojsonFieldIdx = fieldIdx; this._geojsonDataContainer = dataContainer; this._geojsonDataRevision = dataRevision; this.dataToFeature = []; this.centroids = []; let minLng = Infinity; let maxLng = -Infinity; let minLat = Infinity; let maxLat = -Infinity; let hasValid = false; for (let i = 0; i < dataContainer.numRows(); i++) { const rawFeature = getFeature({index: i}); const feature = parseGeoJsonRawFeature(rawFeature, geoArrowEncoding); this.dataToFeature[i] = feature; this.centroids[i] = feature?.geometry ? getCentroidFromGeometry(feature.geometry) : null; if (feature?.geometry) { const positions = getAllPositions(feature.geometry); for (const pos of positions) { const lng = pos[0]; const lat = pos[1]; if (Number.isFinite(lng) && Number.isFinite(lat)) { hasValid = true; if (lng < minLng) minLng = lng; if (lng > maxLng) maxLng = lng; if (lat < minLat) minLat = lat; if (lat > maxLat) maxLat = lat; } } } } this._geojsonBounds = hasValid ? [minLng, minLat, maxLng, maxLat] : null; } calculateDataAttribute({filteredIndex}: KeplerTable, getPosition) { if (this.config.columnMode === COLUMN_MODE_GEOJSON) { return this._calculateGeojsonDataAttribute(filteredIndex); } 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}); } } return data; } /** * For GeoJSON mode, emit a single heatmap data entry per feature * at the geometry centroid (Point coordinates, or vertex average for * LineString / Polygon). */ private _calculateGeojsonDataAttribute(filteredIndex: number[]) { const data: {index: number; position: number[]}[] = []; for (let i = 0; i < filteredIndex.length; i++) { const index = filteredIndex[i]; const centroid = this.centroids[index] || (this.dataToFeature[index]?.geometry ? getCentroidFromGeometry(this.dataToFeature[index].geometry) : null); if (centroid && Number.isFinite(centroid[0]) && Number.isFinite(centroid[1])) { data.push({index, position: [centroid[0], centroid[1]]}); } } return data; } formatLayerData(datasets: Datasets, oldLayerData: unknown): Record { const {dataId} = this.config; if (!notNullorUndefined(dataId)) { return {}; } const dataset = datasets[dataId]; const {weightField, weightScale, weightDomain} = this.config; const {gpuFilter, dataContainer} = dataset; const oldData = oldLayerData as any; const baseOldLayerData = oldData?._unfiltered ? {...oldData, data: oldData._unfiltered} : oldLayerData; const {data = []} = this.updateData(datasets, baseOldLayerData); const isGeojsonMode = this.config.columnMode === COLUMN_MODE_GEOJSON; const getPosition = isGeojsonMode ? (d: {position: number[]}) => d.position : this.getPositionAccessor(dataContainer); // An active selection at the domain minimum also normalizes to [0, 0]. const hasFilter = Object.values(gpuFilter.filterValueUpdateTriggers).some( trigger => trigger !== null ); let filteredData = data; if (hasFilter) { const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)( (d: {index: number}) => d.index ); 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(String(weightScale), weightDomain, weightRange); getWeight = (d: {index: number}) => this.getEncodedChannelValue(scaleFunc || (x => x), d as any, weightField, 0 as any); } return { _unfiltered: data, data: filteredData, getWeight, getPosition }; } getDefaultDeckLayerProps(opts) { // Filtering happens on the CPU. Unused GPU-filter callbacks can change on // every render and incorrectly invalidate deck.gl's density aggregation. const baseProp = super.getDefaultDeckLayerProps({...opts, gpuFilter: undefined}); 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 globeMode = Boolean(mapState?.globe?.enabled); // In globe mode the density texture is framed around the data bounds rather // than the visible screen, so we need valid data bounds to render at all. const densityBounds = this.meta?.bounds as [number, number, number, number] | undefined; if (globeMode && (!densityBounds || densityBounds.length !== 4)) { return []; } const {_unfiltered, ...deckData} = data; const defaultLayerProps = this.getDefaultDeckLayerProps(opts); const {visConfig} = this.config; const colorRange = this.colorRampSelector(visConfig.colorRange.colors); const visualZoom = getVisualZoom(mapState); const intensity = interpolateByZoom( visualZoom, 0, visConfig.intensity, MAX_ZOOM_LEVEL, 3 * visConfig.intensity ); const radiusPixels = interpolateByZoom(visualZoom, 0, 2, MAX_ZOOM_LEVEL, visConfig.radius); const updateTriggers = { getPosition: {columns: this.config.columns, columnMode: this.config.columnMode}, getWeight: { weightField: this.config.weightField, weightScale: this.config.weightScale, weightDomain: this.config.weightDomain } }; return [ new KeplerHeatmapLayer({ ...defaultLayerProps, ...deckData, aggregation: (visConfig.aggregation || 'SUM') as 'SUM' | 'MEAN', radiusPixels, intensity, threshold: visConfig.threshold, updateTriggers, colorRange, weightsTextureSize: 512, // Reuse the density texture while panning and refresh after settling. debounceTimeout: 150, surface: visConfig.surfaceEnabled, surfaceHeight: Number.isFinite(visConfig.surfaceHeight) ? Math.max(0, visConfig.surfaceHeight) : 1000, surfaceLighting: visConfig.surfaceLighting !== false, surfaceContours: Boolean(visConfig.surfaceContours), surfaceContourStep: Number.isFinite(visConfig.surfaceContourStep) && visConfig.surfaceContourStep > 0 ? visConfig.surfaceContourStep : 0.1, // globe-mode extensions globeMode, densityBounds: densityBounds && densityBounds.length === 4 ? densityBounds : null }) ]; } } export default HeatmapLayer;