{"spec_id":"map-route-path","library":"muix","language":"javascript","code":"// anyplot.ai\n// map-route-path: Route Path Map\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 89/100 | Updated: 2026-10-24\n\nimport { ChartsContainer } from \"@mui/x-charts/ChartsContainer\";\nimport { ChartsXAxis } from \"@mui/x-charts/ChartsXAxis\";\nimport { ChartsYAxis } from \"@mui/x-charts/ChartsYAxis\";\nimport { ChartsGrid } from \"@mui/x-charts/ChartsGrid\";\nimport { useDrawingArea, useXScale, useYScale, useZColorScale } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"map-route-path · javascript · muix · anyplot.ai\";\nconst BASEMAP_CAPTION =\n  \"Coordinates: WGS 84 (EPSG:4326) · Basemap: simplified IJ waterfront, canal ring, Amstel and Vondelpark\";\nconst TITLE_HEIGHT = 54;\nconst CAPTION_HEIGHT = 32;\nconst X_AXIS_HEIGHT = 58;\nconst Y_AXIS_WIDTH = 98;\nconst MARGIN = { top: 20, right: 300, bottom: 14, left: 16 };\nconst LABEL_OFFSET = 18;\nconst PAD_SHARE = 0.14;\nconst ARROW_STRIDE = 8;\n\n// Columns: set these to your data's column names\nconst SEQUENCE = \"Waypoint sequence\"; // role: sequence\nconst LAT = \"Latitude (°N)\"; // role: lat\nconst LON = \"Longitude (°E)\"; // role: lon\nconst PROGRESS = \"Elapsed time share\"; // role: timestamp\nconst LANDMARK = \"Landmark\"; // role: label\n\n// Data: replace this block with your own records\nconst KEYFRAMES: Array<[number, number, string]> = [\n  [52.3731, 4.8926, \"Start · Dam Square\"],\n  [52.3702, 4.8895, \"\"],\n  [52.3668, 4.8838, \"\"],\n  [52.364, 4.8815, \"\"],\n  [52.358, 4.8686, \"Vondelpark West\"],\n  [52.3565, 4.8755, \"\"],\n  [52.3585, 4.8815, \"\"],\n  [52.36, 4.8852, \"Rijksmuseum\"],\n  [52.3635, 4.892, \"\"],\n  [52.3662, 4.8995, \"\"],\n  [52.3678, 4.904, \"Waterlooplein\"],\n  [52.372, 4.9005, \"\"],\n  [52.3755, 4.896, \"\"],\n  [52.3765, 4.884, \"Jordaan\"],\n  [52.3795, 4.8895, \"\"],\n  [52.3791, 4.9003, \"End · Amsterdam Centraal\"],\n];\n\nconst STEPS_PER_LEG = 4;\nconst TOTAL_WAYPOINTS = (KEYFRAMES.length - 1) * STEPS_PER_LEG + 1;\nconst data: Array<Record<string, string | number>> = [];\n\nlet seed = 42;\nfor (let leg = 0; leg < KEYFRAMES.length - 1; leg++) {\n  const [lat1, lon1, name1] = KEYFRAMES[leg];\n  const [lat2, lon2] = KEYFRAMES[leg + 1];\n  for (let s = 0; s < STEPS_PER_LEG; s++) {\n    const idx = leg * STEPS_PER_LEG + s;\n    const u = s / STEPS_PER_LEG;\n    seed = (seed * 1664525 + 1013904223) >>> 0;\n    const r1 = seed / 0x100000000;\n    seed = (seed * 1664525 + 1013904223) >>> 0;\n    const r2 = seed / 0x100000000;\n    const wobble = Math.sin(u * Math.PI);\n    const jLat = (r1 - 0.5) * 0.0005 * wobble;\n    const jLon = (r2 - 0.5) * 0.0007 * wobble;\n    data.push({\n      [SEQUENCE]: idx,\n      [LAT]: Number((lat1 + (lat2 - lat1) * u + jLat).toFixed(6)),\n      [LON]: Number((lon1 + (lon2 - lon1) * u + jLon).toFixed(6)),\n      [PROGRESS]: Number((idx / (TOTAL_WAYPOINTS - 1)).toFixed(4)),\n      [LANDMARK]: s === 0 ? name1 : \"\",\n    });\n  }\n}\nconst lastKeyframe = KEYFRAMES[KEYFRAMES.length - 1];\ndata.push({\n  [SEQUENCE]: TOTAL_WAYPOINTS - 1,\n  [LAT]: lastKeyframe[0],\n  [LON]: lastKeyframe[1],\n  [PROGRESS]: 1,\n  [LANDMARK]: lastKeyframe[2],\n});\n\n// Basemap: simplified [lat, lon] outlines of the city around the route\nconst RING_CENTER: [number, number] = [52.3772, 4.8948];\nconst CANAL_RING_RADII = [0.0045, 0.0068, 0.0089, 0.011, 0.0152]; // Singel … Singelgracht (° lat)\nconst WATER_AREAS: Array<Array<[number, number]>> = [\n  // IJ waterfront north of Centraal\n  [\n    [52.3812, 4.84], [52.3808, 4.875], [52.3815, 4.893], [52.3812, 4.905],\n    [52.3802, 4.915], [52.3805, 4.93], [52.39, 4.93], [52.39, 4.84],\n  ],\n  // Oosterdok\n  [[52.3778, 4.9035], [52.3785, 4.912], [52.3768, 4.9135], [52.3762, 4.905]],\n];\nconst RIVERS: Array<Array<[number, number]>> = [\n  // Amstel\n  [[52.35, 4.907], [52.356, 4.9055], [52.3615, 4.9035], [52.3655, 4.9005], [52.3675, 4.8975], [52.3695, 4.8955]],\n];\nconst PARKS: Array<Array<[number, number]>> = [\n  // Vondelpark\n  [\n    [52.3612, 4.8795], [52.3601, 4.8805], [52.3578, 4.8725], [52.3561, 4.8625],\n    [52.3555, 4.858], [52.3567, 4.8575], [52.3585, 4.866], [52.3603, 4.8745],\n  ],\n];\n\n// Plot: reads only data and the constants above\nconst sortedRows = [...data].sort(\n  (a, b) => Number(a[SEQUENCE]) - Number(b[SEQUENCE]),\n);\nconst nWaypoints = sortedRows.length;\nconst lats = sortedRows.map((d) => Number(d[LAT]));\nconst lons = sortedRows.map((d) => Number(d[LON]));\nconst progressVals = sortedRows.map((d) => Number(d[PROGRESS]));\nconst minProgress = Math.min(...progressVals);\nconst maxProgress = Math.max(...progressVals);\n\nconst minLat = Math.min(...lats);\nconst maxLat = Math.max(...lats);\nconst minLon = Math.min(...lons);\nconst maxLon = Math.max(...lons);\nconst meanLatRad = (((minLat + maxLat) / 2) * Math.PI) / 180;\nconst cosMeanLat = Math.cos(meanLatRad);\n\nconst { width: canvasW, height: canvasH } = window.ANYPLOT_SIZE;\nconst chartH = canvasH - TITLE_HEIGHT - CAPTION_HEIGHT;\nconst drawW = canvasW - MARGIN.left - MARGIN.right - Y_AXIS_WIDTH;\nconst drawH = chartH - MARGIN.top - MARGIN.bottom - X_AXIS_HEIGHT;\nconst targetAspect = drawW / drawH;\n\nconst rawLonSpan = (maxLon - minLon) * (1 + 2 * PAD_SHARE);\nconst rawLatSpan = (maxLat - minLat) * (1 + 2 * PAD_SHARE);\nconst rawGroundAspect = (rawLonSpan * cosMeanLat) / rawLatSpan;\n\nconst finalLonSpan =\n  rawGroundAspect >= targetAspect\n    ? rawLonSpan\n    : (rawLatSpan * targetAspect) / cosMeanLat;\nconst finalLatSpan =\n  rawGroundAspect >= targetAspect\n    ? (rawLonSpan * cosMeanLat) / targetAspect\n    : rawLatSpan;\n\nconst centerLon = (minLon + maxLon) / 2;\nconst centerLat = (minLat + maxLat) / 2;\nconst xAxisMin = centerLon - finalLonSpan / 2;\nconst xAxisMax = centerLon + finalLonSpan / 2;\nconst yAxisMin = centerLat - finalLatSpan / 2;\nconst yAxisMax = centerLat + finalLatSpan / 2;\n\nconst startColor = t.palette[0];\nconst endColor = t.palette[4];\n\nconst waterColor = t.seq[t.seq.length - 1];\nconst parkColor = t.seq[0];\n\nfunction Basemap() {\n  const { left, top, width, height } = useDrawingArea();\n  const xScale = useXScale(\"lon\") as (v: number) => number;\n  const yScale = useYScale(\"lat\") as (v: number) => number;\n  const toPath = (coords: Array<[number, number]>, closed: boolean) =>\n    coords\n      .map(([la, lo], i) => `${i === 0 ? \"M\" : \"L\"}${xScale(lo).toFixed(1)},${yScale(la).toFixed(1)}`)\n      .join(\" \") + (closed ? \" Z\" : \"\");\n\n  // Canal ring: half-moon arcs opening towards the IJ, in ground-true proportions\n  const canalArcs = CANAL_RING_RADII.map((r) => {\n    const arc: Array<[number, number]> = [];\n    for (let deg = -12; deg <= 192; deg += 4) {\n      const a = (deg * Math.PI) / 180;\n      arc.push([RING_CENTER[0] - r * Math.sin(a) * 0.85, RING_CENTER[1] + (r * Math.cos(a)) / cosMeanLat]);\n    }\n    return arc;\n  });\n\n  return (\n    <g>\n      <defs>\n        <clipPath id=\"basemap-clip\">\n          <rect x={left} y={top} width={width} height={height} />\n        </clipPath>\n      </defs>\n      <g clipPath=\"url(#basemap-clip)\">\n        {PARKS.map((poly, i) => (\n          <path key={`park-${i}`} d={toPath(poly, true)} fill={parkColor} fillOpacity={0.12} stroke=\"none\" />\n        ))}\n        {WATER_AREAS.map((poly, i) => (\n          <path key={`water-${i}`} d={toPath(poly, true)} fill={waterColor} fillOpacity={0.13} stroke=\"none\" />\n        ))}\n        {canalArcs.map((arc, i) => (\n          <path\n            key={`canal-${i}`}\n            d={toPath(arc, false)}\n            fill=\"none\"\n            stroke={waterColor}\n            strokeOpacity={0.2}\n            strokeWidth={i === CANAL_RING_RADII.length - 1 ? 7 : 4}\n            strokeLinecap=\"round\"\n          />\n        ))}\n        {RIVERS.map((line, i) => (\n          <path\n            key={`river-${i}`}\n            d={toPath(line, false)}\n            fill=\"none\"\n            stroke={waterColor}\n            strokeOpacity={0.2}\n            strokeWidth={10}\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n          />\n        ))}\n      </g>\n    </g>\n  );\n}\n\nfunction RouteOverlay() {\n  const { left, top, width } = useDrawingArea();\n  const xScale = useXScale(\"lon\") as (v: number) => number;\n  const yScale = useYScale(\"lat\") as (v: number) => number;\n  const zColorScale = useZColorScale(\"seqAxis\") as (v: number) => string;\n\n  const pts = sortedRows.map((row) => ({\n    x: xScale(Number(row[LON])),\n    y: yScale(Number(row[LAT])),\n    progress: Number(row[PROGRESS]),\n    color: zColorScale(Number(row[PROGRESS])),\n    landmark: String(row[LANDMARK]),\n    lat: Number(row[LAT]),\n    lon: Number(row[LON]),\n  }));\n\n  // Points sampled densely along the route, used to keep landmark labels off the line\n  const routeSamples = pts.slice(0, -1).flatMap((p, i) =>\n    [0, 0.25, 0.5, 0.75].map((f) => [p.x + (pts[i + 1].x - p.x) * f, p.y + (pts[i + 1].y - p.y) * f]),\n  );\n  const startPt = pts[0];\n  const endPt = pts[pts.length - 1];\n  const startLabel = startPt.landmark || \"Start\";\n  const endLabel = endPt.landmark || \"End\";\n\n  // Compass rose in top-right corner of drawing area\n  const roseCx = left + width - 38;\n  const roseCy = top + 46;\n  const roseR = 16;\n\n  // Right-side legend panel\n  const legX = left + width + 24;\n  const legY = top + 16;\n  const barW = 190;\n  const barH = 14;\n\n  return (\n    <g>\n      <defs>\n        <linearGradient id=\"route-seq-grad\" x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"0%\">\n          {t.seq.map((stop: string, idx: number) => (\n            <stop\n              key={stop}\n              offset={`${(idx / (t.seq.length - 1)) * 100}%`}\n              stopColor={stop}\n            />\n          ))}\n        </linearGradient>\n      </defs>\n\n      {/* Halo under route path for contrast against grid */}\n      <path\n        d={pts.map((p, i) => `${i === 0 ? \"M\" : \"L\"}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(\" \")}\n        fill=\"none\"\n        stroke={t.pageBg}\n        strokeWidth={7}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n      />\n\n      {/* Sequential color-coded route segments */}\n      {pts.slice(0, -1).map((p, i) => {\n        const next = pts[i + 1];\n        return (\n          <line\n            key={`seg-${i}`}\n            x1={p.x}\n            y1={p.y}\n            x2={next.x}\n            y2={next.y}\n            stroke={p.color}\n            strokeWidth={4}\n            strokeLinecap=\"round\"\n          />\n        );\n      })}\n\n      {/* Direction chevrons along the trajectory */}\n      {pts.slice(0, -1).map((p, i) => {\n        if (i === 0 || i % ARROW_STRIDE !== 4) return null;\n        const next = pts[i + 1];\n        const mx = (p.x + next.x) / 2;\n        const my = (p.y + next.y) / 2;\n        const angleDeg = (Math.atan2(next.y - p.y, next.x - p.x) * 180) / Math.PI;\n        return (\n          <g key={`arrow-${i}`} transform={`translate(${mx}, ${my}) rotate(${angleDeg})`}>\n            <polygon\n              points=\"10,0 -8,-7.5 -4,0 -8,7.5\"\n              fill={t.ink}\n              stroke={t.pageBg}\n              strokeWidth={1.5}\n              strokeLinejoin=\"round\"\n            />\n          </g>\n        );\n      })}\n\n      {/* Waypoint dots */}\n      {pts.slice(1, -1).map((p, i) => {\n        const isLandmark = p.landmark !== \"\";\n        return (\n          <circle\n            key={`wp-${i}`}\n            cx={p.x}\n            cy={p.y}\n            r={isLandmark ? 4.8 : 2.8}\n            fill={p.color}\n            stroke={t.pageBg}\n            strokeWidth={isLandmark ? 1.8 : 1}\n          />\n        );\n      })}\n\n      {/* Intermediate landmark labels derived from LANDMARK column */}\n      {pts.slice(1, -1).map((p, i) => {\n        if (!p.landmark) return null;\n        // Try 8 positions around the waypoint; keep the one whose text box lies farthest from the route\n        const labelW = p.landmark.length * 7.6;\n        let best = { score: -Infinity, nx: 0, ny: 0, anchor: \"middle\" as \"start\" | \"middle\" | \"end\" };\n        for (let k = 0; k < 8; k++) {\n          const a = (k * Math.PI) / 4;\n          const nx = Math.cos(a);\n          const ny = Math.sin(a);\n          const anchor = nx < -0.3 ? \"end\" : nx > 0.3 ? \"start\" : \"middle\";\n          const bx = p.x + nx * LABEL_OFFSET;\n          const x0 = anchor === \"end\" ? bx - labelW : anchor === \"middle\" ? bx - labelW / 2 : bx;\n          const y1 = p.y + ny * LABEL_OFFSET + 5;\n          const y0 = y1 - 14;\n          const score = Math.min(\n            ...routeSamples.map(([sx, sy]) =>\n              Math.hypot(Math.max(x0 - sx, 0, sx - x0 - labelW), Math.max(y0 - sy, 0, sy - y1)),\n            ),\n          );\n          if (score > best.score) best = { score, nx, ny, anchor };\n        }\n        return (\n          <text\n            key={`lm-${i}`}\n            x={p.x + best.nx * LABEL_OFFSET}\n            y={p.y + best.ny * LABEL_OFFSET + 5}\n            textAnchor={best.anchor}\n            fontSize={14}\n            fontWeight={500}\n            fill={t.inkSoft}\n            stroke={t.pageBg}\n            strokeWidth={3.5}\n            paintOrder=\"stroke\"\n          >\n            {p.landmark}\n          </text>\n        );\n      })}\n\n      {/* Start marker (circle) and callout */}\n      <circle\n        cx={startPt.x}\n        cy={startPt.y}\n        r={9.5}\n        fill={startColor}\n        stroke={t.pageBg}\n        strokeWidth={2.5}\n      />\n      <text\n        x={startPt.x - 15}\n        y={startPt.y + 5}\n        textAnchor=\"end\"\n        fontSize={15}\n        fontWeight={700}\n        fill={t.ink}\n        stroke={t.pageBg}\n        strokeWidth={4}\n        paintOrder=\"stroke\"\n      >\n        {startLabel}\n      </text>\n\n      {/* End marker (square) and callout */}\n      <rect\n        x={endPt.x - 9}\n        y={endPt.y - 9}\n        width={18}\n        height={18}\n        rx={2.5}\n        fill={endColor}\n        stroke={t.pageBg}\n        strokeWidth={2.5}\n      />\n      <text\n        x={endPt.x + 15}\n        y={endPt.y - 10}\n        textAnchor=\"start\"\n        fontSize={15}\n        fontWeight={700}\n        fill={t.ink}\n        stroke={t.pageBg}\n        strokeWidth={4}\n        paintOrder=\"stroke\"\n      >\n        {endLabel}\n      </text>\n\n      {/* Geographic compass rose */}\n      <g>\n        <circle\n          cx={roseCx}\n          cy={roseCy}\n          r={roseR + 4}\n          fill={t.elevatedBg}\n          stroke={t.grid}\n          strokeWidth={1}\n        />\n        <polygon\n          points={`${roseCx},${roseCy - roseR} ${roseCx - 5},${roseCy + 4} ${roseCx},${roseCy} ${roseCx + 5},${roseCy + 4}`}\n          fill={t.ink}\n        />\n        <text\n          x={roseCx}\n          y={roseCy - roseR - 8}\n          textAnchor=\"middle\"\n          fontSize={14}\n          fontWeight={700}\n          fill={t.ink}\n        >\n          N\n        </text>\n      </g>\n\n      {/* Right-side legend panel */}\n      <g transform={`translate(${legX}, ${legY})`}>\n        <text x={0} y={14} fontSize={15} fontWeight={700} fill={t.ink}>\n          Route endpoints\n        </text>\n        <g transform=\"translate(0, 34)\">\n          <circle cx={9} cy={0} r={8} fill={startColor} stroke={t.pageBg} strokeWidth={2} />\n          <text x={26} y={5} fontSize={14} fill={t.ink}>\n            {startLabel}\n          </text>\n        </g>\n        <g transform=\"translate(0, 64)\">\n          <rect\n            x={1}\n            y={-8}\n            width={16}\n            height={16}\n            rx={2}\n            fill={endColor}\n            stroke={t.pageBg}\n            strokeWidth={2}\n          />\n          <text x={26} y={5} fontSize={14} fill={t.ink}>\n            {endLabel}\n          </text>\n        </g>\n        <g transform=\"translate(0, 94)\">\n          <polygon points=\"17,0 2,-6.5 5.5,0 2,6.5\" fill={t.ink} />\n          <text x={26} y={5} fontSize={14} fill={t.ink}>\n            Travel direction\n          </text>\n          <text x={26} y={24} fontSize={14} fill={t.inkSoft}>\n            {`${nWaypoints} waypoints in sequence`}\n          </text>\n        </g>\n\n        <text x={0} y={162} fontSize={15} fontWeight={700} fill={t.ink}>\n          Basemap\n        </text>\n        <g transform=\"translate(0, 184)\">\n          <rect x={1} y={-8} width={16} height={16} rx={2} fill={waterColor} fillOpacity={0.25} />\n          <text x={26} y={5} fontSize={14} fill={t.ink}>\n            Water · canals\n          </text>\n        </g>\n        <g transform=\"translate(0, 212)\">\n          <rect x={1} y={-8} width={16} height={16} rx={2} fill={parkColor} fillOpacity={0.22} />\n          <text x={26} y={5} fontSize={14} fill={t.ink}>\n            Park\n          </text>\n        </g>\n\n        <g transform=\"translate(0, 262)\">\n          <text x={0} y={0} fontSize={15} fontWeight={700} fill={t.ink}>\n            {PROGRESS}\n          </text>\n          <rect\n            x={0}\n            y={12}\n            width={barW}\n            height={barH}\n            rx={3}\n            fill=\"url(#route-seq-grad)\"\n            stroke={t.grid}\n            strokeWidth={1}\n          />\n          <text x={0} y={44} fontSize={14} fill={t.inkSoft}>\n            {`${minProgress.toFixed(2)} (Early)`}\n          </text>\n          <text x={barW} y={44} textAnchor=\"end\" fontSize={14} fill={t.inkSoft}>\n            {`${maxProgress.toFixed(2)} (Late)`}\n          </text>\n        </g>\n      </g>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div\n      style={{\n        width: canvasW,\n        height: canvasH,\n        backgroundColor: t.pageBg,\n        display: \"flex\",\n        flexDirection: \"column\",\n        fontFamily: \"Inter, system-ui, sans-serif\",\n      }}\n    >\n      <div\n        style={{\n          height: TITLE_HEIGHT,\n          display: \"flex\",\n          alignItems: \"center\",\n          justifyContent: \"center\",\n          fontSize: 22,\n          fontWeight: 600,\n          color: t.ink,\n        }}\n      >\n        {TITLE}\n      </div>\n      <ChartsContainer\n        width={canvasW}\n        height={chartH}\n        margin={MARGIN}\n        skipAnimation\n        series={[]}\n        xAxis={[\n          {\n            id: \"lon\",\n            scaleType: \"linear\",\n            min: xAxisMin,\n            max: xAxisMax,\n            height: X_AXIS_HEIGHT,\n            label: LON,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            valueFormatter: (v: number) => `${v.toFixed(3)}°`,\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"lat\",\n            scaleType: \"linear\",\n            min: yAxisMin,\n            max: yAxisMax,\n            width: Y_AXIS_WIDTH,\n            label: LAT,\n            labelStyle: { fontSize: 16, fill: t.ink, fontWeight: 500 },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n            valueFormatter: (v: number) => `${v.toFixed(3)}°`,\n          },\n        ]}\n        zAxis={[\n          {\n            id: \"seqAxis\",\n            min: minProgress,\n            max: maxProgress,\n            colorMap: {\n              type: \"continuous\",\n              color: [t.seq[0], t.seq[t.seq.length - 1]],\n            },\n          },\n        ]}\n      >\n        <Basemap />\n        <ChartsGrid horizontal vertical />\n        <RouteOverlay />\n        <ChartsXAxis axisId=\"lon\" />\n        <ChartsYAxis axisId=\"lat\" />\n      </ChartsContainer>\n      <div\n        style={{\n          height: CAPTION_HEIGHT,\n          paddingLeft: MARGIN.left + Y_AXIS_WIDTH,\n          display: \"flex\",\n          alignItems: \"center\",\n          fontSize: 14,\n          color: t.inkSoft,\n        }}\n      >\n        {BASEMAP_CAPTION}\n      </div>\n    </div>\n  );\n}\n"}