Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: add map scale bar (#3596)
Igor Dykhtaee9aa8859225
diff --git a/src/components/package.json b/src/components/package.jsonindex 3a68cf16e..dda6aa131 100644--- a/src/components/package.json+++ b/src/components/package.json@@ -65,6 +65,7 @@"@mapbox/mapbox-sdk": "^0.15.3","@math.gl/web-mercator": "^4.1.0","@tippyjs/react": "^4.2.0",+ "@turf/distance": "^7.2.0","@turf/helpers": "^7.2.0","@turf/transform-translate": "^7.2.0","@types/classnames": "^2.3.1",diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex 8c21190f1..437624ae9 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -161,6 +161,7 @@ export {default as LazyTippy} from './map/lazy-tippy';export {default as LocalePanelFactory} from './map/locale-panel';export {default as MapControlFactory} from './map/map-control';export {default as MapNavigationControlFactory} from './map/map-navigation-control';+export {default as MapScaleFactory} from './map/map-scale';export {default as MapControlPanelFactory} from './map/map-control-panel';export {default as MapControlToolbarFactory} from './map/map-control-toolbar';export {default as MapControlTooltipFactory} from './map/map-control-tooltip';diff --git a/src/components/src/loading-indicator.tsx b/src/components/src/loading-indicator.tsxindex 056f1a223..02a05b9eb 100644--- a/src/components/src/loading-indicator.tsx+++ b/src/components/src/loading-indicator.tsx@@ -53,22 +53,26 @@ type LoadingIndicatorProps = {activeSidePanel?: boolean;sidePanelWidth?: number;hasAttributionLogos?: boolean;+ hasMapScale?: boolean;};/** Extra adjustment for the loading indicator when side panel is visible */const LEFT_POSITION_ADJUSTMENT = 3;+/** Height of the map scale bar, used to stack the loading indicator above it */+const MAP_SCALE_HEIGHT = 24;const LoadingIndicator: React.FC<LoadingIndicatorProps & {theme: any}> = ({isVisible,activeSidePanel,sidePanelWidth,hasAttributionLogos,+ hasMapScale,theme}) => {const left =(activeSidePanel ? (sidePanelWidth || 0) + LEFT_POSITION_ADJUSTMENT : 0) +theme.sidePanel.margin.left;- const bottomOffset = hasAttributionLogos ? 24 : 0;+ const bottomOffset = (hasAttributionLogos ? 24 : 0) + (hasMapScale ? MAP_SCALE_HEIGHT : 0);// Helper message to track number of tiles that are being loadedconst numRasterTilesInProgress = getNumRasterTilesBeingLoaded();diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex b40b3ecf3..51d2c2aa0 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -17,6 +17,7 @@ import {VisStateActions, MapStateActions, UIStateActions} from '@kepler.gl/actio// componentsimport MapPopoverFactory from './map/map-popover';import MapControlFactory from './map/map-control';+import MapScaleFactory from './map/map-scale';import {StyledMapContainer} from './common/styled-components';import {Attribution,@@ -179,6 +180,14 @@ const StyledDroppable = styled.div<StyledDroppableProps>`z-index: 1;`;+const StyledMapScaleContainer = styled.div<{$left: number; $bottomOffset: number}>`+ position: absolute;+ bottom: ${props => props.theme.sidePanel.margin.left + props.$bottomOffset}px;+ left: ${props => props.$left}px;+ z-index: 1;+ pointer-events: auto;+`;+export const isSplitSelector = props =>props.visState.splitMaps && props.visState.splitMaps.length > 1;@@ -196,7 +205,7 @@ export const Droppable = ({containerId}) => {// re-exported here to preserve the public import path (@kepler.gl/components).export {Attribution, AttributionLogos, renderBasemapAttribution, dedupeBasemapAttributions};-MapContainerFactory.deps = [MapPopoverFactory, MapControlFactory, EditorFactory];+MapContainerFactory.deps = [MapPopoverFactory, MapControlFactory, EditorFactory, MapScaleFactory];type MapboxStyle = string | object | undefined;type PropSelector<R> = Selector<MapContainerProps, R>;@@ -265,7 +274,8 @@ export interface MapContainerProps {export default function MapContainerFactory(MapPopover: ReturnType<typeof MapPopoverFactory>,MapControl: ReturnType<typeof MapControlFactory>,- Editor: ReturnType<typeof EditorFactory>+ Editor: ReturnType<typeof EditorFactory>,+ MapScale: ReturnType<typeof MapScaleFactory>): React.ComponentType<MapContainerProps> {class MapContainer extends Component<MapContainerProps> {displayName = 'MapContainer';@@ -1464,6 +1474,7 @@ export default function MapContainerFactory(activeSidePanel={Boolean(activeSidePanel)}sidePanelWidth={sidePanelWidth}hasAttributionLogos={attributionLogos.length > 0}+ hasMapScale={getApplicationConfig().enableMapScale}/>) : null}{this.props.primary ? (@@ -1490,6 +1501,18 @@ export default function MapContainerFactory(sidePanelWidth={sidePanelWidth}/>) : null}+ {!isExport && getApplicationConfig().enableMapScale ? (+ <StyledMapScaleContainer+ $left={+ primary && activeSidePanel+ ? (sidePanelWidth || 0) + (theme?.sidePanel?.margin?.left ?? 9)+ : theme?.sidePanel?.margin?.left ?? 9+ }+ $bottomOffset={primary && attributionLogos.length > 0 ? 24 : 0}+ >+ <MapScale mapState={mapState} mapIndex={index ?? 0} />+ </StyledMapScaleContainer>+ ) : null}</>);}diff --git a/src/components/src/map/map-scale.tsx b/src/components/src/map/map-scale.tsxnew file mode 100644index 000000000..3ee8cec21--- /dev/null+++ b/src/components/src/map/map-scale.tsx@@ -0,0 +1,182 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import distance from '@turf/distance';+import {range} from 'd3-array';+import React, {FC, useCallback, useContext, useState} from 'react';+import styled from 'styled-components';+import {WebMercatorViewport} from 'viewport-mercator-project';++import {MapViewStateContext, MapViewStateContextType} from '../map-view-state-context';+import {getViewportFromMapState, getApplicationConfig} from '@kepler.gl/utils';+import {MapState} from '@kepler.gl/types';++export type MapScaleProps = {+ mapState: MapState;+ mapIndex?: number;+};++type Unit = {+ label: string;+ meters: number;+};++const DISPLAY_UNITS: Record<'km' | 'miles', Unit[]> = {+ km: [+ {label: 'm', meters: 1},+ {label: 'km', meters: 1000}+ ],+ miles: [+ {label: 'ft', meters: 0.3048},+ {label: 'mi', meters: 1609.34}+ ]+};++// Pre-generated list of "round" numbers: 1, 2, 5, 10, 20, 50, 100, ...+const NICE_VALUES = range(15).flatMap(p => [1, 2, 5].map(n => n * Math.pow(10, p)));++function findLast<T>(array: T[], predicate: (item: T) => boolean): T | undefined {+ for (let i = array.length - 1; i >= 0; i--) {+ if (predicate(array[i])) {+ return array[i];+ }+ }+ return undefined;+}++const DISTANCE_PREFERENCE_KEY = 'keplergl_distancePreference';++function getStoredDistancePreference(): 'km' | 'miles' {+ try {+ const stored = window.localStorage.getItem(DISTANCE_PREFERENCE_KEY);+ if (stored === 'km' || stored === 'miles') return stored;+ } catch {+ // localStorage unavailable (e.g. SSR)+ }+ return 'km';+}++function setStoredDistancePreference(value: 'km' | 'miles'): void {+ try {+ window.localStorage.setItem(DISTANCE_PREFERENCE_KEY, value);+ } catch {+ // localStorage unavailable+ }+}++const StyledMapScale = styled.div`+ display: flex;+ flex-direction: row;+ cursor: pointer;+ padding: 0 1px 2px 1px;+ border-radius: 3px;+ border: 1px solid ${props => props.theme.borderColor};+ background-color: ${props => props.theme.sidePanelBg}cc;+ user-select: none;+ svg {+ text {+ fill: ${props => props.theme.textColorHl};+ font-size: 10px;+ }+ path {+ stroke: ${props => props.theme.textColorHl};+ }+ }+`;++interface ScaleProps {+ metersPerPixel: number;+ maxWidth?: number;+ height?: number;+ displayUnits?: 'km' | 'miles';+}++const Scale: FC<ScaleProps> = ({+ metersPerPixel,+ maxWidth = 150,+ height: h = 15,+ displayUnits = 'km'+}) => {+ const maxMetersContainer = maxWidth * metersPerPixel;+ const unit = findLast(+ DISPLAY_UNITS[displayUnits],+ u => u.meters * NICE_VALUES[0] <= maxMetersContainer+ );+ if (!unit) return null;++ const niceValue = findLast(NICE_VALUES, v => v * unit.meters <= maxMetersContainer);+ if (!niceValue) return null;++ const niceValuePixels = (niceValue * unit.meters) / metersPerPixel;+ const x1 = Math.round((maxWidth - niceValuePixels) / 2);+ const x2 = maxWidth - x1;+ const w = x2 - x1 + 1;+ const dx = (maxWidth - w) / 2;++ return (+ <svg width={w} height={h}>+ <g>+ <text textAnchor="middle" x={w / 2} y={h - 3}>+ {niceValue} {unit.label}+ </text>+ <path+ d={`M ${-dx + x1 + 0.5} ${h / 2}+ L ${-dx + x1 + 0.5} ${h}+ L ${-dx + x2 - 0.5} ${h}+ L ${-dx + x2 - 0.5} ${h / 2}`}+ fill="none"+ />+ </g>+ </svg>+ );+};++// Reference ruler width in pixels used to sample real-world distance+const RULER_SIZE = 100;++MapScaleFactory.deps = [];++export default function MapScaleFactory() {+ const MapScale: FC<MapScaleProps> = ({mapState, mapIndex = 0}) => {+ const {getInternalViewState} = useContext<MapViewStateContextType>(MapViewStateContext);+ const viewState = getInternalViewState(mapIndex);++ const [displayUnits, setDisplayUnits] = useState<'km' | 'miles'>(+ getStoredDistancePreference+ );++ const handleClick = useCallback(() => {+ setDisplayUnits(prev => {+ const next = prev === 'km' ? 'miles' : 'km';+ setStoredDistancePreference(next);+ return next;+ });+ }, []);++ if (!getApplicationConfig().enableMapScale) return null;++ const mergedState = {...mapState, ...viewState};+ const viewport = getViewportFromMapState(mergedState as MapState) as WebMercatorViewport;++ const cx = (mapState.width || 0) / 2;+ const cy = (mapState.height || 0) / 2;+ const p1 = viewport.unproject([cx - RULER_SIZE / 2, cy]);+ const p2 = viewport.unproject([cx + RULER_SIZE / 2, cy]);++ // unproject can return null in some edge cases (e.g. during globe projection)+ if (!p1 || !p2) return null;++ const metersPerPixel = distance(p1 as [number, number], p2 as [number, number], {units: 'meters'}) / RULER_SIZE;++ if (!isFinite(metersPerPixel) || metersPerPixel <= 0) return null;++ return (+ <StyledMapScale className="map-scale" onClick={handleClick}>+ <Scale metersPerPixel={metersPerPixel} displayUnits={displayUnits} />+ </StyledMapScale>+ );+ };++ MapScale.displayName = 'MapScale';+ return React.memo(MapScale);+}diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex 831da2939..f5c18ebaf 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -125,6 +125,9 @@ export type KeplerApplicationConfig = {/** Whether to show the map navigation control (zoom buttons and compass). Enabled by default. */enableMapNavigationControl?: boolean;+ /** Whether to show the map scale bar at the bottom-left of the map. Enabled by default. */+ enableMapScale?: boolean;+/** Whether to enable the swipe compare mode in split map view. Enabled by default. */enableSwipeMode?: boolean;@@ -241,6 +244,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {enableMapNavigationControl: true,+ enableMapScale: true,+enableSwipeMode: true,enableGlobeView: true,diff --git a/yarn.lock b/yarn.lockindex e6ed94d93..6311ddfe4 100644--- a/yarn.lock+++ b/yarn.lock@@ -5766,6 +5766,7 @@ __metadata:"@mapbox/mapbox-sdk": "npm:^0.15.3""@math.gl/web-mercator": "npm:^4.1.0""@tippyjs/react": "npm:^4.2.0"+ "@turf/distance": "npm:^7.2.0""@turf/helpers": "npm:^7.2.0""@turf/transform-translate": "npm:^7.2.0""@types/classnames": "npm:^2.3.1"