Skip to content

Commit

Permalink
initial h3 widgets example
Browse files Browse the repository at this point in the history
  • Loading branch information
juandjara committed Dec 11, 2024
1 parent 14d9c6e commit f09eb8f
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 13 deletions.
2 changes: 1 addition & 1 deletion h3-widgets/.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
VITE_API_BASE_URL=https://gcp-us-east1.api.carto.com
# This API Access Token only grants access to demo data for the examples. Replace it with your own token.
# Go to app.carto.com -> Developers -> Credentials -> API Access Tokens.
VITE_API_ACCESS_TOKEN=eyJhbGciOiJIUzI1NiJ9.eyJhIjoiYWNfbHFlM3p3Z3UiLCJqdGkiOiJkOTU4OWMyZiJ9.78MdzU2J6y-J6Far71_Mh7IQO9eYIZD9nECUiZJAVL4
VITE_API_ACCESS_TOKEN=eyJhbGciOiJIUzI1NiJ9.eyJhIjoiYWNfNDd1dW5tZWciLCJqdGkiOiIxZDUxNjZjYiJ9.lclEIXHEr8neSmWFGr7vGaBBNSmuMntWJLqGjfdYclk
9 changes: 7 additions & 2 deletions h3-widgets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<div id="top-left">
<div id="story-card">
<p class="overline">✨👀 You're viewing</p>
<h2>CARTO Spatial Features datasets in H3 (12M rows).</h2>
<h2>CARTO Widgets for H3 (12M rows).</h2>
<p>
More info about
<a
Expand Down Expand Up @@ -41,10 +41,15 @@ <h2>CARTO Spatial Features datasets in H3 (12M rows).</h2>
</div>

<div class="widgets">
<div class="formula-widget">
<div class="widget formula-widget">
<p class="overline">Total Population</p>
<div id="formula-data"></div>
</div>
<div class="widget histogram-widget relative">
<p class="overline">Urbanity categories</p>
<p class="loader hidden">Loading...</p>
<canvas id="histogram-data" height="300px"></canvas>
</div>
</div>
</div>
</div>
Expand Down
71 changes: 62 additions & 9 deletions h3-widgets/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,22 @@ import {Deck, MapViewState} from '@deck.gl/core';
import {H3TileLayer, BASEMAP, colorBins} from '@deck.gl/carto';
import { initSelectors } from './selectorUtils';
import { debounce, getSpatialFilterFromViewState } from './utils';
import { h3QuerySource } from '@carto/api-client'
import { h3QuerySource, WidgetSource } from '@carto/api-client'
import Chart from 'chart.js/auto';

const cartoConfig = {
// @ts-expect-error misconfigured env variables
apiBaseUrl: import.meta.env.VITE_API_BASE_URL,
// @ts-expect-error misconfigured env variables
accessToken: import.meta.env.VITE_API_ACCESS_TOKEN,
connectionName: 'carto_dw'
};

const INITIAL_VIEW_STATE: MapViewState = {
latitude: 40.7128, // New York
longitude: -74.006, // New York
zoom: 7,
// Spain
latitude: 37.3753636,
longitude: -5.9962577,
zoom: 6,
pitch: 0,
bearing: 0,
minZoom: 3.5,
Expand All @@ -36,6 +40,9 @@ let viewState = INITIAL_VIEW_STATE
const variableSelector = document.getElementById('variable') as HTMLSelectElement;
const aggMethodLabel = document.getElementById('agg-method') as HTMLSelectElement;
const formulaWidget = document.getElementById('formula-data') as HTMLDivElement;
const categoriesWidget = document.getElementById('categories-data') as HTMLCanvasElement;
const histogramWidget = document.getElementById('histogram-data') as HTMLCanvasElement;
let histogramChart: Chart;

aggMethodLabel.innerText = aggregationExp;
variableSelector?.addEventListener('change', () => {
Expand All @@ -51,8 +58,8 @@ variableSelector?.addEventListener('change', () => {
function render() {
source = h3QuerySource({
...cartoConfig,
aggregationExp: `${aggregationExp} as value`,
sqlQuery: `SELECT * FROM cartobq.public_account.derived_spatialfeatures_usa_h3int_res8_v1_yearly_v2`
aggregationExp: `${aggregationExp} as value`,
sqlQuery: `SELECT * FROM carto-demo-data.demo_tables.derived_spatialfeatures_esp_h3res8_v1_yearly_v2`
});
renderLayers();
renderWidgets();
Expand Down Expand Up @@ -91,15 +98,61 @@ function renderLayers() {
}

async function renderWidgets() {
formulaWidget.innerHTML = '<span style="font-weight: 400; font-size: 14px;">Loading...</span>'
const { widgetSource } = await source
const formula = await widgetSource.getFormula({
await Promise.all([
renderFormula(widgetSource),
renderHistogram(widgetSource)
])
}

async function renderFormula(ws: WidgetSource) {
formulaWidget.innerHTML = '<span style="font-weight: 400; font-size: 14px;">Loading...</span>'
const formula = await ws.getFormula({
column: selectedVariable,
operation: 'sum',
spatialFilter: getSpatialFilterFromViewState(viewState),
viewState,
})
formulaWidget.textContent = Intl.NumberFormat('en-US', {
maximumFractionDigits: 0,
// notation: 'compact'
}).format(formula.value)
}

const TICKS = [100, 500, 1000, 5000];

async function renderHistogram(ws: WidgetSource) {
histogramWidget.parentElement?.querySelector('.loader')?.classList.toggle('hidden', false);
histogramWidget.classList.toggle('hidden', true);

const categories = await ws.getCategories({
column: 'urbanity',
operation: 'count',
spatialFilter: getSpatialFilterFromViewState(viewState),
viewState,
})
formulaWidget.textContent = Intl.NumberFormat('en-US').format(formula.value)

histogramWidget.parentElement?.querySelector('.loader')?.classList.toggle('hidden', true);
histogramWidget.classList.toggle('hidden', false);

if (histogramChart) {
histogramChart.data.labels = categories.map((c) => c.name);
histogramChart.data.datasets[0].data = categories.map((c) => c.value);
histogramChart.update();
} else {
histogramChart = new Chart(histogramWidget, {
type: 'bar',
data: {
labels: categories.map((c) => c.name),
datasets: [
{
label: 'Urbanity category',
data: categories.map((c) => c.value),
}
]
},
})
}
}

const debouncedRenderWidgets = debounce(renderWidgets, 500);
Expand Down
2 changes: 2 additions & 0 deletions h3-widgets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@
"vite": "^4.5.0"
},
"dependencies": {
"@carto/api-client": "^0.4.1-alpha.0",
"@deck.gl/aggregation-layers": "^9.0.17",
"@deck.gl/carto": "^9.0.17",
"@deck.gl/core": "^9.0.17",
"@deck.gl/extensions": "^9.0.17",
"@deck.gl/geo-layers": "^9.0.17",
"@deck.gl/layers": "^9.0.17",
"@deck.gl/mesh-layers": "^9.0.17",
"chart.js": "^4.4.7",
"maplibre-gl": "^3.5.2"
}
}
20 changes: 19 additions & 1 deletion h3-widgets/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ button:hover {
border: #ccc 1px solid;
}

.widgets {
.widget {
margin: 2rem 0;
}

Expand All @@ -131,3 +131,21 @@ button:hover {
font-weight: 600;
font-family: monospace;
}

.relative { position: relative; }

.loader {
font-size: 14px;
font-weight: 400;

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 1;
transition: opacity 0.3s;
}

.hidden {
opacity: 0;
}

0 comments on commit f09eb8f

Please sign in to comment.