Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
chore(examples): add click info example (#3643)
Igor Dykhta423e1767e376
diff --git a/examples/README.md b/examples/README.mdindex 5d2d9f3b9..d4eb91689 100644--- a/examples/README.md+++ b/examples/README.md@@ -45,6 +45,9 @@ yarn start- ### [Custom Theme][custom-theme]Customize the kepler.gl theme by overriding default style properties.+- ### [Clicked Feature][clicked-feature]+ Read `visState.clicked` from Redux and show a GeoJSON feature's `shapeName` in a host-app sidebar outside the map.+- ### [Custom Layer][custom-layer]Add a custom deck.gl layer (`ContourLayer`) to kepler.gl's layer type selector, so it can be picked from the dropdown, configured with dataset columns, and rendered on the map.@@ -65,6 +68,7 @@ yarn start[custom-reducer]: custom-reducer/README.md[replace-component]: replace-component/README.md[custom-theme]: custom-theme/README.md+[clicked-feature]: clicked-feature/README.md[custom-layer]: custom-layer/README.md[custom-map-style]: custom-map-style/README.md[node-app]: node-app/README.mddiff --git a/examples/clicked-feature/.yarnrc.yml b/examples/clicked-feature/.yarnrc.ymlnew file mode 100644index 000000000..19e3db2fd--- /dev/null+++ b/examples/clicked-feature/.yarnrc.yml@@ -0,0 +1,4 @@+# https://yarnpkg.com/configuration/yarnrc+nodeLinker: node-modules+# Define the registry to use when fetching packages.+npmRegistryServer: 'https://registry.yarnpkg.com'diff --git a/examples/clicked-feature/README.md b/examples/clicked-feature/README.mdnew file mode 100644index 000000000..73e4a6d5b--- /dev/null+++ b/examples/clicked-feature/README.md@@ -0,0 +1,60 @@+# Clicked Feature Outside the Map++Shows how to read a clicked GeoJSON feature from Kepler.gl Redux state and+render it in a **host-app sidebar**, not in the on-map tooltip.++This answers [discussion #3054](https://github.com/keplergl/kepler.gl/discussions/3054):+subscribe to `visState.clicked` for the Kepler instance `id`.++## How it works++Layer clicks dispatch `onLayerClick`, which stores deck.gl pick info on+`state.keplerGl.<id>.visState.clicked`. Clicking empty map clears it.++For a GeoJSON polygon, original feature properties are kept on the picked+object (plus an internal `index`):++```ts+const clicked = useSelector(state => state.keplerGl.map.visState.clicked);+const shapeName = clicked?.object?.properties?.shapeName;+```++`<id>` must match the `KeplerGl` `id` prop (`map` in this example).++GeoJSON picking only works while **tooltip interaction is enabled** and the+layer has `allowHover: true` (the default).++## Pre-requirements++- [Node.js ^20.x](http://nodejs.org)+- [Yarn 4.4.0](https://yarnpkg.com): See the detailed [installation instructions][yarn-install].++## 1. Install Dependencies++Go to the `examples/clicked-feature` directory and run:++```sh+touch yarn.lock && yarn+```++> `touch yarn.lock` is required once to mark this directory as a standalone Yarn project,+> independent of the monorepo root.++## 2. Start the App++```sh+yarn start+```++The app will be available at [http://localhost:8080](http://localhost:8080).+Click a neighborhood polygon; `shapeName` appears in the right sidebar.++## Production Build++```sh+yarn build+```++The output will be in the `dist/` directory.++[yarn-install]: https://yarnpkg.com/getting-started/installdiff --git a/examples/clicked-feature/esbuild.config.mjs b/examples/clicked-feature/esbuild.config.mjsnew file mode 100644index 000000000..069364406--- /dev/null+++ b/examples/clicked-feature/esbuild.config.mjs@@ -0,0 +1,126 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import esbuild from 'esbuild';+import copyPlugin from 'esbuild-plugin-copy';+import process from 'node:process';+import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {spawn} from 'node:child_process';++const args = process.argv;++const __dirname = path.dirname(fileURLToPath(import.meta.url));++const port = 8080;++const config = {+ platform: 'browser',+ format: 'iife',+ logLevel: 'info',+ loader: {'.js': 'jsx', '.css': 'css'},+ entryPoints: ['src/app.tsx'],+ outfile: 'dist/bundle.js',+ bundle: true,+ define: {+ NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'production'),+ 'process.env.MapboxAccessToken': JSON.stringify(process.env.MapboxAccessToken || ''),+ 'process.env.DropboxClientId': JSON.stringify(process.env.DropboxClientId || ''),+ 'process.env.MapboxExportToken': JSON.stringify(process.env.MapboxExportToken || ''),+ 'process.env.CartoClientId': JSON.stringify(process.env.CartoClientId || ''),+ 'process.env.FoursquareClientId': JSON.stringify(process.env.FoursquareClientId || ''),+ 'process.env.FoursquareDomain': JSON.stringify(process.env.FoursquareDomain || ''),+ 'process.env.FoursquareAPIURL': JSON.stringify(process.env.FoursquareAPIURL || ''),+ 'process.env.FoursquareUserMapsURL': JSON.stringify(process.env.FoursquareUserMapsURL || ''),+ 'process.env.OpenAIToken': JSON.stringify(process.env.OpenAIToken || ''),+ 'process.env.NODE_DEBUG': JSON.stringify(false)+ },+ plugins: [+ // styled-components: @hubble.gl/react nests its own copy.+ // react-palm: @kepler.gl/actions, reducers, table, tasks each nest their own copy.+ // Both are singletons that break when loaded more than once.+ {+ name: 'dedupe-singletons',+ setup(build) {+ build.onResolve({filter: /^(styled-components|react-palm(\/|$)|react$|react-dom$)/}, async args => {+ if (args.pluginData?.deduped) return;+ const result = await build.resolve(args.path, {+ resolveDir: __dirname,+ kind: args.kind,+ pluginData: {deduped: true}+ });+ return result;+ });+ }+ },+ copyPlugin({+ resolveFrom: 'cwd',+ assets: {+ from: ['src/index.html'],+ to: ['dist']+ }+ })+ ]+};++function openURL(url) {+ const cmd = {+ darwin: ['open'],+ linux: ['xdg-open'],+ win32: ['cmd', '/c', 'start']+ };+ const command = cmd[process.platform];+ if (command) {+ spawn(command[0], [...command.slice(1), url]);+ }+}++(async () => {+ if (args.includes('--build')) {+ const result = await esbuild+ .build({+ ...config,++ minify: true,+ sourcemap: false,+ metafile: true+ })+ .catch(e => {+ console.error(e);+ process.exit(1);+ });+ fs.writeFileSync('dist/esbuild-metadata.json', JSON.stringify(result.metafile));+ }++ if (args.includes('--start')) {+ await esbuild+ .context({+ ...config,+ minify: false,+ sourcemap: true,+ banner: {+ js: `new EventSource('/esbuild').addEventListener('change', () => location.reload());`+ }+ })+ .then(async ctx => {+ await ctx.watch();+ await ctx.serve({+ servedir: 'dist',+ port,+ fallback: 'dist/index.html',+ onRequest: ({remoteAddress, method, path, status, timeInMS}) => {+ console.info(remoteAddress, status, `"${method} ${path}" [${timeInMS}ms]`);+ }+ });+ console.info(+ `kepler.gl clicked-feature example running at http://localhost:${port}, press Ctrl+C to stop`+ );+ openURL(`http://localhost:${port}`);+ })+ .catch(e => {+ console.error(e);+ process.exit(1);+ });+ }+})();diff --git a/examples/clicked-feature/package.json b/examples/clicked-feature/package.jsonnew file mode 100644index 000000000..aa38ef4ba--- /dev/null+++ b/examples/clicked-feature/package.json@@ -0,0 +1,48 @@+{+ "name": "kepler-clicked-feature",+ "version": "0.0.1",+ "license": "MIT",+ "scripts": {+ "bootstrap": "yarn install && yarn",+ "build": "node esbuild.config.mjs --build",+ "start": "node esbuild.config.mjs --start"+ },+ "dependencies": {+ "@deck.gl/mapbox": "9.3.1",+ "@kepler.gl/actions": "^3.3.0-alpha.6",+ "@kepler.gl/components": "^3.3.0-alpha.6",+ "@kepler.gl/processors": "^3.3.0-alpha.6",+ "@kepler.gl/reducers": "^3.3.0-alpha.6",+ "@kepler.gl/utils": "^3.3.0-alpha.6",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "react-redux": "^9.1.0",+ "redux": "^5.0.1"+ },+ "devDependencies": {+ "@types/node": "^20",+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0",+ "esbuild": "^0.25.0",+ "esbuild-plugin-copy": "^2.1.1",+ "typescript": "^5.5.0"+ },+ "resolutions": {+ "@deck.gl/aggregation-layers": "9.3.1",+ "@deck.gl/core": "9.3.1",+ "@deck.gl/extensions": "9.3.1",+ "@deck.gl/geo-layers": "9.3.1",+ "@deck.gl/layers": "9.3.1",+ "@deck.gl/mesh-layers": "9.3.1",+ "@deck.gl/mapbox": "9.3.1",+ "@deck.gl/react": "9.3.1",+ "@deck.gl/widgets": "9.3.1",+ "@luma.gl/constants": "9.3.2",+ "@luma.gl/core": "9.3.2",+ "@luma.gl/effects": "9.3.2",+ "@luma.gl/engine": "9.3.2",+ "@luma.gl/shadertools": "9.3.2",+ "@luma.gl/webgl": "9.3.2",+ "@luma.gl/webgpu": "9.3.2"+ }+}diff --git a/examples/clicked-feature/src/app.tsx b/examples/clicked-feature/src/app.tsxnew file mode 100644index 000000000..0d08ca3ed--- /dev/null+++ b/examples/clicked-feature/src/app.tsx@@ -0,0 +1,264 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import * as React from 'react';+import {useState, useEffect} from 'react';+import ReactDOM from 'react-dom/client';+import {Provider, useDispatch, useSelector} from 'react-redux';+import {applyMiddleware, combineReducers, compose, createStore} from 'redux';++import keplerGlReducer, {enhanceReduxMiddleware} from '@kepler.gl/reducers';+import KeplerGl from '@kepler.gl/components';+import {addDataToMap, wrapTo} from '@kepler.gl/actions';+import {processGeojson} from '@kepler.gl/processors';+import {initApplicationConfig} from '@kepler.gl/utils';++initApplicationConfig({enableAnnotations: false});++const MAP_ID = 'map';+const SIDEBAR_WIDTH = 300;++// Kepler instance state lives at state.keplerGl[id]. The `id` must match the+// KeplerGl `id` prop (and wrapTo) below.+type ClickedPickInfo = {+ picked?: boolean;+ object?: {properties?: Record<string, unknown>};+} | null;++type KeplerRootState = {+ keplerGl: {+ [id: string]: {+ visState: {+ clicked: ClickedPickInfo;+ };+ };+ };+};++const reducers = combineReducers({+ keplerGl: keplerGlReducer.initialState({+ mapStyle: {+ styleType: 'dark-matter'+ },+ uiState: {+ // Hide Kepler's own side panel so the host-app sidebar is the focus.+ readOnly: true,+ currentModal: null+ }+ })+});++const middlewares = enhanceReduxMiddleware([]);+const enhancers = applyMiddleware(...middlewares);+const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;+const store = createStore(reducers, {}, composeEnhancers(enhancers));++// Simple non-overlapping polygons so clicks are easy to target.+function rectangle(west: number, south: number, east: number, north: number) {+ return [+ [+ [west, south],+ [east, south],+ [east, north],+ [west, north],+ [west, south]+ ]+ ];+}++const neighborhoods = {+ type: 'FeatureCollection',+ features: [+ {+ type: 'Feature',+ properties: {shapeName: 'Mission', areaKm2: 3.9},+ geometry: {type: 'Polygon', coordinates: rectangle(-122.428, 37.748, -122.41, 37.765)}+ },+ {+ type: 'Feature',+ properties: {shapeName: 'SoMa', areaKm2: 2.6},+ geometry: {type: 'Polygon', coordinates: rectangle(-122.41, 37.765, -122.392, 37.782)}+ },+ {+ type: 'Feature',+ properties: {shapeName: 'Financial District', areaKm2: 1.2},+ geometry: {type: 'Polygon', coordinates: rectangle(-122.41, 37.782, -122.392, 37.798)}+ },+ {+ type: 'Feature',+ properties: {shapeName: 'Castro', areaKm2: 1.4},+ geometry: {type: 'Polygon', coordinates: rectangle(-122.444, 37.756, -122.428, 37.77)}+ }+ ]+};++const sampleData = {+ info: {+ label: 'Neighborhoods',+ id: 'neighborhoods'+ },+ data: processGeojson(neighborhoods)+};++const mapConfig = {+ version: 'v1',+ config: {+ visState: {+ layers: [+ {+ id: 'neighborhoods-layer',+ type: 'geojson',+ config: {+ dataId: 'neighborhoods',+ label: 'Neighborhoods',+ color: [18, 147, 154],+ columns: {geojson: '_geojson'},+ isVisible: true,+ visConfig: {+ opacity: 0.65,+ thickness: 1,+ strokeColor: [255, 255, 255],+ filled: true,+ stroked: true,+ enable3d: false,+ // GeoJSON picking (and therefore visState.clicked) requires this+ // plus interactionConfig.tooltip.enabled.+ allowHover: true+ }+ },+ visualChannels: {+ colorField: {name: 'shapeName', type: 'string'},+ colorScale: 'ordinal'+ }+ }+ ],+ interactionConfig: {+ tooltip: {+ fieldsToShow: {+ neighborhoods: [{name: 'shapeName'}, {name: 'areaKm2'}]+ },+ enabled: true+ }+ }+ },+ mapState: {+ latitude: 37.772,+ longitude: -122.418,+ zoom: 12.4,+ pitch: 0,+ bearing: 0+ },+ mapStyle: {+ styleType: 'dark-matter'+ }+ }+};++function useWindowSize() {+ const [size, setSize] = useState({width: window.innerWidth, height: window.innerHeight});+ useEffect(() => {+ const onResize = () => setSize({width: window.innerWidth, height: window.innerHeight});+ window.addEventListener('resize', onResize);+ return () => window.removeEventListener('resize', onResize);+ }, []);+ return size;+}++const sidebarStyle: React.CSSProperties = {+ width: SIDEBAR_WIDTH,+ height: '100%',+ padding: 16,+ overflow: 'auto',+ background: '#242730',+ color: '#f7f7f7',+ fontFamily: 'Helvetica, Arial, sans-serif',+ fontSize: 13,+ lineHeight: 1.45,+ flexShrink: 0+};++/**+ * Host-app sidebar that reads the last layer click from Kepler Redux state.+ * `clicked` is a deck.gl PickInfo. For GeoJSON, original feature properties+ * (including shapeName) are on `clicked.object.properties`.+ */+function ClickedFeatureSidebar() {+ const clicked = useSelector(+ (state: KeplerRootState) => state.keplerGl[MAP_ID]?.visState?.clicked+ );++ if (!clicked?.picked) {+ return (+ <aside style={sidebarStyle}>+ <h2 style={{margin: '0 0 8px', fontSize: 16}}>Clicked feature</h2>+ <p style={{margin: 0, color: '#c3c9d5'}}>+ Click a polygon on the map to show its <code>shapeName</code> here,+ outside Kepler.gl.+ </p>+ </aside>+ );+ }++ const properties = clicked.object?.properties ?? {};+ const shapeName = properties.shapeName;+ const extraEntries = Object.entries(properties).filter(+ ([key]) => key !== 'shapeName' && key !== 'index'+ );++ return (+ <aside style={sidebarStyle}>+ <h2 style={{margin: '0 0 8px', fontSize: 16}}>Clicked feature</h2>+ <p style={{margin: '0 0 16px', fontSize: 20, fontWeight: 600}}>+ {shapeName == null ? 'Untitled' : String(shapeName)}+ </p>+ {extraEntries.map(([key, value]) => (+ <div key={key} style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>+ <span style={{color: '#c3c9d5'}}>{key}</span>+ <span>{String(value)}</span>+ </div>+ ))}+ </aside>+ );+}++const App = () => {+ const dispatch = useDispatch();+ const {width, height} = useWindowSize();++ useEffect(() => {+ dispatch(+ wrapTo(+ MAP_ID,+ addDataToMap({+ datasets: sampleData,+ config: mapConfig,+ options: {centerMap: false}+ })+ )+ );+ }, [dispatch]);++ return (+ <div style={{display: 'flex', width: '100%', height: '100%'}}>+ <div style={{position: 'relative', flex: 1, minWidth: 0}}>+ <KeplerGl+ mapboxApiAccessToken="pk.xxx.yyy"+ id={MAP_ID}+ width={Math.max(width - SIDEBAR_WIDTH, 0)}+ height={height}+ />+ </div>+ <ClickedFeatureSidebar />+ </div>+ );+};++const Root = () => (+ <Provider store={store}>+ <App />+ </Provider>+);++const container = document.getElementById('root');+const root = ReactDOM.createRoot(container!);+root.render(<Root />);diff --git a/examples/clicked-feature/src/index.html b/examples/clicked-feature/src/index.htmlnew file mode 100644index 000000000..9a3bddf86--- /dev/null+++ b/examples/clicked-feature/src/index.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<html>+ <head>+ <title>Clicked Feature</title>+ <style>+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }+ #root { width: 100%; height: 100%; }+ </style>+ </head>+ <body>+ <div id="root" />+ <script src="./bundle.js"></script>+ </body>+</html>diff --git a/examples/clicked-feature/tsconfig.json b/examples/clicked-feature/tsconfig.jsonnew file mode 100644index 000000000..1035fe6da--- /dev/null+++ b/examples/clicked-feature/tsconfig.json@@ -0,0 +1,11 @@+{+ "compilerOptions": {+ "sourceMap": true,+ "module": "commonjs",+ "target": "es5",+ "jsx": "react",+ "esModuleInterop": true+ },+ "include": ["src"],+ "compileOnSave": false+}