Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(layers): Add API for custom icons in icon layer (#3502)
Igor Dykhta90ea55c4d050
diff --git a/examples/demo-app/src/app.tsx b/examples/demo-app/src/app.tsxindex 3c526a467..f7d465b86 100644--- a/examples/demo-app/src/app.tsx+++ b/examples/demo-app/src/app.tsx@@ -68,7 +68,6 @@ import sampleAnimateTrip, {replacePointData,config as syncedTripConfig} from './data/sample-animate-trip-data';-import sampleIconCsv from './data/sample-icon-csv';import sampleGpsData from './data/sample-gps-data';import sampleRowData, {config as rowDataConfig} from './data/sample-row-data';import {sampleFlowData, config as flowDataConfig} from './data/sample-flow-data';@@ -422,7 +421,19 @@ const App = props => {}, [dispatch]);const _loadIconData = useCallback(() => {- // load icon data and config and process csv file+ // Demonstrates all 3 icon sources:+ // 1. CDN icons (e.g. 'accel') - fetched automatically+ // 2. Inline custom icons (e.g. 'custom-star'') - via initApplicationConfig({ customIcons })+ // 3. Remote custom icons (e.g. 'remote-triangle', 'remote-cross', 'remote-hexagon') - via customIconUrl+ const csvData = [+ 'time,lat,lng,icon,annotation-severity,annotation-html',+ '2016-06-28 20:10:00,37.780,-122.410,accel,5,"Default CDN icon"',+ '2016-06-28 20:10:10,37.782,-122.415,custom-star,5,"Inline custom star"',+ '2016-06-28 20:10:30,37.778,-122.405,remote-triangle,3,"Remote triangle icon"',+ '2016-06-28 20:10:40,37.784,-122.420,remote-cross,2,"Remote cross icon"',+ '2016-06-28 20:10:50,37.772,-122.412,remote-hexagon,4,"Remote hexagon icon"'+ ].join('\n');+dispatch(addDataToMap({datasets: [@@ -431,9 +442,34 @@ const App = props => {label: 'Icon Data',id: 'test_icon_data'},- data: processCsvData(sampleIconCsv)+ data: processCsvData(csvData)}- ]+ ],+ config: {+ version: 'v1',+ config: {+ visState: {+ layers: [+ {+ type: 'icon',+ config: {+ dataId: 'test_icon_data',+ label: 'Custom Icons',+ columns: {+ lat: 'lat',+ lng: 'lng',+ icon: 'icon'+ },+ isVisible: true,+ visConfig: {+ radius: 100+ }+ }+ }+ ]+ }+ }+ }}));}, [dispatch]);diff --git a/examples/demo-app/src/reducers/index.js b/examples/demo-app/src/reducers/index.jsindex 27c5054d6..a11b4d769 100644--- a/examples/demo-app/src/reducers/index.js+++ b/examples/demo-app/src/reducers/index.js@@ -16,6 +16,8 @@ import {getApplicationConfig} from '@kepler.gl/utils';// import {getApplicationConfig, initApplicationConfig} from '@kepler.gl/utils';// import keplerGlDuckdbPlugin, {KeplerGlDuckDbTable, DuckDBWasmAdapter} from '@kepler.gl/duckdb';+import {initApplicationConfig} from '@kepler.gl/utils';+import {INIT,LOAD_MAP_SAMPLE_FILE,@@ -49,6 +51,36 @@ initApplicationConfig({});*/+// Example: Register custom icons for the icon layer.+// These will be merged with the default icons fetched from CDN.+// Data values in the "icon" column matching these IDs will render the custom shapes.+// NOTE: Cell winding must be counter-clockwise (CCW) to match the CDN icon convention.+initApplicationConfig({+ customIcons: [+ {+ id: 'custom-star',+ mesh: {+ cells: [+ [5, 1, 0],+ [5, 2, 1],+ [5, 3, 2],+ [5, 4, 3],+ [5, 0, 4]+ ],+ positions: [+ [0, 1, 0],+ [0.95, 0.31, 0],+ [0.59, -0.81, 0],+ [-0.59, -0.81, 0],+ [-0.95, 0.31, 0],+ [0, 0, 0]+ ]+ }+ }+ ],+ customIconUrl: 'https://raw.githubusercontent.com/keplergl/kepler.gl-data/refs/heads/master/layers/icon/custom-icons.json'+});+const {DEFAULT_MAP_CONTROLS} = uiStateUpdaters;// INITIAL_APP_STATEdiff --git a/src/layers/src/icon-layer/icon-layer.ts b/src/layers/src/icon-layer/icon-layer.tsindex 50b9bbff2..e0e59e447 100644--- a/src/layers/src/icon-layer/icon-layer.ts+++ b/src/layers/src/icon-layer/icon-layer.ts@@ -14,6 +14,7 @@ import {isTest} from '@kepler.gl/utils';import {getTextOffsetByRadius, formatTextLabelData} from '../layer-text-label';import {default as KeplerTable} from '@kepler.gl/table';import {getApplicationConfig, DataContainerInterface} from '@kepler.gl/utils';+import type {SvgIcon} from '@kepler.gl/utils';import {ColorRange,VisConfigBoolean,@@ -159,7 +160,7 @@ export default class IconLayer extends Layer {props: {id?: string;iconGeometry?: IconGeometry;- svgIcons?: any[];+ svgIcons?: SvgIcon[];} & LayerBaseConfigPartial) {super(props);@@ -248,32 +249,54 @@ export default class IconLayer extends Layer {cache: 'no-cache'};- if (Window.fetch && this.svgIconUrl) {- Window.fetch(this.svgIconUrl, fetchConfig)- .then(response => {- if (!response.ok) {- throw new Error(`Failed to load svg-icons.json: ${response.status}`);- }- return response.json();- })- .then((parsed: {svgIcons?: any[]} = {}) => {- this.setSvgIcons(parsed.svgIcons);- })- .catch(err => {- console.error('Error fetching or parsing svg-icons.json:', err);- // Fallback to empty geometry to allow default icon rendering- this.iconGeometry = {};- this.iconGeometryVersion += 1;- });- } else {- // No fetch available; set empty geometry so layer can render default icons- this.iconGeometry = {};- this.iconGeometryVersion += 1;- }+ const appConfig = getApplicationConfig();+ const customIconUrl = appConfig.customIconUrl;++ const cdnPromise =+ Window.fetch && this.svgIconUrl+ ? Window.fetch(this.svgIconUrl, fetchConfig)+ .then(response => {+ if (!response.ok) {+ throw new Error(`Failed to load svg-icons.json: ${response.status}`);+ }+ return response.json();+ })+ .then((parsed: {svgIcons?: SvgIcon[]} = {}) => parsed.svgIcons || [])+ .catch(err => {+ console.error('Error fetching or parsing svg-icons.json:', err);+ return [] as SvgIcon[];+ })+ : Promise.resolve([] as SvgIcon[]);++ const customUrlPromise =+ Window.fetch && customIconUrl+ ? Window.fetch(customIconUrl, fetchConfig)+ .then(response => {+ if (!response.ok) {+ throw new Error(`Failed to load custom icons from ${customIconUrl}: ${response.status}`);+ }+ return response.json();+ })+ .then((parsed: {svgIcons?: SvgIcon[]} = {}) => parsed.svgIcons || [])+ .catch(err => {+ console.error(`Error fetching custom icons from ${customIconUrl}:`, err);+ return [] as SvgIcon[];+ })+ : Promise.resolve([] as SvgIcon[]);++ Promise.all([cdnPromise, customUrlPromise]).then(([cdnIcons, remoteCustomIcons]) => {+ const mergedCdnAndRemote = this.mergeIcons(cdnIcons, remoteCustomIcons);+ this.setSvgIcons(mergedCdnAndRemote);+ }).catch(() => {+ this.setSvgIcons([]);+ });}- setSvgIcons(svgIcons: any[] = []) {- this.iconGeometry = svgIcons.reduce(+ setSvgIcons(svgIcons: SvgIcon[] = []) {+ const customIcons = getApplicationConfig().customIcons || [];+ const allIcons = this.mergeIcons(svgIcons, customIcons);++ this.iconGeometry = allIcons.reduce((accu, curr) => ({...accu,[curr.id]: flatterIconPositions(curr)@@ -284,12 +307,29 @@ export default class IconLayer extends Layer {// Increment version when SVG icons are loaded to trigger layer re-renderthis.iconGeometryVersion += 1;- this._layerInfoModal = IconInfoModalFactory(svgIcons);+ this._layerInfoModal = IconInfoModalFactory(allIcons);// Trigger a map redraw so deck.gl picks up the new geometrythis.onRedrawNeeded?.();}+ /**+ * Merge default icons with custom icons. Custom icons with the same id+ * as a default icon will override the default.+ */+ mergeIcons(defaultIcons: SvgIcon[], customIcons: SvgIcon[]): SvgIcon[] {+ if (!customIcons.length) return defaultIcons;++ const iconMap = new Map<string, SvgIcon>();+ for (const icon of defaultIcons) {+ iconMap.set(icon.id, icon);+ }+ for (const icon of customIcons) {+ iconMap.set(icon.id, icon);+ }+ return Array.from(iconMap.values());+ }+static findDefaultLayerProps({fieldPairs = [],fields = []diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex 3dec769c4..19fcb9c4e 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -8,6 +8,25 @@ import type {BaseMapLibraryType} from '@kepler.gl/constants';import type {DatabaseAdapter} from './application-config-types';+/**+ * Represents a custom SVG icon that can be used in the icon layer.+ * The mesh describes the icon's geometry as triangulated SVG paths.+ *+ * Important: Triangle cells must use counter-clockwise (CCW) winding order.+ * Positions should be in the range [-1, 1] on both axes.+ */+export type SvgIcon = {+ /** Unique identifier for the icon, used as the value in the data's icon column */+ id: string;+ /** Triangulated SVG path geometry */+ mesh: {+ /** Triangle cell indices referencing positions (CCW winding order) */+ cells: [number, number, number][];+ /** Vertex positions [x, y, z] in range [-1, 1] */+ positions: [number, number, number][];+ };+};+/*** Detect if running with webpack build tool*/@@ -108,6 +127,42 @@ export type KeplerApplicationConfig = {/** Whether to enable the swipe compare mode in split map view. Enabled by default. */enableSwipeMode?: boolean;++ /**+ * Custom SVG icons to be made available in the icon layer.+ * These icons will be merged with the default icons fetched from CDN.+ * Each icon must have a unique `id` and a `mesh` describing its triangulated geometry.+ *+ * @example+ * ```+ * initApplicationConfig({+ * customIcons: [+ * {+ * id: 'my-custom-marker',+ * mesh: {+ * cells: [[0, 1, 2], [2, 3, 0]],+ * positions: [[0, 1, 0], [1, -1, 0], [-1, -1, 0], [0, 0, 0]]+ * }+ * }+ * ]+ * });+ * ```+ */+ customIcons?: SvgIcon[];++ /**+ * URL to a remote JSON file containing custom SVG icons.+ * The JSON file should have the format: `{ "svgIcons": [{ id, mesh: { cells, positions } }, ...] }`+ * Icons from this URL will be merged with default CDN icons and inline `customIcons`.+ *+ * @example+ * ```+ * initApplicationConfig({+ * customIconUrl: 'https://my-server.com/my-icons.json'+ * });+ * ```+ */+ customIconUrl?: string;};const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {@@ -180,7 +235,11 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {enableMapNavigationControl: true,- enableSwipeMode: true+ enableSwipeMode: true,++ customIcons: [],++ customIconUrl: ''};const applicationConfig: Required<KeplerApplicationConfig> = DEFAULT_APPLICATION_CONFIG;diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex ec0394b22..0b84e0972 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -183,7 +183,8 @@ export type {KeplerApplicationConfig,BaseMapLibraryConfig,MapLibInstance,- GetMapRef+ GetMapRef,+ SvgIcon} from './application-config';export type {DatabaseAdapter, DatabaseConnection} from './application-config-types';