Skip to content

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

[Enhancement] Add H3 layer to kepler.gl (#198)

Eric Socolofskya8ea76fa162e
diff --git a/examples/demo-app/src/app.js b/examples/demo-app/src/app.js
index 93d5625ed..d1e1cb10e 100644
--- a/examples/demo-app/src/app.js
+++ b/examples/demo-app/src/app.js
@@ -38,6 +38,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 sampleH3Data from './data/sample-hex-id-csv';
import sampleIconCsv, {config as savedMapConfig} from './data/sample-icon-csv';
import {updateVisData, addDataToMap} from 'kepler.gl/actions';
import Processors from 'kepler.gl/processors';
@@ -166,6 +167,21 @@ class App extends Component {
data: Processors.processGeojson(sampleGeojson)
})
);
+
+ // load h3 hexagon
+ this.props.dispatch(
+ addDataToMap({
+ datasets: [
+ {
+ info: {
+ label: 'H3 Hexagons V2',
+ id: 'h3-hex-id'
+ },
+ data: Processors.processCsvData(sampleH3Data)
+ }
+ ]
+ })
+ );
}
render() {
diff --git a/examples/demo-app/src/data/sample-hex-id-csv.js b/examples/demo-app/src/data/sample-hex-id-csv.js
new file mode 100644
index 000000000..767f39a84
--- /dev/null
+++ b/examples/demo-app/src/data/sample-hex-id-csv.js
@@ -0,0 +1,109 @@
+// 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.
+
+export default `hex_id,value
+89283082c2fffff,64
+8928308288fffff,73
+89283082c07ffff,65
+89283082817ffff,74
+89283082c3bffff,66
+89283082883ffff,76
+89283082c03ffff,60
+89283082807ffff,68
+8928308289bffff,49
+89283082c0fffff,41
+89283082c87ffff,50
+89283082d4fffff,45
+89283082c77ffff,41
+89283082c2bffff,53
+89283082803ffff,41
+89283082813ffff,43
+89283082d5bffff,45
+89283082897ffff,40
+89283082c67ffff,42
+89283082d47ffff,51
+89283082dc3ffff,52
+89283082c33ffff,43
+89283082c23ffff,40
+89283082887ffff,36
+89283082d4bffff,36
+892830828bbffff,48
+892830828b7ffff,28
+89283082c17ffff,34
+89283082c6fffff,21
+8928308288bffff,25
+892830828abffff,26
+89283082c27ffff,27
+89283082c8fffff,33
+89283082cafffff,29
+89283082c13ffff,27
+89283082cabffff,22
+89283082c63ffff,26
+89283082d43ffff,30
+89283082d53ffff,19
+892830828a3ffff,28
+89283082d1bffff,20
+89283095367ffff,17
+8928309536bffff,26
+89283082c37ffff,16
+89283082c73ffff,17
+89283082c8bffff,15
+89283082ca7ffff,27
+89283082cb3ffff,32
+89283082c0bffff,26
+89283082ca3ffff,19
+89283082dcfffff,18
+89283082c1bffff,20
+89283082ddbffff,18
+8928309534fffff,16
+89283082d03ffff,15
+89283082cbbffff,21
+89283082cd7ffff,9
+8928309534bffff,9
+892830828c7ffff,13
+89283082cc7ffff,12
+89283082d0bffff,19
+89283082dcbffff,19
+89283082dd3ffff,15
+89283082dd7ffff,15
+892830828d7ffff,13
+89283082d17ffff,5
+8928309536fffff,8
+89283095373ffff,6
+89283082cb7ffff,15
+89283082d83ffff,9
+89283082d07ffff,4
+89283082d0fffff,3
+89283082d13ffff,6
+89283082d9bffff,5
+89283082c83ffff,11
+89283082d8bffff,4
+89283082dc7ffff,5
+89283095377ffff,5
+89283082c97ffff,4
+89283082d7bffff,2
+89283082d8fffff,1
+89283095347ffff,3
+89283095363ffff,2
+8928309537bffff,4
+89283082d93ffff,6
+89283082d73ffff,1
+8928309530bffff,1
+8928309532bffff,1`;
diff --git a/package.json b/package.json
index 898b23900..c9b49fead 100644
--- a/package.json
+++ b/package.json
@@ -74,6 +74,7 @@
"deck.gl": "5.3.4",
"fuzzy": "^0.1.3",
"global": "^4.3.0",
+ "h3-js": "^3.1.0",
"keymirror": "^0.1.1",
"lodash.clonedeep": "^4.0.1",
"lodash.debounce": "^4.0.8",
diff --git a/src/components/side-panel/layer-panel/layer-configurator.js b/src/components/side-panel/layer-panel/layer-configurator.js
index 54b3efb26..1dff65fd5 100644
--- a/src/components/side-panel/layer-panel/layer-configurator.js
+++ b/src/components/side-panel/layer-panel/layer-configurator.js
@@ -370,6 +370,15 @@ export default class LayerConfigurator extends Component {
{...visConfiguratorProps}
/>
</LayerConfigGroup>
+
+ {/* Cell size */}
+ <LayerConfigGroup label={'radius'}>
+ <VisConfigSlider
+ {...layer.visConfigSettings.coverage}
+ {...visConfiguratorProps}
+ />
+ </LayerConfigGroup>
+
{/* height */}
<LayerConfigGroup
{...LAYER_VIS_CONFIGS.enable3d}
diff --git a/src/layers/h3-hexagon-layer/h3-hexagon-cell-layer.js b/src/layers/h3-hexagon-layer/h3-hexagon-cell-layer.js
new file mode 100644
index 000000000..b2e6b6ac9
--- /dev/null
+++ b/src/layers/h3-hexagon-layer/h3-hexagon-cell-layer.js
@@ -0,0 +1,104 @@
+// 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 {HexagonCellLayer} from 'deck.gl';
+import {CylinderGeometry} from 'luma.gl';
+import {getAngle, getRadius, getH3VerticeTransform, transformCylinderPositions} from './h3-utils';
+
+// TODO: export all dekc.gl layers from kepler.gl
+export default class H3HexagonCellLayer extends HexagonCellLayer {
+
+ getCylinderGeometry(radius) {
+ const transform = this.getTransform();
+
+ const cylinderGeometry = new CylinderGeometry({
+ radius,
+ topRadius: radius,
+ bottomRadius: radius,
+ topCap: true,
+ bottomCap: true,
+ height: 1,
+ verticalAxis: 'z',
+ nradial: 6,
+ nvertical: 1
+ });
+
+ const pos = cylinderGeometry.attributes.positions.value;
+
+ if (transform) {
+ const adjusted = transformCylinderPositions(pos, transform);
+ cylinderGeometry.attributes.positions.value = adjusted;
+ }
+
+ return cylinderGeometry;
+ }
+
+ getTransform() {
+ const {hexagonVertices, hexagonCenter} = this.props;
+
+ if (Array.isArray(hexagonVertices) &&
+ hexagonVertices.length >= 6 &&
+ Array.isArray(hexagonCenter)) {
+ const screenVertices = hexagonVertices.map(d => this.projectFlat(d));
+ const screenCentroid = this.projectFlat(hexagonCenter);
+ return getH3VerticeTransform(screenVertices, screenCentroid);
+ }
+
+ return null;
+ }
+
+ updateRadiusAngle() {
+ let {angle, radius} = this.props;
+ const {hexagonVertices} = this.props;
+
+ if (Array.isArray(hexagonVertices) && hexagonVertices.length >= 6) {
+ const {viewport} = this.context;
+ // calculate angle and vertices from hexagonVertices if provided
+ const vertices = this.props.hexagonVertices;
+
+ const vertex0 = vertices[0];
+ const vertex3 = vertices[3];
+
+ // transform to space coordinates
+ const {pixelsPerMeter} = viewport.getDistanceScales();
+ const spaceCoord0 = this.projectFlat(vertex0);
+ const spaceCoord3 = this.projectFlat(vertex3);
+
+ angle = getAngle(spaceCoord0, spaceCoord3);
+ radius = getRadius(spaceCoord0, spaceCoord3) /pixelsPerMeter[0];
+ }
+
+ this.setState({angle, radius});
+ }
+
+ draw(opts) {
+ const {uniforms} = opts;
+
+ super.draw({
+ ...opts,
+ uniforms: {
+ ...uniforms,
+ picking_uHighlightScale: this.props.extruded ? 1.4 : 0.0
+ }
+ })
+ }
+}
+
+H3HexagonCellLayer.layerName = 'H3HexagonCellLayer';
diff --git a/src/layers/h3-hexagon-layer/h3-hexagon-layer-icon.js b/src/layers/h3-hexagon-layer/h3-hexagon-layer-icon.js
new file mode 100644
index 000000000..dda9b538f
--- /dev/null
+++ b/src/layers/h3-hexagon-layer/h3-hexagon-layer-icon.js
@@ -0,0 +1,48 @@
+// 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 React, {Component} from 'react';
+import PropTypes from 'prop-types';
+import Base from 'components/common/icons/base';
+
+class H3HexagonLayerIcon extends Component {
+ static propTypes = {
+ /** Set the height of the icon, ex. '16px' */
+ height: PropTypes.string,
+ colors: PropTypes.arrayOf(PropTypes.string)
+ };
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'h3-hexagon-layer-icon',
+ totalColor: 4
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <path d="M44.59,54.5H19.41L6.81,32.68,19.41,10.87H44.59L57.19,32.68Zm-23-3.83H42.38l10.38-18-10.38-18H21.62l-10.38,18Z" />
+ <polygon points="24.65 32.86 24.65 37.79 22.53 37.79 22.53 26.3 24.65 26.3 24.65 30.91 29.32 30.91 29.32 26.3 31.43 26.3 31.43 37.79 29.32 37.79 29.32 32.86 24.65 32.86" />
+ <path d="M33.79,37.05l.6-1.67a5.86,5.86,0,0,0,1.39.61,5.59,5.59,0,0,0,1.5.19A2.57,2.57,0,0,0,39,35.66a1.81,1.81,0,0,0,.61-1.46A1.29,1.29,0,0,0,38.94,33a4.55,4.55,0,0,0-2.05-.32H35.74V31h1.1A5.4,5.4,0,0,0,38,30.85a2.1,2.1,0,0,0,.77-.29,1.53,1.53,0,0,0,.51-.54,1.58,1.58,0,0,0,.15-.73,1.14,1.14,0,0,0-.51-1,2.67,2.67,0,0,0-1.5-.34,4.56,4.56,0,0,0-1.51.24,5,5,0,0,0-1.34.73l-.7-1.61a4.92,4.92,0,0,1,1.66-.83,6.91,6.91,0,0,1,2-.31,4.41,4.41,0,0,1,2.81.79,2.71,2.71,0,0,1,1,2.24,2.33,2.33,0,0,1-.54,1.62,3.45,3.45,0,0,1-1.46.93v0a3,3,0,0,1,1.67.81,2.3,2.3,0,0,1,.64,1.7A3.27,3.27,0,0,1,40.48,37a5,5,0,0,1-3.16.91A6.77,6.77,0,0,1,33.79,37.05Z" />
+ </Base>
+ );
+ }
+};
+
+export default H3HexagonLayerIcon;
diff --git a/src/layers/h3-hexagon-layer/h3-hexagon-layer.js b/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
new file mode 100644
index 000000000..d514f1318
--- /dev/null
+++ b/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
@@ -0,0 +1,277 @@
+// 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 memoize from 'lodash.memoize';
+
+import Layer from '../base-layer';
+import {GeoJsonLayer} from 'deck.gl';
+import H3HexagonCellLayer from './h3-hexagon-cell-layer';
+import {getVertices, getCentroid, idToPolygonGeo} from './h3-utils';
+import H3HexagonLayerIcon from './h3-hexagon-layer-icon';
+
+export const HEXAGON_ID_FIELDS = {
+ hex_id: ['hex_id', 'hexagon_id', 'h3_id']
+};
+
+export const hexIdRequiredColumns = ['hex_id'];
+export const hexIdAccessor = ({hex_id}) => d => d[hex_id.fieldIdx];
+export const hexIdResolver = ({hex_id}) => hex_id.fieldIdx;
+
+export const HexagonIdVisConfigs = {
+ opacity: 'opacity',
+ colorRange: 'colorRange',
+ coverage: 'coverage',
+ sizeRange: 'elevationRange',
+ elevationScale: 'elevationScale',
+ 'hi-precision': 'hi-precision'
+};
+
+function hexToRgb(hex) {
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+
+ const r = parseInt(result[1], 16);
+ const g = parseInt(result[2], 16);
+ const b = parseInt(result[3], 16);
+
+ return [r, g, b];
+}
+
+export default class HexagonIdLayer extends Layer {
+ constructor(props) {
+ super(props);
+ this.registerVisConfig(HexagonIdVisConfigs);
+ this.getHexId = memoize(hexIdAccessor, hexIdResolver);
+ }
+
+ get type() {
+ return 'hexagonId';
+ }
+
+ get name() {
+ return 'H3';
+ }
+
+ get requiredLayerColumns() {
+ return hexIdRequiredColumns;
+ }
+
+ get layerIcon() {
+ // use hexagon layer icon for now
+ return H3HexagonLayerIcon;
+ }
+
+ get visualChannels() {
+ return {
+ ...super.visualChannels,
+ size: {
+ ...super.visualChannels.size,
+ property: 'height'
+ }
+ };
+ }
+
+ static findDefaultLayerProps({fields}) {
+ const foundColumns = this.findDefaultColumnField(HEXAGON_ID_FIELDS, fields);
+ if (!foundColumns || !foundColumns.length) {
+ return null;
+ }
+
+ return foundColumns.map(columns => ({
+ isVisible: true,
+ label: 'H3 Hexagon',
+ columns
+ }));
+ }
+
+ formatLayerData(_, allData, filteredIndex, oldLayerData, opt = {}) {
+ const {
+ colorScale,
+ colorDomain,
+ colorField,
+ color,
+ columns,
+ sizeField,
+ sizeScale,
+ sizeDomain,
+ visConfig: {sizeRange, colorRange}
+ } = this.config;
+
+ // color
+ const cScale =
+ colorField &&
+ this.getVisChannelScale(
+ colorScale,
+ colorDomain,
+ colorRange.colors.map(c => hexToRgb(c))
+ );
+
+ // height
+ const sScale =
+ sizeField && this.getVisChannelScale(sizeScale, sizeDomain, sizeRange);
+
+ const getHexId = this.getHexId(columns);
+
+ if (!oldLayerData || oldLayerData.getHexId !== getHexId) {
+ this.updateLayerMeta(allData, getHexId);
+ }
+
+ let data;
+ if (
+ oldLayerData &&
+ oldLayerData.data &&
+ opt.sameData &&
+ oldLayerData.getHexId === getHexId
+ ) {
+ data = oldLayerData.data;
+ } else {
+ data = filteredIndex.reduce((accu, index, i) => {
+ const id = getHexId(allData[index]);
+ const centroid = this.dataToFeature.centroids[index];
+
+ if (centroid) {
+ accu.push({
+ // keep a reference to the original data index
+ index: i,
+ data: allData[index],
+ id,
+ centroid
+ });
+ }
+
+ return accu;
+ }, []);
+ }
+
+ const getElevation = sScale ? d =>
+ this.getEncodedChannelValue(sScale, d.data, sizeField, 0) : 0;
+
+ const getColor = cScale ? d =>
+ this.getEncodedChannelValue(cScale, d.data, colorField) : color;
+
+ // const layerData = {
+ return {
+ data,
+ getElevation,
+ getColor,
+ getHexId,
+ hexagonVertices: this.dataToFeature.hexagonVertices,
+ hexagonCenter: this.dataToFeature.hexagonCenter
+ };
+ }
+
+ updateLayerMeta(allData, getHexId) {
+ let hexagonVertices;
+ let hexagonCenter;
+ const centroids = {};
+
+ allData.forEach((d, index) => {
+ const id = getHexId(d);
+ if (typeof id !== 'string' || !id.length) {
+ return;
+ }
+ // find hexagonVertices
+ // only need 1 instance of hexagonVertices
+ if (!hexagonVertices) {
+ hexagonVertices = id && getVertices({id});
+ hexagonCenter = id && getCentroid({id})
+ }
+
+ // save a reference of centroids to dataToFeature
+ // so we don't have to re calculate it again
+ centroids[index] = getCentroid({id});
+ });
+
+ const bounds = this.getPointsBounds(Object.values(centroids), d => d);
+ const lightSettings = this.getLightSettingsFromBounds(bounds);
+
+ this.dataToFeature = {hexagonVertices, hexagonCenter, centroids};
+ this.updateMeta({bounds, lightSettings});
+ }
+
+ renderLayer({
+ data,
+ idx,
+ layerInteraction,
+ objectHovered,
+ mapState,
+ interactionConfig
+ }) {
+ const zoomFactor = this.getZoomFactor(mapState);
+ const eleZoomFactor = this.getElevationZoomFactor(mapState);
+ const {config, meta} = this;
+ const {visConfig} = config;
+
+ const updateTriggers = {
+ getColor: {
+ color: config.color,
+ colorField: config.colorField,
+ colorRange: config.visConfig.colorRange,
+ colorScale: config.colorScale
+ },
+ getElevation: {
+ sizeField: config.sizeField,
+ sizeRange: config.visConfig.sizeRange
+ }
+ };
+
+ return [
+ new H3HexagonCellLayer({
+ ...layerInteraction,
+ ...data,
+ id: this.id,
+ idx,
+ pickable: true,
+
+ // coverage
+ coverage: visConfig.coverage,
+
+ // parameters
+ parameters: {depthTest: Boolean(config.sizeField || mapState.dragRotate)},
+
+ // highlight
+ autoHighlight: Boolean(config.sizeField),
+
+ // elevation
+ extruded: Boolean(config.sizeField),
+ elevationScale: visConfig.elevationScale * eleZoomFactor,
+
+ // color
+ opacity: visConfig.opacity,
+
+ // render
+ lightSettings: meta.lightSettings,
+ updateTriggers
+ }),
+ ...(this.isLayerHovered(objectHovered) && !config.sizeField
+ ? [
+ new GeoJsonLayer({
+ id: `${this.id}-hovered`,
+ data: [
+ idToPolygonGeo(objectHovered, {
+ lineColor: config.highlightColor
+ })
+ ],
+ lineWidthScale: 8 * zoomFactor
+ })
+ ]
+ : [])
+ ];
+ }
+}
diff --git a/src/layers/h3-hexagon-layer/h3-utils.js b/src/layers/h3-hexagon-layer/h3-utils.js
new file mode 100644
index 000000000..2d53bd33b
--- /dev/null
+++ b/src/layers/h3-hexagon-layer/h3-utils.js
@@ -0,0 +1,174 @@
+// 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 {h3GetResolution, h3ToGeo, h3ToGeoBoundary, geoToH3} from 'h3-js';
+export {h3GetResolution};
+
+// get vertices should return [lon, lat]
+export function getVertices({id}) {
+ // always reverse it
+ return h3ToGeoBoundary(id, true);
+}
+
+// get centroid should return [lon, lat]
+export function getCentroid({id}) {
+ // always reverse it to [lng, lat]
+ return h3ToGeo(id).reverse();
+}
+
+export function idToPolygonGeo({object}, properties) {
+ if (!object || !object.id) {
+ return null;
+ }
+
+ const vertices = getVertices(object);
+
+ return {
+ geometry: {
+ coordinates: vertices,
+ type: 'LineString'
+ },
+ properties
+ };
+}
+
+export function getCenterHex({latitude, longitude}, resolution) {
+ return geoToH3(latitude, longitude, resolution);
+}
+
+// H3 hexagon are not perfect hexagon after projection, they are slightly distorted
+// Here we calculate the translation from perfect hexagon to h3 hexagon
+// A mathematica proof can be found at
+// https://beta.observablehq.com/@heshan0131/h3-hexagon-shape-normalize
+export function getH3VerticeTransform(rawVertices, centroid) {
+ const vertices = revertVertices(rawVertices.map(vt => offset(vt, centroid)));
+ const radius = getRadius(vertices[0], vertices[3]);
+
+ const angle = getAngle(vertices[0], vertices[3])
+
+ // rotate hexagon vertices, so that v0 - v3 axis parallel with xAxis
+ // 2___1
+ // 3 / \ 0
+ // \___/
+ // 4 5
+ //
+ const rotatedVertices = vertices.map(vt => rotate([0, 0], vt, angle));
+
+ // vertices of a perfect hexagon
+ const normalVertices = getHexagonVertices(radius);
+
+ // calculate translation
+ return getTranslations(rotatedVertices, normalVertices)
+}
+
+// Vertices index based on
+// https://github.com/uber/luma.gl/blob/master/modules/core/src/geometry/truncated-cone-geometry.js
+export function transformCylinderPositions(positions, translations) {
+
+ const primitives = translations.map(({dr, da}, i) =>
+ getPtOnCircle(dr, da + Math.PI * i / 3));
+ // close it
+ primitives.push(primitives[0]);
+
+ // starting from the 8th vertice, repeat 4 times, only replace x(0), y(1)
+ return positions.map((v, i) => {
+ if (i > 20 && i < 21 * 5 && i % 3 < 2) {
+ const row = Math.floor(i / 3);
+ const col = i % 3;
+ return primitives[row % 7][col];
+ }
+ return v;
+ });
+}
+
+function offset([px, py], [x0, y0]) {
+ return [[px - x0], [py - y0]];
+}
+
+function rotate([cx, cy], [x, y], radians) {
+ const cos = Math.cos(radians);
+ const sin = Math.sin(radians);
+ const nx = (cos * (x - cx)) + (sin * (y - cy)) + cx;
+ const ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
+
+ return [nx, ny];
+}
+
+function getDistance(pt0, pt1) {
+ const dx = pt0[0] - pt1[0];
+ const dy = pt0[1] - pt1[1];
+ const dxy = Math.sqrt(dx * dx + dy * dy);
+ return dxy;
+}
+
+export function getRadius(pt0, pt3) {
+ const dxy = getDistance(pt0, pt3);
+ return dxy / 2;
+}
+
+export function getAngle(pt0, pt3) {
+ const dx = pt0[0] - pt3[0];
+ const dy = pt0[1] - pt3[1];
+ const dxy = Math.sqrt(dx * dx + dy * dy);
+
+ // Calculate angle that the perpendicular hexagon vertex axis is tilted
+ const angle = Math.acos(dx / dxy) * Math.sign(dy);
+ return angle;
+}
+
+function getPtOnCircle(radius, angle) {
+ return [radius * Math.cos(angle), radius * Math.sin(angle)];
+}
+
+function getHexagonVertices(r) {
+ const ang60 = Math.PI / 3;
+ const pts = []
+ for (let i = 0; i < 6; i++) {
+ pts.push(getPtOnCircle(r, ang60 * i))
+ }
+
+ return pts;
+}
+
+function revertVertices(verts) {
+ // reverting verts from clock (h3) to counter clock wise (luma cylinder)
+ const seq = [0, 5, 4, 3, 2, 1];
+ return seq.map(s => verts[s]);
+}
+
+function getTranslations(vts, origs) {
+ // 0 and 3 should be the guide
+ const ct = [0, 0];
+ const translations = [];
+
+ for (let i = 0; i < 6; i++) {
+ const vt = vts[i];
+ const org = origs[i];
+
+ const r = getRadius(org, ct);
+ const dr = getRadius(vt, ct) / r
+
+ const da = Math.atan2(vt[1], vt[0]) - Math.atan2(org[1], org[0]);
+
+ translations.push({dr, da});
+ }
+
+ return translations;
+}
diff --git a/src/layers/index.js b/src/layers/index.js
index 55722f876..3522059f3 100644
--- a/src/layers/index.js
+++ b/src/layers/index.js
@@ -27,6 +27,7 @@ import {default as GeojsonLayer} from './geojson-layer/geojson-layer';
import {default as ClusterLayer} from './cluster-layer/cluster-layer';
import {default as IconLayer} from './icon-layer/icon-layer';
import {default as HeatmapLayer} from './heatmap-layer/heatmap-layer';
+import {default as H3Layer} from './h3-hexagon-layer/h3-hexagon-layer';
// base layer
export {default as Layer} from './base-layer';
@@ -41,7 +42,8 @@ export const KeplerGlLayers = {
GeojsonLayer,
ClusterLayer,
IconLayer,
- HeatmapLayer
+ HeatmapLayer,
+ H3Layer
};
export const LayerClasses = {
@@ -53,5 +55,6 @@ export const LayerClasses = {
geojson: GeojsonLayer,
cluster: ClusterLayer,
icon: IconLayer,
- heatmap: HeatmapLayer
+ heatmap: HeatmapLayer,
+ hexagonId: H3Layer
};
diff --git a/yarn.lock b/yarn.lock
index 53a078290..ff54cee4f 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3513,6 +3513,10 @@ grid-index@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/grid-index/-/grid-index-1.0.0.tgz#ad2c5d54ce5b35437faff1d70a9aeb3d1d261110"
+h3-js@^3.1.0:
+ version "3.1.0"
+ resolved "https://registry.yarnpkg.com/h3-js/-/h3-js-3.1.0.tgz#a47142eed83b7de5d27f6be026ed6fe3a9a67cb4"
+
hammerjs@^2.0.8:
version "2.0.8"
resolved "https://registry.yarnpkg.com/hammerjs/-/hammerjs-2.0.8.tgz#04ef77862cff2bb79d30f7692095930222bf60f1"