Skip to content

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

feat: centerMap - add optional padding (#3644)

Igor Dykhta525b54acdc8b
diff --git a/src/actions/src/actions.ts b/src/actions/src/actions.ts
index 01597b064..7695fc8b2 100644
--- a/src/actions/src/actions.ts
+++ b/src/actions/src/actions.ts
@@ -46,6 +46,8 @@ export type ActionHandlers<T extends {[k: string]: Handler}> = {
* @param {Object} data.options
* @param {boolean} data.options.centerMap `default: true` if `centerMap` is set to `true` kepler.gl will
* place the map view within the data points boundaries. `options.centerMap` will override `config.mapState` if passed in.
+ * @param {Number|Object} data.options.padding padding in pixels applied when `centerMap` is true so data is not hidden
+ * under the side panel or other UI. Can be a number or `{top, bottom, left, right}`.
* @param {boolean} data.options.readOnly `default: false` if `readOnly` is set to `true`
* the left setting panel will be hidden
* @param {boolean} data.options.keepExistingConfig whether to keep exiting map data and associated layer filter interaction config `default: false`.
@@ -94,6 +96,7 @@ export type ActionHandlers<T extends {[k: string]: Handler}> = {
* },
* options: {
* centerMap: true,
+ * padding: {left: 300, top: 24, right: 24, bottom: 24},
* readOnly: false,
* keepExistingConfig: false
* },
@@ -140,6 +143,8 @@ export type ReceiveMapConfigPayload = {
* @param {Object} options - ***optional** The Option object
* @param {boolean} options.centerMap `default: true` if `centerMap` is set to `true` kepler.gl will
* place the map view within the data points boundaries
+ * @param {Number|Object} options.padding padding in pixels applied when `centerMap` is true so data is not hidden
+ * under the side panel or other UI. Can be a number or `{top, bottom, left, right}`.
* @param {boolean} options.readOnly `default: false` if `readOnly` is set to `true`
* the left setting panel will be hidden
* @param {boolean} options.keepExistingConfig whether to keep exiting layer filter and interaction config `default: false`.
@@ -192,6 +197,7 @@ export const keplerGlInit: (options?: KeplerGlInitPayload) => {
export type ReplaceDataToMapOptions = {
centerMap?: boolean;
+ padding?: AddDataToMapOptions['padding'];
keepExistingConfig?: boolean;
autoCreateLayers?: boolean;
};
diff --git a/src/actions/src/map-state-actions.ts b/src/actions/src/map-state-actions.ts
index 64b7bc76b..b6238bb0a 100644
--- a/src/actions/src/map-state-actions.ts
+++ b/src/actions/src/map-state-actions.ts
@@ -3,7 +3,7 @@
import {createAction} from '@reduxjs/toolkit';
import {default as ActionTypes} from './action-types';
-import {Bounds, Merge, Viewport} from '@kepler.gl/types';
+import {Bounds, Merge, Viewport, ViewportPadding} from '@kepler.gl/types';
import {MapSplitMode, MapViewMode, GlobeConfig} from '@kepler.gl/constants';
export type TogglePerspectiveUpdaterAction = void;
@@ -21,21 +21,30 @@ export const togglePerspective: () => Merge<
{type: typeof ActionTypes.TOGGLE_PERSPECTIVE}
> = createAction(ActionTypes.TOGGLE_PERSPECTIVE);
-export type FitBoundsUpdaterAction = {payload: Bounds};
+export type FitBoundsUpdaterAction = {
+ payload: Bounds;
+ meta?: {padding?: ViewportPadding};
+};
/**
* Fit map viewport to bounds
* @memberof mapStateActions
* @param {Array<Number>} bounds as `[lngMin, latMin, lngMax, latMax]`
+ * @param {Number|Object} [padding] padding in pixels around the bounds. Can be a number or `{top, bottom, left, right}`.
* @public
* @example
* import {fitBounds} from '@kepler.gl/actions';
* this.props.dispatch(fitBounds([-122.23, 37.127, -122.11, 37.456]));
+ * this.props.dispatch(fitBounds([-122.23, 37.127, -122.11, 37.456], {left: 300}));
*/
export const fitBounds: (
- payload: Bounds
+ bounds: Bounds,
+ padding?: ViewportPadding
) => Merge<FitBoundsUpdaterAction, {type: typeof ActionTypes.FIT_BOUNDS}> = createAction(
ActionTypes.FIT_BOUNDS,
- (bounds: Bounds) => ({payload: bounds})
+ (bounds: Bounds, padding?: ViewportPadding) => ({
+ payload: bounds,
+ meta: {padding}
+ })
);
export type UpdateMapUpdaterAction = {payload: {viewport: Viewport; mapIndex?: number}};
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 1ca0e91ad..e9ac6dc79 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -8,6 +8,7 @@ import {Layer, LayerBaseConfig} from '@kepler.gl/layers';
import {KeplerTable} from '@kepler.gl/table';
import {
AddDataToMapPayload,
+ ViewportPadding,
ValueOf,
Merge,
PickInfo,
@@ -1045,6 +1046,7 @@ export function setColumnDisplayFormat(
export type AddDataToMapUpdaterOptions = {
centerMap?: boolean;
+ padding?: ViewportPadding;
readOnly?: boolean;
keepExistingConfig?: boolean;
};
@@ -1069,6 +1071,8 @@ export type UpdateVisDataUpdaterAction = {
* @param {object} options
* @param options.centerMap `default: true` if `centerMap` is set to `true` kepler.gl will
* place the map view within the data points boundaries
+ * @param options.padding padding in pixels applied when `centerMap` is true so data is not hidden
+ * under the side panel or other UI. Can be a number or `{top, bottom, left, right}`.
* @param options.readOnly `default: false` if `readOnly` is set to `true`
* the left setting panel will be hidden
* @param config this object will contain the full kepler.gl instance configuration {mapState, mapStyle, visState}
diff --git a/src/reducers/src/combined-updaters.ts b/src/reducers/src/combined-updaters.ts
index 35bde1363..bb9d48aac 100644
--- a/src/reducers/src/combined-updaters.ts
+++ b/src/reducers/src/combined-updaters.ts
@@ -121,7 +121,7 @@ export const defaultAddDataToMapOptions = {
* @param {Object} action.payload `{datasets, options, config}`
* @param action.payload.datasets - ***required** datasets can be a dataset or an array of datasets
* Each dataset object needs to have `info` and `data` property.
- * @param [action.payload.options] option object `{centerMap: true}`
+ * @param [action.payload.options] option object `{centerMap: true, padding: {left: 300}}`
* @param [action.payload.config] map config
* @param [action.payload.info] map info contains title and description
* @returns nextState
diff --git a/src/reducers/src/map-state-updaters.ts b/src/reducers/src/map-state-updaters.ts
index 486099424..3a5115182 100644
--- a/src/reducers/src/map-state-updaters.ts
+++ b/src/reducers/src/map-state-updaters.ts
@@ -180,7 +180,8 @@ export const fitBoundsUpdater = (
): MapState => {
const centerAndZoom = getCenterAndZoomFromBounds(action.payload, {
width: state.width,
- height: state.height
+ height: state.height,
+ padding: action.meta?.padding
});
if (!centerAndZoom) {
// bounds is invalid
@@ -398,7 +399,8 @@ export const receiveMapConfigUpdater = (
// center map will override mapState config
if (options.centerMap && bounds) {
mergedState = fitBoundsUpdater(mergedState, {
- payload: bounds
+ payload: bounds,
+ meta: {padding: options.padding}
});
}
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index ea729d228..d4875b523 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -3124,8 +3124,9 @@ function postMergeUpdater(mergedState: VisState, postMergerPayload: PostMergerPa
if (newLayers.length && (options || {}).centerMap) {
const bounds = findMapBounds(newLayers);
if (bounds) {
+ const padding = options?.padding;
const fitBoundsTask = ACTION_TASK_FIT_BOUNDS().map(() => {
- return fitMapBounds(bounds);
+ return fitMapBounds(bounds, padding);
});
updatedState = withTask(updatedState, fitBoundsTask);
}
diff --git a/src/types/actions.d.ts b/src/types/actions.d.ts
index 2f1a9de36..6747be981 100644
--- a/src/types/actions.d.ts
+++ b/src/types/actions.d.ts
@@ -3,6 +3,7 @@
import {SavedMap, ParsedConfig, SavedConfigV1, MinSavedConfigV1} from './schemas';
import type {LayerVisConfig} from './layers';
+import type {ViewportPadding} from './reducers';
/** EXPORT_FILE_TO_CLOUD */
export type MapData = {
@@ -66,6 +67,12 @@ export type ProtoDataset = {
export type AddDataToMapOptions = {
centerMap?: boolean;
+ /**
+ * Padding in pixels applied when `centerMap` is true.
+ * Use this so a few points are not hidden under the side panel or other UI.
+ * A number applies the same padding on all sides.
+ */
+ padding?: ViewportPadding;
readOnly?: boolean;
keepExistingConfig?: boolean;
autoCreateLayers?: boolean;
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index ceb3b5530..4544d8df2 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -74,6 +74,19 @@ export type MapState = {
export type Bounds = [number, number, number, number];
+/**
+ * Padding in pixels used when fitting the map viewport to bounds.
+ * A number applies the same padding on all sides.
+ */
+export type ViewportPadding =
+ | number
+ | {
+ top?: number;
+ bottom?: number;
+ left?: number;
+ right?: number;
+ };
+
export type RangeFieldDomain = {
domain: number[];
step: number;
diff --git a/src/utils/src/projection-utils.ts b/src/utils/src/projection-utils.ts
index 26833bd42..695fadf2b 100644
--- a/src/utils/src/projection-utils.ts
+++ b/src/utils/src/projection-utils.ts
@@ -6,6 +6,8 @@ import geoViewport from '@mapbox/geo-viewport';
import WebMercatorViewport from 'viewport-mercator-project';
import Console from 'global/console';
+import type {ViewportPadding} from '@kepler.gl/types';
+
export const MAPBOX_TILE_SIZE = 512;
function isLat(num) {
@@ -33,13 +35,74 @@ export function validateBounds(bounds) {
return null;
}
-export function getCenterAndZoomFromBounds(bounds, {width, height}) {
+function normalizeViewportPadding(padding?: ViewportPadding | null): {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+} | null {
+ if (padding == null) {
+ return null;
+ }
+ if (typeof padding === 'number') {
+ return padding > 0 ? {top: padding, bottom: padding, left: padding, right: padding} : null;
+ }
+ const normalized = {
+ top: padding.top || 0,
+ bottom: padding.bottom || 0,
+ left: padding.left || 0,
+ right: padding.right || 0
+ };
+ return normalized.top || normalized.bottom || normalized.left || normalized.right
+ ? normalized
+ : null;
+}
+
+export function getCenterAndZoomFromBounds(
+ bounds,
+ {
+ width,
+ height,
+ padding
+ }: {
+ width: number;
+ height: number;
+ padding?: ViewportPadding;
+ }
+) {
const validBounds = validateBounds(bounds);
if (!validBounds) {
Console.warn('invalid map bounds provided');
return null;
}
+ const normalizedPadding = normalizeViewportPadding(padding);
+ if (normalizedPadding) {
+ try {
+ const viewport = new WebMercatorViewport({width, height, zoom: 0}).fitBounds(
+ [
+ [validBounds[0], validBounds[1]],
+ [validBounds[2], validBounds[3]]
+ ],
+ {padding: normalizedPadding}
+ );
+ let zoom = viewport.zoom;
+ const center = [viewport.longitude, viewport.latitude];
+
+ // NOTE: this logic is used in deck.gl normalizeViewportProps
+ // This is required in order to prevent projection matrix mismatch between basemap and layers
+ const minZoom = Math.log2(height / MAPBOX_TILE_SIZE);
+ if (zoom <= minZoom) {
+ zoom = minZoom;
+ center[1] = 0;
+ }
+
+ return {zoom, center};
+ } catch (err) {
+ Console.warn('failed to fit map bounds with padding', err);
+ }
+ }
+
// viewport(bounds, dimensions, minzoom, maxzoom, tileSize, allowFloat)
let {zoom} = geoViewport.viewport(
bounds,
diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.js
index ece4c36f8..1f97a9951 100644
--- a/test/node/reducers/composer-state-test.js
+++ b/test/node/reducers/composer-state-test.js
@@ -137,6 +137,44 @@ test('#composerStateReducer - addDataToMapUpdater: mapState should be centered (
t.end();
});
+test('#composerStateReducer - addDataToMapUpdater: centerMap padding', t => {
+ const state = keplerGlReducer({}, registerEntry({id: 'test'})).test;
+ const datasets = {
+ data: mockRawData,
+ info: {
+ id: 'foo'
+ }
+ };
+
+ const fitMapAfterAdd = options => {
+ let nextState = addDataToMapUpdater(state, {
+ payload: {
+ datasets,
+ options
+ }
+ });
+ nextState.visState = applyExistingDatasetTasks(visStateReducer, nextState.visState);
+ const tasks = drainTasksForTesting();
+ nextState.mapState = mapStateReducer(nextState.mapState, succeedTaskWithValues(tasks[0], {}));
+ drainTasksForTesting();
+ return nextState;
+ };
+
+ const unpadded = fitMapAfterAdd({centerMap: true});
+ const padded = fitMapAfterAdd({centerMap: true, padding: {left: 300}});
+
+ t.ok(
+ padded.mapState.zoom < unpadded.mapState.zoom,
+ 'padding should zoom out relative to unpadded centerMap'
+ );
+ t.ok(
+ padded.mapState.longitude < unpadded.mapState.longitude,
+ 'left padding should pan west so points are not hidden under the side panel'
+ );
+
+ t.end();
+});
+
test('#composerStateReducer - addDataToMapUpdater: uiState', t => {
// init kepler.gl root and instance
const state = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;
diff --git a/test/node/reducers/map-state-test.js b/test/node/reducers/map-state-test.js
index 1b8501b13..35b1decf4 100644
--- a/test/node/reducers/map-state-test.js
+++ b/test/node/reducers/map-state-test.js
@@ -370,6 +370,31 @@ test('#mapStateReducer -> FIT_BOUNDS', t => {
t.end();
});
+test('#mapStateReducer -> FIT_BOUNDS with padding', t => {
+ const bounds = [5.668343999999995, 45.111511000000014, 5.852471999999996, 45.26800200000002];
+ const mapUpdate = {
+ width: 640,
+ height: 480
+ };
+
+ const stateWidthMapDimension = reducer(undefined, updateMap(mapUpdate, 0));
+ const unpadded = reducer(stateWidthMapDimension, fitBounds(bounds));
+ const paddedLeft = reducer(stateWidthMapDimension, fitBounds(bounds, {left: 300}));
+ const paddedUniform = reducer(stateWidthMapDimension, fitBounds(bounds, 80));
+
+ t.ok(
+ paddedLeft.zoom < unpadded.zoom,
+ 'left padding should zoom out so bounds fit in the remaining viewport'
+ );
+ t.ok(
+ paddedLeft.longitude < unpadded.longitude,
+ 'left padding should pan west so bounds sit in the visible area to the right of the side panel'
+ );
+ t.ok(paddedUniform.zoom < unpadded.zoom, 'uniform padding should zoom out');
+
+ t.end();
+});
+
test('#mapStateReducer -> FIT_BOUNDS - split map and unsynced viewports', t => {
// default input and output in @mapbox/geo-viewport
// https://github.com/mapbox/geo-viewport