Kepler.gl

A powerful open source geospatial analysis tool for large-scale data sets.

README

version build stars MIT License Fossa

kepler.gl | Website | Demo App | Docs


[Kepler.gl](http://kepler.gl)

[Kepler.gl Demo](http://kepler.gl/#/demo)

[Kepler.gl][web] is a data-agnostic, high-performance web-based application for visual exploration of large-scale geolocation data sets. Built on top of Mapbox GL and deck.gl, kepler.gl can render millions of points representing thousands of trips and perform spatial aggregations on the fly.

Kepler.gl is also a React component that uses Redux to manage its state and data flow. It can be embedded into other React-Redux applications and is highly customizable. For information on how to embed kepler.gl in your app take a look at this step-by-step [tutorial][vis-academy] on vis.academy.

Links


- [Website][web]
- [Demo][demo-app]
- [Examples][examples]
- [Get Started][get-started]
- [App User Guide][user-guide]
- [Jupyter Widget User Guide][user-guide-jupyter]
- [Tutorial][vis-academy]
- [Stack Overflow][stack]
- [Contribution Guidelines][contributing]
- [Api Reference][api-reference]
- [Roadmap][roadmap]

Env


Use Node 10.15.0 or above, older node versions have not been supported/ tested.
For best results, use nvmnvm install.

Install kepler.gl


Install node (> 10.15.0), yarn, and project dependencies

  1. ```sh
  2. npm install --save kepler.gl
  3. // or
  4. yarn add kepler.gl
  5. ```

kepler.gl is built upon [mapbox][mapbox]. You will need a [Mapbox Access Token][mapbox-token] to use it.

If you don't use a module bundler, it's also fine. Kepler.gl npm package includes precompiled production UMD builds in the umd folder.
You can add the script tag to your html file as it follows:

  1. ``` html
  2. <script src="https://unpkg.com/kepler.gl/umd/keplergl.min.js" />
  3. ```

or if you would like, you can load a specific version

  1. ``` html
  2. <script src="https://unpkg.com/kepler.gl@0.2.2/umd/keplergl.min.js" />
  3. ```

Develop kepler.gl


Take a look at the [development guide][developers] to develop kepler.gl locally.

Basic Usage


Here are the basic steps to import kepler.gl into your app. You also take a look at the examples folder. Each example in the folder can be installed and run locally.

1. Mount reducer


Kepler.gl uses Redux to manage its internal state, along with [react-palm][react-palm] middleware to handle side effects.

You need to add taskMiddleware of react-palm to your store too. We are actively working on a solution where
react-palm will not be required, however it is still a very lightweight side effects management tool that is easier to test than react-thunk.

  1. ``` js
  2. import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
  3. import keplerGlReducer from 'kepler.gl/reducers';
  4. import {enhanceReduxMiddleware} from 'kepler.gl/middleware';

  5. const initialState = {};
  6. const reducers = combineReducers({
  7.   // <-- mount kepler.gl reducer in your app
  8.   keplerGl: keplerGlReducer,

  9.   // Your other reducers here
  10.   app: appReducer
  11. });

  12. // using createStore
  13. export default createStore(
  14.   reducer,
  15.   initialState,
  16.   applyMiddleware(
  17.     enhanceReduxMiddleware([
  18.       /* Add other middlewares here */
  19.     ])
  20.   )
  21. );
  22. ```

Or if use enhancer:

  1. ``` js
  2. // using enhancers
  3. const initialState = {};
  4. const middlewares = enhanceReduxMiddleware([
  5.   // Add other middlewares here
  6. ]);
  7. const enhancers = [applyMiddleware(...middlewares)];

  8. export default createStore(reducer, initialState, compose(...enhancers));
  9. ```

If you mount kepler.gl reducer in another address instead of keplerGl, or the kepler.gl reducer is not
mounted at root of your state, you will need to specify the path to it when you mount the component
with the getState prop.

Read more about [Reducers][reducers].

2. Mount Component


  1. ``` js
  2. import KeplerGl from 'kepler.gl';

  3. const Map = props => (
  4.   <KeplerGl
  5.     id="foo"
  6.     width={width}
  7.     mapboxApiAccessToken={token}
  8.     height={height}
  9.   />
  10. );
  11. ```

Props


id (String, required)

- Default: map

The id of this KeplerGl instance. id is required if you have multiple
KeplerGl instances in your app. It defines the prop name of the KeplerGl state that is
stored in the KeplerGl reducer. For example, the state of the KeplerGl component with id foo is
stored in state.keplerGl.foo.

In case you create multiple kepler.gl instances using the same id, the kepler.gl state defined by the entry will be
overridden by the latest instance and reset to a blank state.

mapboxApiAccessToken (String, required*)

- Default: undefined


By default, kepler.gl uses mapbox-gl.js to render its base maps. You can create a free account at [mapbox][mapbox] and create a token at [www.mapbox.com/account/access-tokens][mapbox-token].

If you replaced kepler.gl default map styles with your own, and they are not Mapbox styles. mapboxApiAccessToken will not be reuiqred.

Read more about [Custom Map Styles][custom-map-styles].

getState (Function, optional)

- Default: state => state.keplerGl

The path to the root keplerGl state in your reducer.

width (Number, optional)

- Default: 800

Width of the KeplerGl UI.

height (Number, optional)

- Default: 800

appName (String, optional)

- Default: Kepler.Gl

App name displayed in side panel header

version (String, optional)

- Default: v1.0

version displayed in side panel header

onSaveMap (Function, optional)

- Default: undefined

Action called when click Save Map Url in side panel header.

onViewStateChange (Function, optional)

- Default: undefined
- Parameter: viewState - An updated view state object containing parameters such as longitude, latitude, zoom etc

Action triggered when map viewport is updated.

getMapboxRef(mapbox, index) (Function, optional)

- Default: undefined

Function called when KeplerGL adds or removes a MapContainer component having an inner Mapbox map.

The mapbox argument is an [InteractiveMap](https://uber.github.io/react-map-gl/#/Documentation/api-reference/interactive-map) when added or null when removed.

The index argument is 0 for a single map or 1 for an additional map (since KeplerGL supports an optional split map view).

actions (Object, optional)

- Default: {}

Actions creators to replace default kepler.gl action creator. Only use custom action when you want to modify action payload.

mint (Boolean, optional)

- Default: true

Whether to load a fresh empty state when component is mounted. when parse mint: true kepler.gl component will always load a fresh state when re-mount the same component, state inside this component will be destroyed once its unmounted.
By Parsing mint: false kepler.gl will keep the component state in the store even when it is unmounted, and use it as initial state when re-mounted again. This is useful when mounting kepler.gl in a modal, and keep the same map when re-open.

Read more about [Components][components].

theme (Object | String, optional)

- default: null

One of "dark", "light" or "base"
You can pass theme name or object used to customize Kepler.gl style. Kepler.gl provide an 'light' theme besides the default 'dark' theme. When pass in a theme object Kepler.gl will use the value passed as input to override values from theme.

Read more about [Custom Theme][custom-theme]

mapboxApiUrl (String, optional)


- Default: https://api.mapbox.com

If you are using your own mapbox tile server, you can pass in your own tile server api url.

mapStylesReplaceDefault (Boolean, optional)


- Default: false

kepler.gl provide 4 map styles to choose from. Pass true if you want to supply your own mapStyles. See Below.

mapStyles (Array, optional)


- Default: []

You can supply additional map styles to be displayed in map style selection panel. By default, additional map styles will be added to default map styles. If passmapStylesReplaceDefault: true, they will replace the default ones. kepler.gl will attempt to group layers of your style based on its id naming convention and use it to allow toggle visibility of base map layers. Supply your ownlayerGroups to override default for more accurate layer grouping.

Each mapStyles should has the following properties:

- id (String, required) unique string that should not be one of these reserved dark light muted. muted_night
- label (String, required) name to be displayed in map style selection panel
- url (String, required) mapbox style url or a url pointing to the map style json object written in Mapbox GL Style Spec.
- icon (String, optional) image icon of the style, it can be a url, or an image data url
- layerGroups (Array, optional)

  1. ``` js
  2. const mapStyles = [
  3.   {
  4.     id: 'my_dark_map',
  5.     label: 'Dark Streets 9',
  6.     url: 'mapbox://styles/mapbox/dark-v9',
  7.     icon: `${apiHost}/styles/v1/mapbox/dark-v9/static/-122.3391,37.7922,9.19,0,0/400x300?access_token=${accessToken}&logo=false&attribution=false`,
  8.     layerGroups: [
  9.       {
  10.         slug: 'label',
  11.         filter: ({id}) => id.match(/(?=(label|place-|poi-))/),
  12.         defaultVisibility: true
  13.       },
  14.       {
  15.         // adding this will keep the 3d building option
  16.         slug: '3d building',
  17.         filter: () => false,
  18.         defaultVisibility: false
  19.       }
  20.     ]
  21.   }
  22. ];
  23. ```

Read more about [Custom Map Styles][custom-map-styles].

initialUiState (object, optional)


- Default: undefined

Intial UI State applied to uiState reducer, value will be shallow merged with default [INITIAL_UI_STATE](https://docs.kepler.gl/docs/api-reference/reducers/ui-state#initial_ui_state)

localeMessages (object, optional)


- Default: undefined Modify default translation or add new translation

Read more about [Localization][localization].

3. Dispatch custom actions to keplerGl reducer.


One advantage of using the reducer over React component state to handle keplerGl state is the flexibility
to customize its behavior. If you only have one KeplerGl instance in your app or never intend to dispatch actions to KeplerGl from outside the component itself,
you don’t need to worry about forwarding dispatch and can move on to the next section. But life is full of customizations, and we want to make yours as enjoyable as possible.

There are multiple ways to dispatch actions to a specific KeplerGl instance.

- In the root reducer, with reducer updaters.

Each action is mapped to a reducer updater in kepler.gl. You can import the reducer updater corresponding to a specific action, and call it with the previous state and action payload to get the updated state.
e.g. updateVisDataUpdater is the updater for ActionTypes.UPDATE_VIS_DATA (take a look at each reducer reducers/vis-state.js for action to updater mapping).
Here is an example how you can listen to an app action QUERY_SUCCESS and call updateVisDataUpdater to load data into Kepler.Gl.

  1. ``` js
  2. import keplerGlReducer, {visStateUpdaters} from 'kepler.gl/reducers';

  3. // Root Reducer
  4. const reducers = combineReducers({
  5.   keplerGl: keplerGlReducer,

  6.   app: appReducer
  7. });

  8. const composedReducer = (state, action) => {
  9.   switch (action.type) {
  10.     case 'QUERY_SUCCESS':
  11.       return {
  12.         ...state,
  13.         keplerGl: {
  14.           ...state.keplerGl,

  15.           // 'map' is the id of the keplerGl instance
  16.           map: {
  17.             ...state.keplerGl.map,
  18.             visState: visStateUpdaters.updateVisDataUpdater(
  19.               state.keplerGl.map.visState,
  20.               {datasets: action.payload}
  21.             )
  22.           }
  23.         }
  24.       };
  25.   }
  26.   return reducers(state, action);
  27. };

  28. export default composedReducer;
  29. ```

Read more about [using updaters to modify kepler.gl state][using-updaters]

- Using redux connect

You can add a dispatch function to your component that dispatches actions to a specific keplerGl component,
using connect.

  1. ``` js
  2. // component
  3. import KeplerGl from 'kepler.gl';

  4. // action and forward dispatcher
  5. import {toggleFullScreen, forwardTo} from 'kepler.gl/actions';
  6. import {connect} from 'react-redux';

  7. const MapContainer = props => (
  8.   <div>
  9.     <button onClick={() => props.keplerGlDispatch(toggleFullScreen())}/>
  10.     <KeplerGl
  11.       id="foo"
  12.     />
  13.   </div>
  14. )

  15. const mapStateToProps = state => state
  16. const mapDispatchToProps = (dispatch, props) => ({
  17. dispatch,
  18. keplerGlDispatch: forwardTo(foo, dispatch)
  19. });

  20. export default connect(
  21. mapStateToProps,
  22. mapDispatchToProps
  23. )(MapContainer);
  24. ```

- Wrap action payload

You can also simply wrap an action into a forward action with the wrapTo helper

  1. ``` js
  2. // component
  3. import KeplerGl from 'kepler.gl';

  4. // action and forward dispatcher
  5. import {toggleFullScreen, wrapTo} from 'kepler.gl/actions';

  6. // create a function to wrapper action payload to 'foo'
  7. const wrapToMap = wrapTo('foo');
  8. const MapContainer = ({dispatch}) => (
  9.   <div>
  10.     <button onClick={() => dispatch(wrapToMap(toggleFullScreen())} />
  11.     <KeplerGl
  12.       id="foo"
  13.     />
  14.   </div>
  15. );

  16. ```

Read more about [forward dispatching actions][forward-actions]

4. Customize style.


Kepler.gl implements css styling using Styled-Components. By using said framework Kepler.gl offers the ability to customize its style/theme using the following approaches:

- Passing a Theme prop
- Styled-Components ThemeProvider

The available properties to customize are listed here theme.


Passing a Theme prop.


You can customize Kepler.gl theme by passing a theme props to Kepler.gl react component as it follows:

  1. ``` js
  2. const white = '#ffffff';
  3. const customTheme = {
  4.   sidePanelBg: white,
  5.   titleTextColor: '#000000',
  6.   sidePanelHeaderBg: '#f7f7F7',
  7.   subtextColorActive: '#2473bd'
  8. };

  9. return (
  10.   <KeplerGl
  11.     mapboxApiAccessToken={MAPBOX_TOKEN}
  12.     id="map"
  13.     width={800}
  14.     height={800}
  15.     theme={customTheme}
  16.   />
  17. );
  18. ```

As you can see the customTheme object defines certain properties which will override Kepler.gl default style rules.

Styled-Components Theme Provider.


In order to customize Kepler.gl theme using ThemeProvider you can simply wrap Kepler.gl using ThemeProvider as it follows:

  1. ``` js
  2. import {ThemeProvider} from 'styled-components';

  3. const white = '#ffffff';
  4. const customTheme = {
  5.   sidePanelBg: white,
  6.   titleTextColor: '#000000',
  7.   sidePanelHeaderBg: '#f7f7F7',
  8.   subtextColorActive: '#2473bd'
  9. };

  10. return (
  11.   <ThemeProvider theme={customTheme}>
  12.     <KeplerGl
  13.       mapboxApiAccessToken={MAPBOX_TOKEN}
  14.       id="map"
  15.       width={800}
  16.       height={800}
  17.     />
  18.   </ThemeProvider>
  19. );
  20. ```

5. Render Custom UI components.


Everyone wants the flexibility to render custom kepler.gl components. Kepler.gl has a dependency injection system that allow you to inject
components to KeplerGl replacing existing ones. All you need to do is to create a component factory for the one you want to replace, import the original component factory
and call injectComponents at the root component of your app where KeplerGl is mounted.
Take a look at examples/demo-app/src/app.js and see how it renders a custom side panel header in kepler.gl

  1. ``` js
  2. import {injectComponents, PanelHeaderFactory} from 'kepler.gl/components';

  3. // define custom header
  4. const CustomHeader = () => <div>My kepler.gl app</div>;
  5. const myCustomHeaderFactory = () => CustomHeader;

  6. // Inject custom header into Kepler.gl, replacing default
  7. const KeplerGl = injectComponents([
  8.   [PanelHeaderFactory, myCustomHeaderFactory]
  9. ]);

  10. // render KeplerGl, it will render your custom header instead of the default
  11. const MapContainer = () => (
  12.   <div>
  13.     <KeplerGl id="foo" />
  14.   </div>
  15. );
  16. ```

Using withState helper to add reducer state and actions to customized component as additional props.

  1. ``` js
  2. import {
  3.   withState,
  4.   injectComponents,
  5.   PanelHeaderFactory
  6. } from 'kepler.gl/components';
  7. import {visStateLens} from 'kepler.gl/reducers';

  8. // custom action wrap to mounted instance
  9. const addTodo = text =>
  10.   wrapTo('map', {
  11.     type: 'ADD_TODO',
  12.     text
  13.   });

  14. // define custom header
  15. const CustomHeader = ({visState, addTodo}) => (
  16.   <div onClick={() => addTodo('hello')}>{`${
  17.     Object.keys(visState.datasets).length
  18.   } dataset loaded`}</div>
  19. );

  20. // now CustomHeader will receive `visState` and `addTodo` as additional props.
  21. const myCustomHeaderFactory = () =>
  22.   withState(
  23.     // keplerGl state lenses
  24.     [visStateLens],
  25.     // customMapStateToProps
  26.     headerStateToProps,
  27.     // actions
  28.     {addTodo}
  29.   )(CustomHeader);
  30. ```

Read more about [replacing UI component][replace-ui-component]

6. How to add data to map


To interact with a kepler.gl instance and add new data to it, you can dispatch the addDataToMap action from anywhere inside your app. It adds a dataset or multiple datasets to a kepler.gl instance and updates the full configuration (mapState, mapStyle, visState).

Parameters


- data [Object][40] *\required
  - datasets ([Array][41]<[Object][40]> | [Object][40]) *\required datasets can be a dataset or an array of datasets
    Each dataset object needs to have info and data property.
    - datasets.info [Object][40] \-info of a dataset
      - datasets.info.id [string][42] id of this dataset. If config is defined, id should matches the dataId in config.
      - datasets.info.label [string][42] A display name of this dataset
    - datasets.data [Object][40] *\required The data object, in a tabular format with 2 properties fields and rows
      - datasets.data.fields [Array][41]<[Object][40]> *\required Array of fields,
        - datasets.data.fields.name [string][42] *\required Name of the field,
      - datasets.data.rows [Array][41]<[Array][41]> *\required Array of rows, in a tabular format with fields and rows
  - options [Object][40]

    - options.centerMap [boolean][43] default: true if centerMap is set to true kepler.gl will place the map view within the data points boundaries
    - options.readOnly [boolean][43] default: false if readOnly is set to true
      the left setting panel will be hidden
    - options.keepExistingConfig [boolean][43] default: false whether to keep exiting map config, including layers, filters and splitMaps.

- config [Object][40] this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}

Kepler.gl provides an easy API KeplerGlSchema.getConfigToSave to generate a json blob of the current kepler instance configuration.

Examples


  1. ``` js
  2. // app.js
  3. import {addDataToMap} from 'kepler.gl/actions';

  4. const sampleTripData = {
  5.   fields: [
  6.     {name: 'tpep_pickup_datetime', format: 'YYYY-M-D H:m:s', type: 'timestamp'},
  7.     {name: 'pickup_longitude', format: '', type: 'real'},
  8.     {name: 'pickup_latitude', format: '', type: 'real'}
  9.   ],
  10.   rows: [
  11.     ['2015-01-15 19:05:39 +00:00', -73.99389648, 40.75011063],
  12.     ['2015-01-15 19:05:39 +00:00', -73.97642517, 40.73981094],
  13.     ['2015-01-15 19:05:40 +00:00', -73.96870422, 40.75424576]
  14.   ]
  15. };

  16. const sampleConfig = {
  17.   visState: {
  18.     filters: [
  19.       {
  20.         id: 'me',
  21.         dataId: 'test_trip_data',
  22.         name: 'tpep_pickup_datetime',
  23.         type: 'timeRange',
  24.         view: 'enlarged'
  25.       }
  26.     ]
  27.   }
  28. };

  29. this.props.dispatch(
  30.   addDataToMap({
  31.     datasets: {
  32.       info: {
  33.         label: 'Sample Taxi Trips in New York City',
  34.         id: 'test_trip_data'
  35.       },
  36.       data: sampleTripData
  37.     },
  38.     option: {
  39.       centerMap: true,
  40.       readOnly: false
  41.     },
  42.     config: sampleConfig
  43.   })
  44. );
  45. ```

Read more about addDataToMap and [Saving and loading maps with schema manager][saving-loading-w-schema].

[contributing]: contributing/README.md
[demo-app]: http://kepler.gl/#/demo
[github]: https://github.com/keplergl/kepler.gl
[github-pr]: https://help.github.com/articles/creating-a-pull-request/
[mapbox]: https://www.mapbox.com
[mapbox-token]: https://www.mapbox.com/help/define-access-token/
[developers]: contributing/DEVELOPERS.md
[examples]: https://github.com/keplergl/kepler.gl/tree/master/examples
[react-palm]: https://github.com/btford/react-palm
[roadmap]: https://github.com/keplergl/kepler.gl/wiki/Kepler.gl-2019-Roadmap
[stack]: https://stackoverflow.com/questions/tagged/kepler.gl
[web]: http://www.kepler.gl/
[vis-academy]: http://vis.academy/#/kepler.gl/
[user-guide]: docs/user-guides/README.md
[user-guide-jupyter]: docs/keplergl-jupyter/README.md
[api-reference]: docs/api-reference/README.md
[get-started]: ./docs/api-reference/get-started.md
[reducers]: docs/api-reference/reducers/README.md
[components]: docs/api-reference/components/README.md
[custom-theme]: docs/api-reference/custom-theme/README.md
[reducers]: docs/api-reference/reducers/README.md
[actions-updaters]: docs/api-reference/actions/README.md
[processors]: docs/api-reference/processors/README.md
[schemas]: docs/api-reference/schemas/README.md
[using-updaters]: ./docs/api-reference/advanced-usages/using-updaters.md
[custom-map-styles]: ./docs/api-reference/advanced-usages/custom-map-styles.md
[forward-actions]: ./docs/api-reference/advanced-usages/forward-actions.md
[replace-ui-component]: ./docs/api-reference/advanced-usages/replace-ui-component.md
[saving-loading-w-schema]: ./docs/api-reference/advanced-usages/saving-loading-w-schema.md
[localization]: ./docs/api-reference/localization/README.md
[40]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object
[41]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array
[42]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String
[43]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean
[44]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number
[45]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/function