Skip to content

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

[Enhancement] Enable Export High Resolution (2x) Images (#37)

Shan Hec10c0b846c04
diff --git a/examples/demo-app/package.json b/examples/demo-app/package.json
index ab305db4f..7684ec3ca 100644
--- a/examples/demo-app/package.json
+++ b/examples/demo-app/package.json
@@ -8,6 +8,7 @@
"d3-request": "^1.0.6",
"global": "^4.3.0",
"kepler.gl": "github:uber/kepler.gl",
+ "lodash.debounce": "^4.0.8",
"react": "^15.3.1",
"react-dom": "^15.6.1",
"react-palm": "^0.8.1",
diff --git a/examples/demo-app/src/app.js b/examples/demo-app/src/app.js
index 55b097aee..69ee34491 100644
--- a/examples/demo-app/src/app.js
+++ b/examples/demo-app/src/app.js
@@ -36,6 +36,7 @@ const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line
/* eslint-disable no-unused-vars */
import sampleTripData from './data/sample-trip-data';
import sampleGeojson from './data/sample-geojson.json';
+import sampleIconCsv, {config as savedMapConfig} from './data/sample-icon-csv';
import {updateVisData, addDataToMap} from 'kepler.gl/actions';
import Processors from 'kepler.gl/processors';
/* eslint-enable no-unused-vars */
@@ -51,12 +52,10 @@ class App extends Component {
const {token} = this.props.location.query;
window.gtag('set', {token});
- window.gtag('config', 'UA-64694404-19',
- {
- user_id: token,
- custom_map: {dimension1: 'token'}
- }
- );
+ window.gtag('config', 'UA-64694404-19', {
+ user_id: token,
+ custom_map: {dimension1: 'token'}
+ });
window.gtag('send', 'pageview', {token});
}
@@ -66,54 +65,68 @@ class App extends Component {
/**
* ENABLE THE FOLLOWING CODE TO PRE-POLUATE KEPLER.GL INSTANCE
*/
+
// load trip based data with config
- // this.props.dispatch(
- // updateVisData(
- // // datasets
- // {
- // info: {
- // label: 'Sample Taxi Trips in New York City',
- // id: 'test_trip_data'
- // },
- // data: sampleTripData
- // },
- // // option
- // {
- // centerMap: true,
- // readOnly: false
- // },
- // // config
- // {
- // filters: [
- // {
- // id: 'me',
- // dataId: 'test_trip_data',
- // name: 'tpep_pickup_datetime',
- // type: 'timeRange',
- // enlarged: true
- // }
- // ]
- // })
- // );
-
- // load icon data
- // this.props.dispatch(
- // updateVisData({
- // info: {
- // label: 'Icon Data',
- // id: 'test_icon_data'
- // },
- // data: Processor.processCsvData(sampleIconCsv)
- // })
- // );
+ // this._loadSampleData();
+ }
+
+ _loadSampleData() {
+ this.props.dispatch(
+ updateVisData(
+ // datasets
+ {
+ info: {
+ label: 'Sample Taxi Trips in New York City',
+ id: 'test_trip_data'
+ },
+ data: sampleTripData
+ },
+ // option
+ {
+ centerMap: true,
+ readOnly: false
+ },
+ // config
+ {
+ filters: [
+ {
+ id: 'me',
+ dataId: 'test_trip_data',
+ name: 'tpep_pickup_datetime',
+ type: 'timeRange',
+ enlarged: true
+ }
+ ]
+ }
+ )
+ );
+
+ // load icon data and config and process csv file
+ this.props.dispatch(
+ addDataToMap({
+ datasets: [
+ {
+ info: {
+ label: 'Icon Data',
+ id: 'test_icon_data'
+ },
+ data: Processors.processCsvData(sampleIconCsv)
+ }
+ ],
+ options: {
+ centerMap: false
+ },
+ config: savedMapConfig
+ })
+ );
// load geojson
- // this.props.dispatch(
- // updateVisData({
- // info: {label: 'SF Zip Geo'},
- // data: Processors.processGeojson(sampleGeojson)
- // })
- // );
+ this.props.dispatch(
+ updateVisData({
+ info: {label: 'SF Zip Geo'},
+ data: Processors.processGeojson(sampleGeojson)
+ })
+ );
}
render() {
diff --git a/examples/demo-app/src/data/sample-icon-csv.js b/examples/demo-app/src/data/sample-icon-csv.js
index 5ff070621..e7b43f7f0 100644
--- a/examples/demo-app/src/data/sample-icon-csv.js
+++ b/examples/demo-app/src/data/sample-icon-csv.js
@@ -180,4 +180,109 @@ export default `time,event_lat,event_lng,icon,icon-bk,annotation-severity,annota
2016-06-28 20:03:24,37.789154,-121.873825,,up-arrow-thin,3,Period of dangerous driving 10:32pm-10:34pm
2016-06-28 20:01:29,37.38603,-122.400986,,up-arrow,5,"Braking at 10:32pm, -0.3g"
2016-06-28 20:04:58,37.776512,-122.46835,,upload,4,"10:33pm,37.3490528616667,-121.972682895794,accel,3,""Acceleration at 10:33pm, +0.2g"""
-2016-06-28 20:02:13,37.764816,-122.04143,,wrench,2,"Aborted lane change, 10:34pm"`;
\ No newline at end of file
+2016-06-28 20:02:13,37.764816,-122.04143,,wrench,2,"Aborted lane change, 10:34pm"`;
+
+export const config = {
+ version: 'v1',
+ config: {
+ visState: {
+ filters: [],
+ layers: [
+ {
+ id: 'xbbp4of',
+ type: 'hexagon',
+ config: {
+ dataId: 'test_icon_data',
+ label: 'new layer',
+ color: [221, 178, 124],
+ columns: {
+ lat: 'event_lat',
+ lng: 'event_lng'
+ },
+ isVisible: true,
+ visConfig: {
+ opacity: 0.8,
+ worldUnitSize: 0.5,
+ resolution: 8,
+ colorRange: {
+ name: 'Global Warming',
+ type: 'sequential',
+ category: 'Uber',
+ colors: [
+ '#5A1846',
+ '#900C3F',
+ '#C70039',
+ '#E3611C',
+ '#F1920E',
+ '#FFC300'
+ ]
+ },
+ coverage: 1,
+ sizeRange: [0, 500],
+ percentile: [0, 100],
+ elevationPercentile: [0, 100],
+ elevationScale: 5,
+ 'hi-precision': false,
+ colorAggregation: 'average',
+ sizeAggregation: 'average',
+ enable3d: true
+ }
+ },
+ visualChannels: {
+ colorField: {
+ name: 'annotation-severity',
+ type: 'integer'
+ },
+ colorScale: 'quantile',
+ sizeField: null,
+ sizeScale: 'linear'
+ }
+ }
+ ],
+ interactionConfig: {
+ tooltip: {
+ fieldsToShow: {
+ test_icon_data: [
+ 'time',
+ 'icon',
+ 'icon-bk',
+ 'annotation-severity',
+ 'annotation-html'
+ ],
+ '6b69fg6ca': ['OBJECTID', 'ZIP_CODE', 'ID']
+ },
+ enabled: true
+ },
+ brush: {
+ size: 0.5,
+ enabled: false
+ }
+ },
+ layerBlending: 'normal',
+ splitMaps: []
+ },
+ mapState: {
+ bearing: 24,
+ dragRotate: true,
+ latitude: 37.77189215118738,
+ longitude: -122.42436896812978,
+ pitch: 50,
+ zoom: 12.132280694715416,
+ isSplit: false
+ },
+ mapStyle: {
+ styleType: 'dark',
+ topLayerGroups: {
+ label: true
+ },
+ visibleLayerGroups: {
+ label: true,
+ road: true,
+ border: false,
+ building: true,
+ water: true,
+ land: true
+ }
+ }
+ }
+};
diff --git a/package.json b/package.json
index b8df067f7..e8030f015 100644
--- a/package.json
+++ b/package.json
@@ -76,6 +76,7 @@
"global": "^4.3.0",
"keymirror": "^0.1.1",
"lodash.clonedeep": "^4.0.1",
+ "lodash.debounce": "^4.0.8",
"lodash.flattendeep": "^4.2.0",
"lodash.memoize": "^4.1.2",
"lodash.pick": "^4.4.0",
diff --git a/src/components/common/icons/files.js b/src/components/common/icons/files.js
new file mode 100644
index 000000000..a71e5addf
--- /dev/null
+++ b/src/components/common/icons/files.js
@@ -0,0 +1,22 @@
+import PropTypes from 'prop-types';
+import React from 'react';
+import Base from './base';
+
+export default class Files extends React.Component {
+ static propTypes = {
+ /** Set the height of the icon, ex. '16px' */
+ height: PropTypes.string
+ };
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'data-ex-icons-minus'
+ };
+
+ render() {
+ return (
+ <Base viewBox="0 0 64 64" {...this.props}>
+ <path d="M48.015 58h-32a8 8 0 0 1-8-8V26h48v24a8 8 0 0 1-8 8zm-2-44h-28a6 6 0 0 0-6 6v2h40v-2a6 6 0 0 0-6-6zm-2 26v-6h-4v4h-16v-4h-4v6a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2zm-4-34h-16a4 4 0 0 0-4 4h24a4 4 0 0 0-4-4z" />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/common/icons/index.js b/src/components/common/icons/index.js
index 71fcd3ef7..dff5f6c80 100644
--- a/src/components/common/icons/index.js
+++ b/src/components/common/icons/index.js
@@ -35,6 +35,7 @@ export {default as Expand} from './expand';
export {default as EyeSeen} from './eye-seen';
export {default as EyeUnseen} from './eye-unseen';
export {default as File} from './file';
+export {default as Files} from './files';
export {default as FileType} from './file-type';
export {default as FilterFunnel} from './filter-funnel';
export {default as Histogram} from './histogram';
@@ -45,6 +46,7 @@ export {default as LineChart} from './line-chart';
export {default as Minus} from './minus';
export {default as Messages} from './messages';
export {default as Pause} from './pause';
+export {default as Picture} from './picture';
export {default as Pin} from './pin';
export {default as Play} from './play';
export {default as Reduce} from './reduce';
diff --git a/src/components/common/icons/picture.js b/src/components/common/icons/picture.js
new file mode 100644
index 000000000..ce09d975c
--- /dev/null
+++ b/src/components/common/icons/picture.js
@@ -0,0 +1,43 @@
+// Copyright (c) 2018 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import PropTypes from 'prop-types';
+import React from 'react';
+import Base from './base';
+
+export default class Picture extends React.Component {
+ static propTypes = {
+ /** Set the height of the icon, ex. '16px' */
+ height: PropTypes.string
+ };
+
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'data-ex-icons-minus'
+ };
+
+ render() {
+ return (
+ <Base viewBox="0 0 64 64" {...this.props}>
+ <path d="M55 8H9a1 1 0 0 0-1 1v46a1 1 0 0 0 1 1h46a1 1 0 0 0 1-1V9a1 1 0 0 0-1-1zm-3 36H12V12h40v32zM40.508 25.75l8.217 11.05c.98 1.319.047 3.2-1.587 3.2H16.987c-1.863 0-2.698-2.356-1.257-3.547l6.012-4.966a1.97 1.97 0 0 1 2.513 0l3.859 3.187a1.973 1.973 0 0 0 2.843-.347l6.378-8.578a1.973 1.973 0 0 1 3.173 0zM26 21a4 4 0 1 1-8 0 4 4 0 0 1 8 0z" />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/common/item-selector/item-selector.js b/src/components/common/item-selector/item-selector.js
index 01754e922..2d3fb903a 100644
--- a/src/components/common/item-selector/item-selector.js
+++ b/src/components/common/item-selector/item-selector.js
@@ -94,6 +94,7 @@ class ItemSelector extends Component {
selectedItems: PropTypes.oneOfType([
PropTypes.array,
PropTypes.string,
+ PropTypes.number,
PropTypes.bool,
PropTypes.object
]),
diff --git a/src/components/common/logo.js b/src/components/common/logo.js
index e4b3f3788..4812ba3f3 100644
--- a/src/components/common/logo.js
+++ b/src/components/common/logo.js
@@ -74,7 +74,7 @@ const KeplerGlLogo = ({appName, version}) => (
</LogoSvgWrapper>
<LogoTitle className="logo__title">
<LogoName className="logo__name">{appName}</LogoName>
- <LogoVersion className="logo__version">{version}</LogoVersion>
+ {version ? <LogoVersion className="logo__version">{version}</LogoVersion> : null}
</LogoTitle>
</LogoWrapper>
);
diff --git a/src/components/map-container.js b/src/components/map-container.js
index 47e24203f..8ab5d2e76 100644
--- a/src/components/map-container.js
+++ b/src/components/map-container.js
@@ -71,6 +71,7 @@ export default function MapContainerFactory(MapPopover, MapControl) {
mapStateActions: PropTypes.object.isRequired,
// optional
+ isExport: PropTypes.bool,
clicked: PropTypes.object,
hoverInfo: PropTypes.object,
mapLayers: PropTypes.object,
@@ -79,6 +80,10 @@ export default function MapContainerFactory(MapPopover, MapControl) {
onMapRender: PropTypes.func
};
+ static defaultProps = {
+ MapComponent: MapboxGLMap
+ };
+
constructor(props) {
super(props);
this.state = {
@@ -413,7 +418,7 @@ export default function MapContainerFactory(MapPopover, MapControl) {
return <div/>;
}
- const {mapLayers, layers, datasets, index, mapboxApiAccessToken,
+ const {mapLayers, layers, datasets, mapboxApiAccessToken,
mapControls, toggleMapControl} = this.props;
const mapProps = {
@@ -426,22 +431,23 @@ export default function MapContainerFactory(MapPopover, MapControl) {
return (
<StyledMapContainer style={MAP_STYLE.container} onMouseMove={this._onMouseMove}>
<MapControl
- index={index}
datasets={datasets}
dragRotate={mapState.dragRotate}
isSplit={mapState.isSplit}
+ isExport={this.props.isExport}
layers={layers}
mapIndex={this.props.index}
mapLayers={mapLayers}
mapControls={mapControls}
+ scale={mapState.scale || 1}
+ top={0}
onTogglePerspective={mapStateActions.togglePerspective}
onToggleSplitMap={mapStateActions.toggleSplitMap}
onMapToggleLayer={this._handleMapToggleLayer}
onToggleFullScreen={mapStateActions.toggleFullScreen}
onToggleMapControl={toggleMapControl}
- top={0}
/>
- <MapboxGLMap
+ <this.props.MapComponent
{...mapProps}
key="bottom"
ref="mapbox"
@@ -450,10 +456,10 @@ export default function MapContainerFactory(MapPopover, MapControl) {
>
{this._renderOverlay()}
{this._renderMapboxOverlays()}
- </MapboxGLMap>
+ </this.props.MapComponent>
{mapStyle.topMapStyle && (
<div style={MAP_STYLE.top}>
- <MapboxGLMap
+ <this.props.MapComponent
{...mapProps}
key="top"
mapStyle={mapStyle.topMapStyle}
diff --git a/src/components/map/map-control.js b/src/components/map/map-control.js
index 5ddf66583..fd8aae171 100644
--- a/src/components/map/map-control.js
+++ b/src/components/map/map-control.js
@@ -25,6 +25,7 @@ import styled from 'styled-components';
import {Tooltip, IconRoundSmall} from 'components/common/styled-components';
import MapLayerSelector from 'components/common/map-layer-selector';
+import KeplerGlLogo from 'components/common/logo';
import MapLegend from './map-legend';
import {
Close,
@@ -162,14 +163,22 @@ const layerSelector = (layers, mapLayers) => {
export class MapControl extends Component {
static propTypes = {
+ datasets: PropTypes.object.isRequired,
dragRotate: PropTypes.bool.isRequired,
isSplit: PropTypes.bool.isRequired,
+ layers: PropTypes.arrayOf(PropTypes.object),
+ mapIndex: PropTypes.number.isRequired,
mapControls: PropTypes.object.isRequired,
onToggleFullScreen: PropTypes.func.isRequired,
onTogglePerspective: PropTypes.func.isRequired,
onToggleSplitMap: PropTypes.func.isRequired,
onToggleMapControl: PropTypes.func.isRequired,
- top: PropTypes.number.isRequired
+ onMapToggleLayer: PropTypes.func.isRequired,
+ top: PropTypes.number.isRequired,
+
+ // optional
+ scale: PropTypes.number,
+ mapLayers: PropTypes.object
};
static defaultProps = {
@@ -196,43 +205,49 @@ export class MapControl extends Component {
const {
dragRotate,
isSplit,
+ isExport,
mapIndex,
mapControls,
onTogglePerspective,
onToggleSplitMap,
onMapToggleLayer,
- onToggleMapControl
+ onToggleMapControl,
+ scale
} = this.props;
- const {visibleLayers = {}, mapLegend = {}, toggle3d = {}, splitMap = {}} = mapControls;
+ const {
+ visibleLayers = {},
+ mapLegend = {},
+ toggle3d = {},
+ splitMap = {}
+ } = mapControls;
return (
<StyledMapControl className="map-control">
{/* Split Map */}
- {splitMap.show ? <ActionPanel key={0}>
- <StyledMapControlButton
- active={isSplit}
- onClick={e => {
- e.preventDefault();
- onToggleSplitMap(isSplit ? mapIndex : undefined);
- }}
- key={`split-${isSplit}`}
- className="map-control-button split-map"
- data-tip
- data-for="action-toggle"
- >
- {isSplit ?
- <Delete height="18px" /> :
- <Split height="18px" />
- }
- <MapLegendTooltip
- id="action-toggle"
- message={
- isSplit ? 'Close current panel' : 'Switch to dual map view'
- }
- />
- </StyledMapControlButton>
- </ActionPanel> : null}
+ {splitMap.show ? (
+ <ActionPanel key={0}>
+ <StyledMapControlButton
+ active={isSplit}
+ onClick={e => {
+ e.preventDefault();
+ onToggleSplitMap(isSplit ? mapIndex : undefined);
+ }}
+ key={`split-${isSplit}`}
+ className="map-control-button split-map"
+ data-tip
+ data-for="action-toggle"
+ >
+ {isSplit ? <Delete height="18px" /> : <Split height="18px" />}
+ <MapLegendTooltip
+ id="action-toggle"
+ message={
+ isSplit ? 'Close current panel' : 'Switch to dual map view'
+ }
+ />
+ </StyledMapControlButton>
+ </ActionPanel>
+ ) : null}
{/* Map Layers */}
{isSplit && visibleLayers.show ? (
@@ -247,52 +262,69 @@ export class MapControl extends Component {
) : null}
{/* 3D Map */}
- {toggle3d.show ? <ActionPanel key={2}>
- <StyledMapControlButton
- onClick={e => {
- e.preventDefault();
- onTogglePerspective();
- }}
- active={dragRotate}
- data-tip
- data-for="action-3d"
- >
- <Cube3d height="22px" />
- {/* No icon since we are injecting through css .threeD-map class*/}
- <MapLegendTooltip
- id="action-3d"
- message={dragRotate ? 'Disable 3D Map' : '3D Map'}
- />
- </StyledMapControlButton>
- </ActionPanel> : null}
+ {toggle3d.show ? (
+ <ActionPanel key={2}>
+ <StyledMapControlButton
+ onClick={e => {
+ e.preventDefault();
+ onTogglePerspective();
+ }}
+ active={dragRotate}
+ data-tip
+ data-for="action-3d"
+ >
+ <Cube3d height="22px" />
+ {/* No icon since we are injecting through css .threeD-map class*/}
+ <MapLegendTooltip
+ id="action-3d"
+ message={dragRotate ? 'Disable 3D Map' : '3D Map'}
+ />
+ </StyledMapControlButton>
+ </ActionPanel>
+ ) : null}
{/* Map Legend */}
- {mapLegend.show ? <ActionPanel key={3}>
- <MapLegendPanel
- items={items}
- onMapToggleLayer={onMapToggleLayer}
- isActive={mapLegend.active}
- toggleMenuPanel={() => onToggleMapControl('mapLegend')}
- />
- </ActionPanel> : null}
+ {mapLegend.show ? (
+ <ActionPanel key={3}>
+ <MapLegendPanel
+ items={items}
+ scale={scale}
+ isExport={isExport}
+ onMapToggleLayer={onMapToggleLayer}
+ isActive={mapLegend.active}
+ toggleMenuPanel={() => onToggleMapControl('mapLegend')}
+ />
+ </ActionPanel>
+ ) : null}
</StyledMapControl>
);
}
}
-const MapControlPanel = ({children, header, onClick}) => (
- <StyledMapControlPanel>
+const MapControlPanel = ({children, header, onClick, scale = 1, isExport}) => (
+ <StyledMapControlPanel
+ style={{
+ transform: `scale(${scale}) translate(calc(-${25 * (scale - 1)}% - ${10 *
+ scale}px), calc(${25 * (scale - 1)}% + ${10 * scale}px))`
+ }}
+ >
<StyledMapControlPanelHeader style={{position: 'relative'}}>
- <span style={{verticalAlign: 'middle'}}>{header}</span>
- <IconRoundSmall>
- <Close height="16px" onClick={onClick} />
- </IconRoundSmall>
+ {isExport ? (
+ <KeplerGlLogo version={false} />
+ ) : (
+ <span style={{verticalAlign: 'middle'}}>{header}</span>
+ )}
+ {isExport ? null : (
+ <IconRoundSmall>
+ <Close height="16px" onClick={onClick} />
+ </IconRoundSmall>
+ )}
</StyledMapControlPanelHeader>
<StyledMapControlPanelContent>{children}</StyledMapControlPanelContent>
</StyledMapControlPanel>
);
-const MapLegendPanel = ({items, isActive, toggleMenuPanel}) => (
+const MapLegendPanel = ({items, isActive, scale, toggleMenuPanel, isExport}) =>
!isActive ? (
<StyledMapControlButton
key={2}
@@ -301,7 +333,7 @@ const MapLegendPanel = ({items, isActive, toggleMenuPanel}) => (
className="map-control-button show-legend"
onClick={e => {
e.preventDefault();
- toggleMenuPanel()
+ toggleMenuPanel();
}}
>
<Legend height="22px" />
@@ -309,17 +341,23 @@ const MapLegendPanel = ({items, isActive, toggleMenuPanel}) => (
</StyledMapControlButton>
) : (
<MapControlPanel
+ scale={scale}
header={'Layer Legend'}
onClick={toggleMenuPanel}
+ isExport={isExport}
>
<MapLegend
layers={items.filter(item => item.isVisible).map(item => item.layer)}
/>
</MapControlPanel>
- )
-);
+ );
-const LayerSelectorPanel = ({items, onMapToggleLayer, isActive, toggleMenuPanel}) => (
+const LayerSelectorPanel = ({
+ items,
+ onMapToggleLayer,
+ isActive,
+ toggleMenuPanel
+}) =>
!isActive ? (
<StyledMapControlButton
key={1}
@@ -331,21 +369,17 @@ const LayerSelectorPanel = ({items, onMapToggleLayer, isActive, toggleMenuPanel}
data-tip
data-for="toggle-layer"
>
- <Layers height="22px"/>
+ <Layers height="22px" />
<MapLegendTooltip
id="toggle-layer"
message={isActive ? 'Hide layer panel' : 'Show layer panel'}
/>
</StyledMapControlButton>
) : (
- <MapControlPanel
- header="Visible layers"
- onClick={toggleMenuPanel}
- >
+ <MapControlPanel header="Visible layers" onClick={toggleMenuPanel}>
<MapLayerSelector layers={items} onMapToggleLayer={onMapToggleLayer} />
</MapControlPanel>
- )
-);
+ );
const ActionPanel = ({children}) => (
<StyledMapControlAction>{children}</StyledMapControlAction>
@@ -357,5 +391,6 @@ const MapLegendTooltip = ({id, message}) => (
</Tooltip>
);
-const MapControlFactory = () => MapControl;
+const MapControlFactory = () => MapControl;
+
export default MapControlFactory;
diff --git a/src/components/modal-container.js b/src/components/modal-container.js
index 1b29a3cdb..97c853810 100644
--- a/src/components/modal-container.js
+++ b/src/components/modal-container.js
@@ -22,13 +22,12 @@ import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {css} from 'styled-components';
import {findDOMNode} from 'react-dom';
-import {Blob, URL} from 'global/window';
-import document from 'global/document';
+import {Blob} from 'global/window';
import ModalDialog from './common/modal';
import {formatCsv} from 'processors/data-processor';
import KeplerGlSchema from 'schemas';
-
+import {downloadFile, dataURItoBlob} from 'utils/export-image-utils';
// modals
import DeleteDatasetModalFactory from './modals/delete-data-modal';
import IconInfoModalFactory from './modals/icon-info-modal';
@@ -121,27 +120,16 @@ export default function ModalContainerFactory(
_onExportImage = () => {
const {exporting, imageDataUri} = this.props.uiState.exportImage;
if (!exporting && imageDataUri) {
- this._downloadWithLink(imageDataUri, DEFAULT_EXPORT_IMAGE_NAME)
+ const file = dataURItoBlob(imageDataUri);
+ downloadFile(file, DEFAULT_EXPORT_IMAGE_NAME);
}
this.props.uiStateActions.cleanupExportImage();
this._closeModal();
};
- _downloadWithLink(href, filename) {
- const link = document.createElement('a');
- link.setAttribute('href', href);
- link.setAttribute('download', filename);
-
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- }
-
_downloadFile(data, type, filename) {
const fileBlob = new Blob([data], {type});
- const url = URL.createObjectURL(fileBlob);
- this._downloadWithLink(url, filename);
- URL.revokeObjectURL(url);
+ downloadFile(fileBlob, filename);
}
_onExportData = () => {
@@ -286,7 +274,8 @@ export default function ModalContainerFactory(
onConfirm: this._onExportImage,
confirmButton: {
large: true,
- children: 'Export'
+ disabled: exporting,
+ children: 'Download'
}
};
break;
diff --git a/src/components/modals/export-image-modal.js b/src/components/modals/export-image-modal.js
index 10778d629..e71b4a05a 100644
--- a/src/components/modals/export-image-modal.js
+++ b/src/components/modals/export-image-modal.js
@@ -165,7 +165,7 @@ class ExportImageModal extends Component {
</div>
<div className="image-option-section">
<div className="image-option-section-title">Resolution</div>
- For print choose 2x (available soon). For digital use choose 1x.
+ High resolution is better for prints.
<div className="button-list">
{RESOLUTION_OPTIONS.map(op =>
<Button
diff --git a/src/components/plot-container.js b/src/components/plot-container.js
index f6f0d185e..46fc2c60c 100644
--- a/src/components/plot-container.js
+++ b/src/components/plot-container.js
@@ -21,12 +21,15 @@
// libraries
import React, {Component} from 'react';
import PropTypes from 'prop-types';
+import {createSelector} from 'reselect';
import styled from 'styled-components';
-import throttle from 'lodash.throttle';
+import {StaticMap} from 'react-map-gl';
+import debounce from 'lodash.debounce';
+import window from 'global/window';
import MapContainerFactory from './map-container';
import {calculateExportImageSize, convertToPng} from 'utils/export-image-utils';
-
+import {scaleMapStyleByResolution} from 'utils/map-style-utils/mapbox-gl-style-editor';
const propTypes = {
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
@@ -39,7 +42,7 @@ PlotContainerFactory.deps = [MapContainerFactory];
const StyledPlotContainer = styled.div`
.mapboxgl-ctrl-bottom-left,
.mapboxgl-ctrl-bottom-right {
- display: none
+ display: none;
}
`;
@@ -47,21 +50,41 @@ export default function PlotContainerFactory(MapContainer) {
class PlotContainer extends Component {
constructor(props) {
super(props);
- this._onMapRender = throttle(this._onMapRender, 500);
+ this._onMapRender = debounce(this._onMapRender, 500);
+ }
+
+ componentWillMount() {
+ this.props.startExportingImage();
}
componentWillReceiveProps(newProps) {
- // re-fetch the new screenshot only when ratio or resolution changes
- if (
- this.props.exportImageSetting.ratio !== newProps.exportImageSetting.ratio ||
- this.props.exportImageSetting.resolution !== newProps.exportImageSetting.resolution ||
- this.props.exportImageSetting.legend !== newProps.exportImageSetting.legend
- ) {
+ // re-fetch the new screenshot only when ratio legend or resolution changes
+ const checks = ['ratio', 'resolution', 'legend'];
+ const shouldRetrieveScreenshot = checks.some(
+ item =>
+ this.props.exportImageSetting[item] !==
+ newProps.exportImageSetting[item]
+ );
+ if (shouldRetrieveScreenshot) {
this._retrieveNewScreenshot();
}
}
- _onMapRender = (map) => {
+ mapStyleSelector = props => props.mapFields.mapStyle;
+ resolutionSelector = props => props.exportImageSetting.resolution;
+ scaledMapStyleSelector = createSelector(
+ this.mapStyleSelector,
+ this.resolutionSelector,
+ (mapStyle, resolution) => ({
+ bottomMapStyle: scaleMapStyleByResolution(
+ mapStyle.bottomMapStyle,
+ resolution
+ ),
+ topMapStyle: scaleMapStyleByResolution(mapStyle.topMapStyle, resolution)
+ })
+ );
+
+ _onMapRender = map => {
if (map.isStyleLoaded()) {
this._retrieveNewScreenshot();
}
@@ -69,10 +92,16 @@ export default function PlotContainerFactory(MapContainer) {
_retrieveNewScreenshot = () => {
if (this.plottingAreaRef) {
+ // setting windowDevicePixelRatio to 1
+ // so that large mapbox base map will load in full
+ const savedDevicePixelRatio = window.devicePixelRatio;
+ window.devicePixelRatio = 1;
+
this.props.startExportingImage();
- convertToPng(this.plottingAreaRef).then(
- dataUri => this.props.setExportImageDataUri({dataUri})
- );
+ convertToPng(this.plottingAreaRef).then(dataUri => {
+ this.props.setExportImageDataUri({dataUri});
+ window.devicePixelRatio = savedDevicePixelRatio;
+ });
}
};
@@ -80,22 +109,21 @@ export default function PlotContainerFactory(MapContainer) {
const {width, height, exportImageSetting, mapFields} = this.props;
const {ratio, resolution, legend} = exportImageSetting;
const exportImageSize = calculateExportImageSize({
- width, height, ratio, resolution
+ width,
+ height,
+ ratio,
+ resolution
});
- // TODO: should override the map style according to the resolution
- const mapboxStyle = mapFields.mapStyle;
-
- // figure out how to turn on legend through mapProps
const mapProps = {
...mapFields,
- mapboxStyle,
+ mapStyle: this.scaledMapStyleSelector(this.props),
+
+ // override viewport based on export settings
mapState: {
...mapFields.mapState,
- // zoom: mapFields.mapState.zoom + Math.log2(exportRatio),
- zoom: mapFields.mapState.zoom,
- width: exportImageSize.width,
- height: exportImageSize.height
+ ...exportImageSize,
+ zoom: mapFields.mapState.zoom + exportImageSize.zoomOffset
},
mapControls: {
// override map legend visibility
@@ -104,16 +132,17 @@ export default function PlotContainerFactory(MapContainer) {
active: true
}
},
- mapStateActions: {
- ...mapFields.mapStateActions,
- updateMap: () => {}
- }
+ MapComponent: StaticMap
};
return (
- <StyledPlotContainer style={{position: 'absolute', top: -9999, left: -9999}}>
+ <StyledPlotContainer
+ style={{position: 'absolute', top: -9999, left: -9999}}
+ >
<div
- ref={element => {this.plottingAreaRef = element}}
+ ref={element => {
+ this.plottingAreaRef = element;
+ }}
style={{
width: exportImageSize.width,
height: exportImageSize.height
@@ -122,6 +151,7 @@ export default function PlotContainerFactory(MapContainer) {
<MapContainer
index={0}
onMapRender={this._onMapRender}
+ isExport
{...mapProps}
/>
</div>
diff --git a/src/components/side-panel/panel-header.js b/src/components/side-panel/panel-header.js
index 00eafebcc..b0833fa54 100644
--- a/src/components/side-panel/panel-header.js
+++ b/src/components/side-panel/panel-header.js
@@ -23,7 +23,7 @@ import styled from 'styled-components';
import PropTypes from 'prop-types';
import {Tooltip} from 'components/common/styled-components';
import KeplerGlLogo from 'components/common/logo';
-import {Save, Layers, Share} from 'components/common/icons';
+import {Save, Files, Share, Picture} from 'components/common/icons';
import PanelDropdown from 'components/side-panel/panel-dropdown';
const StyledPanelHeader = styled.div.attrs({
@@ -153,7 +153,7 @@ export const SaveExportDropdown = ({
onClose();
onExportImage();
}}>
- <Layers height="16px" />
+ <Picture height="16px" />
<div className="save-export-dropdown__title">Export Image</div>
</div>
@@ -162,7 +162,7 @@ export const SaveExportDropdown = ({
onClose();
onExportData();
}}>
- <Layers height="16px" />
+ <Files height="16px" />
<div className="save-export-dropdown__title">Export Data</div>
</div>
diff --git a/src/constants/default-settings.js b/src/constants/default-settings.js
index e87eb9478..78b04abbf 100644
--- a/src/constants/default-settings.js
+++ b/src/constants/default-settings.js
@@ -476,12 +476,22 @@ export const RESOLUTION_OPTIONS = [{
id: RESOLUTIONS.ONE_X,
label: '1x',
available: true,
- getSize: (screenW, screenH) => ({width: screenW, height: screenH})
+ scale: 1,
+ zoomOffset: Math.log2(1),
+ getSize: (screenW, screenH) => ({
+ width: screenW,
+ height: screenH
+ })
}, {
id: RESOLUTIONS.TWO_X,
label: '2x',
- available: false,
- getSize: (screenW, screenH) => ({width: screenW * 2, height: screenH * 2})
+ available: true,
+ scale: 2,
+ zoomOffset: Math.log2(2),
+ getSize: (screenW, screenH) => ({
+ width: screenW * 2,
+ height: screenH * 2
+ })
}];
export const DEFAULT_EXPORT_IMAGE_NAME = 'kepler-gl.png';
diff --git a/src/layers/base-layer.js b/src/layers/base-layer.js
index b013dbfc7..24b259c05 100644
--- a/src/layers/base-layer.js
+++ b/src/layers/base-layer.js
@@ -332,12 +332,26 @@ export default class Layer {
};
}
- getZoomFactor(zoom) {
- return Math.pow(2, Math.max(14 - zoom, 0));
+ /**
+ * Calculate a radius zoom multiplier to render points, so they are visible in all zoom level
+ * @param mapState
+ * @param mapState.zoom - actual zoom
+ * @param mapState.zoomOffset - zoomOffset when render in the plot container for export image
+ * @returns {number}
+ */
+ getZoomFactor({zoom, zoomOffset = 0}) {
+ return Math.pow(2, Math.max(14 - zoom + zoomOffset, 0));
}
- getElevationZoomFactor(zoom) {
- return Math.pow(2, Math.max(8 - zoom, 0));
+ /**
+ * Calculate a elevation zoom multiplier to render points, so they are visible in all zoom level
+ * @param mapState
+ * @param mapState.zoom - actual zoom
+ * @param mapState.zoomOffset - zoomOffset when render in the plot container for export image
+ * @returns {number}
+ */
+ getElevationZoomFactor({zoom, zoomOffset = 0}) {
+ return Math.pow(2, Math.max(8 - zoom + zoomOffset, 0));
}
formatLayerData(data, allData, filteredIndex) {
@@ -712,7 +726,7 @@ export default class Layer {
);
}
- getRadiusScaleByZoom(zoom, fixedRadius) {
+ getRadiusScaleByZoom(mapState, fixedRadius) {
const radiusChannel = Object.values(this.visualChannels).find(
vc => vc.property === 'radius'
);
@@ -730,7 +744,7 @@ export default class Layer {
return fixed
? 1
- : (this.config[field] ? 1 : radius) * this.getZoomFactor(zoom);
+ : (this.config[field] ? 1 : radius) * this.getZoomFactor(mapState);
}
shouldCalculateLayerData(props) {
diff --git a/src/layers/geojson-layer/geojson-layer.js b/src/layers/geojson-layer/geojson-layer.js
index 647d2c011..6d43ccb38 100644
--- a/src/layers/geojson-layer/geojson-layer.js
+++ b/src/layers/geojson-layer/geojson-layer.js
@@ -323,8 +323,8 @@ export default class GeoJsonLayer extends Layer {
interactionConfig
}) {
const {fp64, lightSettings, fixedRadius} = this.meta;
- const radiusScale = this.getRadiusScaleByZoom(mapState.zoom, fixedRadius);
- const zoomFactor = this.getZoomFactor(mapState.zoom);
+ const radiusScale = this.getRadiusScaleByZoom(mapState, fixedRadius);
+ const zoomFactor = this.getZoomFactor(mapState);
const layerProps = {
// multiplier applied just so it being consistent with previously saved maps
diff --git a/src/layers/grid-layer/grid-layer.js b/src/layers/grid-layer/grid-layer.js
index 53fa4e60b..4ed7e63a5 100644
--- a/src/layers/grid-layer/grid-layer.js
+++ b/src/layers/grid-layer/grid-layer.js
@@ -86,8 +86,8 @@ export default class GridLayer extends AggregationLayer {
interaction,
layerCallbacks
}) {
- const zoomFactor = this.getZoomFactor(mapState.zoom);
- const eleZoomFactor = this.getElevationZoomFactor(mapState.zoom);
+ const zoomFactor = this.getZoomFactor(mapState);
+ const eleZoomFactor = this.getElevationZoomFactor(mapState);
const {visConfig} = this.config;
const cellSize = visConfig.worldUnitSize * 1000;
diff --git a/src/layers/hexagon-layer/hexagon-layer.js b/src/layers/hexagon-layer/hexagon-layer.js
index bebb20b1d..979053a2b 100644
--- a/src/layers/hexagon-layer/hexagon-layer.js
+++ b/src/layers/hexagon-layer/hexagon-layer.js
@@ -68,8 +68,8 @@ export default class HexagonLayer extends AggregationLayer {
interaction,
layerCallbacks
}) {
- const zoomFactor = this.getZoomFactor(mapState.zoom);
- const eleZoomFactor = this.getElevationZoomFactor(mapState.zoom);
+ const zoomFactor = this.getZoomFactor(mapState);
+ const eleZoomFactor = this.getElevationZoomFactor(mapState);
const {visConfig} = this.config;
const radius = visConfig.worldUnitSize * 1000;
diff --git a/src/layers/icon-layer/icon-layer.js b/src/layers/icon-layer/icon-layer.js
index e291d2f7a..b4deac528 100644
--- a/src/layers/icon-layer/icon-layer.js
+++ b/src/layers/icon-layer/icon-layer.js
@@ -230,7 +230,7 @@ export default class IconLayer extends Layer {
const layerProps = {
radiusMinPixels: 1,
fp64: this.config.visConfig['hi-precision'],
- radiusScale: this.getRadiusScaleByZoom(mapState.zoom),
+ radiusScale: this.getRadiusScaleByZoom(mapState),
...(this.config.visConfig.fixedRadius ? {} : {radiusMaxPixels: 500})
};
diff --git a/src/layers/point-layer/point-layer.js b/src/layers/point-layer/point-layer.js
index 36a145604..0b5d7f6f4 100644
--- a/src/layers/point-layer/point-layer.js
+++ b/src/layers/point-layer/point-layer.js
@@ -223,7 +223,7 @@ export default class PointLayer extends Layer {
radiusMinPixels: 1,
fp64: this.config.visConfig['hi-precision'],
strokeWidth: this.config.visConfig.thickness,
- radiusScale: this.getRadiusScaleByZoom(mapState.zoom),
+ radiusScale: this.getRadiusScaleByZoom(mapState),
...(this.config.visConfig.fixedRadius ? {} : {radiusMaxPixels: 500})
};
diff --git a/src/utils/export-image-utils.js b/src/utils/export-image-utils.js
index bbe117a89..a81641ec1 100644
--- a/src/utils/export-image-utils.js
+++ b/src/utils/export-image-utils.js
@@ -19,16 +19,69 @@
// THE SOFTWARE.
import domtoimage from 'dom-to-image';
+import {
+ Blob,
+ URL,
+ atob,
+ Uint8Array,
+ ArrayBuffer,
+ document
+} from 'global/window';
import {RESOLUTION_OPTIONS, RATIO_OPTIONS} from 'constants/default-settings';
export function calculateExportImageSize({width, height, ratio, resolution}) {
- const {
- width: scaledWidth,
- height: scaledHeight
- } = RESOLUTION_OPTIONS.find(op => op.id === resolution).getSize(width, height);
- return RATIO_OPTIONS.find(op => op.id === ratio).getSize(scaledWidth, scaledHeight);
+ const resolutionItem = RESOLUTION_OPTIONS.find(op => op.id === resolution);
+ const {width: scaledWidth, height: scaledHeight} = resolutionItem.getSize(
+ width,
+ height
+ );
+ const {zoomOffset, scale} = resolutionItem;
+
+ return {
+ zoomOffset,
+ scale,
+ ...RATIO_OPTIONS.find(op => op.id === ratio).getSize(
+ scaledWidth,
+ scaledHeight
+ )
+ };
}
export function convertToPng(sourceElem) {
return domtoimage.toPng(sourceElem);
}
+
+export function dataURItoBlob(dataURI) {
+ const binary = atob(dataURI.split(',')[1]);
+
+ // separate out the mime component
+ const mimeString = dataURI
+ .split(',')[0]
+ .split(':')[1]
+ .split(';')[0];
+
+ // write the bytes of the string to an ArrayBuffer
+ const ab = new ArrayBuffer(binary.length);
+
+ // create a view into the buffer
+ const ia = new Uint8Array(ab);
+
+ for (let i = 0; i < binary.length; i++) {
+ ia[i] = binary.charCodeAt(i);
+ }
+
+ return new Blob([ab], {type: mimeString});
+}
+
+export function downloadFile(fileBlob, filename) {
+ const url = URL.createObjectURL(fileBlob);
+
+ const link = document.createElement('a');
+ link.setAttribute('href', url);
+ link.setAttribute('download', filename);
+
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
diff --git a/src/utils/map-style-utils/mapbox-gl-style-editor.js b/src/utils/map-style-utils/mapbox-gl-style-editor.js
index c2e9efe4f..a32b5bc96 100644
--- a/src/utils/map-style-utils/mapbox-gl-style-editor.js
+++ b/src/utils/map-style-utils/mapbox-gl-style-editor.js
@@ -20,6 +20,11 @@
import Immutable from 'immutable';
import memoize from 'lodash.memoize';
+import {
+ DEFAULT_LAYER_GROUPS,
+ RESOLUTIONS,
+ RESOLUTION_OPTIONS
+} from 'constants/default-settings';
export function getDefaultLayerGroupVisibility({layerGroups = []}) {
return layerGroups.reduce(
@@ -96,3 +101,45 @@ const mapUrlRg = /^mapbox:\/\/styles\/[-a-z0-9]{2,256}\/[-a-z0-9]{2,256}/;
export function isValidStyleUrl(url) {
return typeof url === 'string' && Boolean(url.match(mapUrlRg));
}
+
+export function scaleMapStyleByResolution(mapboxStyle, resolution) {
+ const labelLayerGroup = DEFAULT_LAYER_GROUPS.find(lg => lg.slug === 'label');
+ const {filter: labelLayerFilter} = labelLayerGroup;
+
+ if (resolution !== RESOLUTIONS.ONE_X && mapboxStyle) {
+ const {scale, zoomOffset} = RESOLUTION_OPTIONS.find(
+ r => r.id === resolution
+ );
+ const copyStyle = mapboxStyle.toJS();
+ (copyStyle.layers || []).forEach(d => {
+ // edit minzoom and maxzoom
+ if (d.maxzoom) {
+ d.maxzoom += zoomOffset;
+ }
+
+ if (d.minzoom) {
+ d.minzoom += zoomOffset;
+ }
+
+ // edit text size
+ if (labelLayerFilter(d)) {
+ if (
+ d.layout &&
+ d.layout['text-size'] &&
+ Array.isArray(d.layout['text-size'].stops)
+ ) {
+ d.layout['text-size'].stops.forEach(stop => {
+ // zoom
+ stop[0] += Math.log2(scale);
+ // size
+ stop[1] *= scale;
+ });
+ }
+ }
+ });
+
+ return Immutable.fromJS(copyStyle);
+ }
+
+ return mapboxStyle;
+}
diff --git a/yarn.lock b/yarn.lock
index 53badbd08..b37543350 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4513,6 +4513,10 @@ lodash.clonedeep@^4.0.1:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.clonedeep/-/lodash.clonedeep-4.5.0.tgz#e23f3f9c4f8fbdde872529c1071857a086e5ccef"
+lodash.debounce@^4.0.8:
+ version "4.0.8"
+ resolved "https://registry.yarnpkg.com/lodash.debounce/-/lodash.debounce-4.0.8.tgz#82d79bff30a67c4005ffd5e2515300ad9ca4d7af"
+
lodash.flattendeep@^4.2.0, lodash.flattendeep@^4.4.0:
version "4.4.0"
resolved "https://registry.yarnpkg.com/lodash.flattendeep/-/lodash.flattendeep-4.4.0.tgz#fb030917f86a3134e5bc9bec0d69e0013ddfedb2"