{"spec_id":"heatmap-geographic","library":"muix","language":"javascript","code":"// anyplot.ai\n// heatmap-geographic: Geographic Heatmap for Spatial Density\n// Library: muix 9.17.0 | JavaScript 22.23.4\n// Quality: 88/100 | Updated: 2026-11-08\n//# anyplot-orientation: square\nimport Box from \"@mui/material/Box\";\nimport Typography from \"@mui/material/Typography\";\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { useDrawingArea, useXScale, useYScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\nconst SIZE = window.ANYPLOT_SIZE;\n\n// Constants\nconst KM_PER_DEG = 111.32; // km per degree of latitude, and of longitude at the equator\nconst PAD_SHARE = 0.04; // map padding around the points, as a share of their extent\nconst BANDWIDTH_SHARE = 0.03; // Gaussian kernel bandwidth as a share of the larger point extent in km\nconst KERNEL_CUTOFF = 3; // the kernel is truncated at this many bandwidths\nconst RASTER_COLS = 240; // density samples across the map width\nconst DENSITY_FLOOR = 0.12; // relative density below which the layer is fully transparent\nconst MAX_ALPHA = 0.92; // opacity of the layer at the peak density\nconst COLORBAR_TICKS = [0, 0.25, 0.5, 0.75, 1];\nconst DENSITY_LABEL = \"Relative density (peak = 1)\";\nconst TITLE = \"heatmap-geographic · javascript · muix · anyplot.ai\";\nconst TITLE_H = 92;\nconst MARGIN = { top: 16, right: 150, bottom: 16, left: 16 };\nconst X_AXIS_H = 64;\nconst Y_AXIS_W = 96;\n\n// Columns: set these to your data's column names\nconst LATITUDE = \"Latitude\"; // role: latitude\nconst LONGITUDE = \"Longitude\"; // role: longitude\n\n// Data: replace this block with your own records, one object per row, and the basemap of your region\n// Retail foot-traffic check-ins across the San Francisco Bay Area: six downtown clusters plus scattered visits.\n// Basemap: one simplified polygon of ocean and bay water as [longitude, latitude] pairs, and the cluster places.\nconst WATER = [\n  [-123.2, 38.2], [-122.69, 37.91], [-122.645, 37.9], [-122.58, 37.86], [-122.56, 37.835], [-122.53, 37.816],\n  [-122.495, 37.82], [-122.478, 37.826], [-122.48, 37.857], [-122.465, 37.87], [-122.45, 37.875], [-122.48, 37.91],\n  [-122.5, 37.93], [-122.49, 37.945], [-122.46, 37.99], [-122.47, 38.05], [-122.36, 38.05], [-122.43, 37.965],\n  [-122.42, 37.94], [-122.37, 37.91], [-122.325, 37.9], [-122.318, 37.888], [-122.315, 37.866], [-122.298, 37.842],\n  [-122.315, 37.826], [-122.325, 37.802], [-122.322, 37.782], [-122.28, 37.76], [-122.25, 37.75], [-122.215, 37.712],\n  [-122.185, 37.695], [-122.15, 37.64], [-122.13, 37.61], [-122.1, 37.565], [-122.075, 37.535], [-122.04, 37.51],\n  [-121.99, 37.49], [-121.95, 37.465], [-121.97, 37.43], [-122.02, 37.42], [-122.07, 37.435], [-122.105, 37.455],\n  [-122.13, 37.47], [-122.17, 37.49], [-122.205, 37.51], [-122.24, 37.54], [-122.255, 37.56], [-122.295, 37.575],\n  [-122.325, 37.59], [-122.358, 37.605], [-122.375, 37.635], [-122.38, 37.665], [-122.385, 37.68], [-122.38, 37.71],\n  [-122.358, 37.728], [-122.375, 37.745], [-122.383, 37.762], [-122.386, 37.776], [-122.388, 37.79], [-122.394, 37.8],\n  [-122.405, 37.809], [-122.42, 37.81], [-122.445, 37.807], [-122.465, 37.806], [-122.477, 37.81], [-122.485, 37.793],\n  [-122.512, 37.78], [-122.51, 37.76], [-122.506, 37.735], [-122.502, 37.712], [-122.496, 37.688], [-122.494, 37.665],\n  [-122.493, 37.635], [-122.516, 37.592], [-122.515, 37.545], [-122.5, 37.497], [-122.455, 37.475], [-122.437, 37.44],\n  [-122.41, 37.375], [-122.405, 37.32], [-122.41, 37.265], [-122.395, 37.185], [-122.33, 37.11], [-122.19, 37.01],\n  [-122.19, 36.9], [-123.2, 36.9],\n];\nconst PLACES = [\n  { name: \"San Francisco\", lon: -122.419, lat: 37.775 },\n  { name: \"Oakland\", lon: -122.271, lat: 37.804 },\n  { name: \"Berkeley\", lon: -122.273, lat: 37.871 },\n  { name: \"Palo Alto\", lon: -122.143, lat: 37.442 },\n  { name: \"Fremont\", lon: -121.989, lat: 37.548 },\n  { name: \"San Jose\", lon: -121.886, lat: 37.338 },\n];\nconst data = (() => {\n  let seed = 42;\n  const rand = () => {\n    seed = (seed * 1664525 + 1013904223) % 4294967296;\n    return seed / 4294967296;\n  };\n  const gaussian = () => {\n    const u1 = Math.max(rand(), 1e-9);\n    const u2 = rand();\n    return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);\n  };\n  const hotspots = [\n    { lon: -122.42, lat: 37.775, weight: 1.0, sigmaKm: 2.6 },\n    { lon: -122.27, lat: 37.805, weight: 0.5, sigmaKm: 1.7 },\n    { lon: -122.27, lat: 37.872, weight: 0.4, sigmaKm: 1.5 },\n    { lon: -121.885, lat: 37.335, weight: 0.85, sigmaKm: 3.4 },\n    { lon: -122.16, lat: 37.445, weight: 0.55, sigmaKm: 2.4 },\n    { lon: -121.99, lat: 37.548, weight: 0.3, sigmaKm: 2.0 },\n  ];\n  const rows: { [LATITUDE]: number; [LONGITUDE]: number }[] = [];\n  hotspots.forEach((h) => {\n    for (let i = 0; i < Math.round(h.weight * 140); i += 1) {\n      const lon = h.lon + (gaussian() * h.sigmaKm) / 88;\n      const lat = h.lat + (gaussian() * h.sigmaKm) / 111;\n      rows.push({ [LATITUDE]: Math.round(lat * 1e5) / 1e5, [LONGITUDE]: Math.round(lon * 1e5) / 1e5 });\n    }\n  });\n  for (let i = 0; i < 90; i += 1) {\n    const lon = -122.55 + rand() * 0.8;\n    const lat = 37.25 + rand() * 0.65;\n    rows.push({ [LATITUDE]: Math.round(lat * 1e5) / 1e5, [LONGITUDE]: Math.round(lon * 1e5) / 1e5 });\n  }\n  return rows;\n})();\n\n// Plot: reads only data and the constants above\nconst points = data.filter((d) => Number.isFinite(d[LATITUDE]) && Number.isFinite(d[LONGITUDE]));\nconst lonLo = Math.min(...points.map((d) => d[LONGITUDE]));\nconst lonHi = Math.max(...points.map((d) => d[LONGITUDE]));\nconst latLo = Math.min(...points.map((d) => d[LATITUDE]));\nconst latHi = Math.max(...points.map((d) => d[LATITUDE]));\nconst meanLat = (latLo + latHi) / 2;\nconst cosLat = Math.cos((meanLat * Math.PI) / 180);\n\n// Map extent: the padded point extent, widened on the short side so px per degree of latitude\n// equals px per degree of longitude divided by cos(mean latitude)\nconst drawW = SIZE.width - MARGIN.left - MARGIN.right - Y_AXIS_W;\nconst drawH = SIZE.height - TITLE_H - MARGIN.top - MARGIN.bottom - X_AXIS_H;\nconst lonSpan = (lonHi - lonLo) * (1 + 2 * PAD_SHARE);\nconst latSpan = (latHi - latLo) * (1 + 2 * PAD_SHARE);\nconst lonView = Math.max(lonSpan, (latSpan * drawW) / drawH / cosLat);\nconst latView = Math.max(latSpan, (lonSpan * cosLat * drawH) / drawW);\nconst xMin = (lonLo + lonHi) / 2 - lonView / 2;\nconst xMax = (lonLo + lonHi) / 2 + lonView / 2;\nconst yMin = (latLo + latHi) / 2 - latView / 2;\nconst yMax = (latLo + latHi) / 2 + latView / 2;\n\n// Gaussian kernel density in km, sampled on a raster over the map extent (row 0 at the north edge)\nconst kmPerDegLon = KM_PER_DEG * cosLat;\nconst bandwidth = BANDWIDTH_SHARE * Math.max((lonHi - lonLo) * kmPerDegLon, (latHi - latLo) * KM_PER_DEG);\nconst cutoffSq = (KERNEL_CUTOFF * bandwidth) ** 2;\nconst rasterRows = Math.round((RASTER_COLS * drawH) / drawW);\nconst density = new Float32Array(RASTER_COLS * rasterRows);\nfor (let row = 0; row < rasterRows; row += 1) {\n  const lat = yMax - ((row + 0.5) / rasterRows) * (yMax - yMin);\n  for (let col = 0; col < RASTER_COLS; col += 1) {\n    const lon = xMin + ((col + 0.5) / RASTER_COLS) * (xMax - xMin);\n    let sum = 0;\n    for (const p of points) {\n      const dx = (lon - p[LONGITUDE]) * kmPerDegLon;\n      const dy = (lat - p[LATITUDE]) * KM_PER_DEG;\n      const distSq = dx * dx + dy * dy;\n      if (distSq < cutoffSq) sum += Math.exp(-distSq / (2 * bandwidth * bandwidth));\n    }\n    density[row * RASTER_COLS + col] = sum;\n  }\n}\nconst peak = density.reduce((m, v) => Math.max(m, v), 0);\n\n// Imprint sequential ramp with a matching opacity ramp, painted once into an offscreen canvas\nconst SEQ_RGB = t.seq.map((hex: string) => [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16)));\nconst canvas = document.createElement(\"canvas\");\ncanvas.width = RASTER_COLS;\ncanvas.height = rasterRows;\nconst ctx = canvas.getContext(\"2d\");\nconst pixels = ctx.createImageData(RASTER_COLS, rasterRows);\ndensity.forEach((v, i) => {\n  const z = v / peak;\n  SEQ_RGB[0].forEach((c: number, k: number) => {\n    pixels.data[i * 4 + k] = Math.round(c + (SEQ_RGB[1][k] - c) * z);\n  });\n  pixels.data[i * 4 + 3] = z <= DENSITY_FLOOR ? 0 : Math.round(((z - DENSITY_FLOOR) / (1 - DENSITY_FLOOR)) * MAX_ALPHA * 255);\n});\nctx.putImageData(pixels, 0, 0);\nconst densityImage = canvas.toDataURL(\"image/png\");\nconst floorColor = `rgb(${SEQ_RGB[0].map((c: number, k: number) => Math.round(c + (SEQ_RGB[1][k] - c) * DENSITY_FLOOR)).join(\", \")})`;\n\nconst subtitle = `n = ${points.length} points · Gaussian kernel density, bandwidth ${bandwidth.toFixed(1)} km · equal ground scale at ${meanLat.toFixed(1)}° latitude`;\n\nfunction WaterLayer() {\n  const xScale = useXScale() as unknown as (v: number) => number;\n  const yScale = useYScale() as unknown as (v: number) => number;\n  const { left, top, width, height } = useDrawingArea();\n  const d = `${WATER.map(([lon, lat], i) => `${i === 0 ? \"M\" : \"L\"}${xScale(lon)},${yScale(lat)}`).join(\" \")} Z`;\n  return (\n    <g>\n      <defs>\n        <clipPath id=\"map-clip\">\n          <rect x={left} y={top} width={width} height={height} />\n        </clipPath>\n      </defs>\n      <path d={d} fill={t.grid} clipPath=\"url(#map-clip)\" />\n    </g>\n  );\n}\n\nfunction DensityLayer() {\n  const xScale = useXScale() as unknown as (v: number) => number;\n  const yScale = useYScale() as unknown as (v: number) => number;\n  const { left, top, width, height } = useDrawingArea();\n  const d = `${WATER.map(([lon, lat], i) => `${i === 0 ? \"M\" : \"L\"}${xScale(lon)},${yScale(lat)}`).join(\" \")} Z`;\n  const barX = left + width + 32;\n  const barW = 22;\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"density-colorbar\" x1=\"0\" y1=\"1\" x2=\"0\" y2=\"0\">\n          <stop offset=\"0%\" stopColor={t.seq[0]} stopOpacity={0} />\n          <stop offset={`${DENSITY_FLOOR * 100}%`} stopColor={floorColor} stopOpacity={0} />\n          <stop offset=\"100%\" stopColor={t.seq[1]} stopOpacity={MAX_ALPHA} />\n        </linearGradient>\n      </defs>\n      <image\n        href={densityImage}\n        x={xScale(xMin)}\n        y={yScale(yMax)}\n        width={xScale(xMax) - xScale(xMin)}\n        height={yScale(yMin) - yScale(yMax)}\n        preserveAspectRatio=\"none\"\n      />\n      <path d={d} fill=\"none\" stroke={t.inkSoft} strokeWidth={1.25} strokeLinejoin=\"round\" clipPath=\"url(#map-clip)\" />\n      {PLACES.filter((p) => p.lon > xMin && p.lon < xMax && p.lat > yMin && p.lat < yMax).map((p) => (\n        <g key={p.name}>\n          <circle cx={xScale(p.lon)} cy={yScale(p.lat)} r={3.5} fill={t.ink} />\n          <text\n            x={xScale(p.lon) + 8}\n            y={yScale(p.lat)}\n            dominantBaseline=\"central\"\n            fontSize={15}\n            fontWeight={600}\n            fill={t.ink}\n            stroke={t.pageBg}\n            strokeWidth={4}\n            paintOrder=\"stroke\"\n          >\n            {p.name}\n          </text>\n        </g>\n      ))}\n      <rect x={barX} y={top} width={barW} height={height} fill=\"url(#density-colorbar)\" stroke={t.inkSoft} strokeWidth={1} />\n      {COLORBAR_TICKS.map((tick) => {\n        const ty = top + height * (1 - tick);\n        return (\n          <g key={tick}>\n            <line x1={barX + barW} x2={barX + barW + 6} y1={ty} y2={ty} stroke={t.inkSoft} strokeWidth={1} />\n            <text x={barX + barW + 10} y={ty} fontSize={14} fill={t.inkSoft} dominantBaseline=\"central\">\n              {tick.toFixed(2)}\n            </text>\n          </g>\n        );\n      })}\n      <text\n        x={barX + barW + 70}\n        y={top + height / 2}\n        fontSize={16}\n        fill={t.ink}\n        textAnchor=\"middle\"\n        transform={`rotate(-90, ${barX + barW + 70}, ${top + height / 2})`}\n      >\n        {DENSITY_LABEL}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <Box sx={{ width: SIZE.width, height: SIZE.height, display: \"flex\", flexDirection: \"column\" }}>\n      <Box sx={{ height: TITLE_H, pt: \"20px\", px: \"24px\", textAlign: \"center\", boxSizing: \"border-box\" }}>\n        <Typography sx={{ fontSize: 22, fontWeight: 600, color: t.ink, lineHeight: 1.2 }}>{TITLE}</Typography>\n        <Typography sx={{ fontSize: 15, color: t.inkSoft, mt: \"6px\" }}>{subtitle}</Typography>\n      </Box>\n      <ChartsContainer\n        width={SIZE.width}\n        height={SIZE.height - TITLE_H}\n        series={[]}\n        skipAnimation\n        margin={MARGIN}\n        xAxis={[\n          {\n            scaleType: \"linear\",\n            min: xMin,\n            max: xMax,\n            label: LONGITUDE,\n            height: X_AXIS_H,\n            tickNumber: 6,\n            valueFormatter: (v: number) => `${Math.abs(v).toFixed(2)}°${v < 0 ? \"W\" : \"E\"}`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        yAxis={[\n          {\n            scaleType: \"linear\",\n            min: yMin,\n            max: yMax,\n            label: LATITUDE,\n            width: Y_AXIS_W,\n            tickNumber: 6,\n            valueFormatter: (v: number) => `${Math.abs(v).toFixed(2)}°${v < 0 ? \"S\" : \"N\"}`,\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            labelStyle: { fontSize: 16, fill: t.ink },\n          },\n        ]}\n        sx={{\n          \"& .MuiChartsAxis-line\": { stroke: t.inkSoft },\n          \"& .MuiChartsAxis-tick\": { stroke: t.inkSoft },\n          \"& .MuiChartsGrid-line\": { stroke: t.grid, strokeDasharray: \"4 4\" },\n        }}\n      >\n        <WaterLayer />\n        <ChartsGrid vertical horizontal />\n        <DensityLayer />\n        <ChartsXAxis />\n        <ChartsYAxis />\n      </ChartsContainer>\n    </Box>\n  );\n}\n"}