{"spec_id":"map-connection-lines","library":"muix","language":"javascript","code":"// anyplot.ai\n// map-connection-lines: Connection Lines Map (Origin-Destination)\n// Library: muix 9.16.0 | JavaScript 22.23.3\n// Quality: 85/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 { ChartsReferenceLine } from \"@mui/x-charts/ChartsReferenceLine\";\nimport { useXScale, useYScale, useDrawingArea } from \"@mui/x-charts/hooks\";\n\nconst t = window.ANYPLOT_TOKENS;\n\n// Constants\nconst TITLE = \"map-connection-lines · javascript · muix · anyplot.ai\";\nconst LON_PAD_FRAC = 0.08;\nconst LAT_PAD_FRAC = 0.15;\nconst ARC_BOW_FACTOR = 0.16;\nconst NEIGHBOR_THRESHOLD_SHARE = 0.045;\n\n// Simplified world coastlines (lon/lat vertices)\nconst CONTINENTS: Array<Array<[number, number]>> = [\n  [\n    [-165, 65], [-140, 60], [-125, 49], [-124, 40], [-117, 32], [-105, 22], [-97, 16],\n    [-90, 14], [-88, 21], [-81, 25], [-80, 32], [-75, 40], [-70, 44], [-65, 47],\n    [-75, 55], [-95, 62], [-110, 68], [-140, 68], [-165, 65],\n  ],\n  [\n    [-77, 8], [-80, 0], [-81, -6], [-71, -18], [-70, -33], [-68, -45], [-68, -54],\n    [-65, -52], [-58, -38], [-48, -25], [-40, -13], [-35, -6], [-50, 0], [-60, 8],\n    [-72, 10], [-77, 8],\n  ],\n  [\n    [-9, 43], [-9, 37], [3, 36], [10, 44], [15, 38], [20, 40], [28, 41], [30, 46],\n    [38, 55], [30, 60], [10, 58], [5, 51], [-1, 51], [-5, 55], [-9, 43],\n  ],\n  [\n    [-17, 21], [-17, 14], [-10, 6], [3, 6], [9, 4], [13, -6], [18, -34], [26, -33],\n    [35, -20], [40, -3], [45, 11], [43, 12], [38, 15], [32, 31], [10, 37], [-6, 35],\n    [-17, 21],\n  ],\n  [\n    [27, 41], [35, 30], [42, 13], [56, 25], [61, 25], [72, 19], [77, 8], [80, 13],\n    [88, 22], [96, 16], [100, 13], [104, 10], [109, 21], [121, 25], [122, 31],\n    [130, 38], [140, 36], [142, 43], [135, 50], [100, 55], [60, 55], [48, 42],\n    [35, 45], [27, 41],\n  ],\n  [\n    [113, -22], [115, -32], [131, -12], [142, -11], [145, -17], [153, -28],\n    [151, -34], [140, -38], [135, -35], [113, -22],\n  ],\n];\n\n// Columns: set these to your data's column names\nconst ORIGIN_CODE = \"Origin airport\"; // role: label\nconst ORIGIN_LAT = \"Origin latitude (°)\"; // role: origin_lat\nconst ORIGIN_LON = \"Origin longitude (°)\"; // role: origin_lon\nconst DEST_CODE = \"Destination airport\"; // role: dest_label\nconst DEST_LAT = \"Destination latitude (°)\"; // role: dest_lat\nconst DEST_LON = \"Destination longitude (°)\"; // role: dest_lon\nconst PASSENGERS = \"Annual passengers (thousands)\"; // role: value\n\n// Data: replace this block with your own records\nconst data: Array<Record<string, string | number>> = [\n  { [ORIGIN_CODE]: \"JFK\", [ORIGIN_LAT]: 40.64, [ORIGIN_LON]: -73.78, [DEST_CODE]: \"LHR\", [DEST_LAT]: 51.47, [DEST_LON]: -0.45, [PASSENGERS]: 820 },\n  { [ORIGIN_CODE]: \"JFK\", [ORIGIN_LAT]: 40.64, [ORIGIN_LON]: -73.78, [DEST_CODE]: \"CDG\", [DEST_LAT]: 49.01, [DEST_LON]: 2.55, [PASSENGERS]: 610 },\n  { [ORIGIN_CODE]: \"LAX\", [ORIGIN_LAT]: 33.94, [ORIGIN_LON]: -118.41, [DEST_CODE]: \"NRT\", [DEST_LAT]: 35.76, [DEST_LON]: 140.39, [PASSENGERS]: 540 },\n  { [ORIGIN_CODE]: \"LAX\", [ORIGIN_LAT]: 33.94, [ORIGIN_LON]: -118.41, [DEST_CODE]: \"SYD\", [DEST_LAT]: -33.95, [DEST_LON]: 151.18, [PASSENGERS]: 310 },\n  { [ORIGIN_CODE]: \"SFO\", [ORIGIN_LAT]: 37.62, [ORIGIN_LON]: -122.38, [DEST_CODE]: \"HKG\", [DEST_LAT]: 22.31, [DEST_LON]: 113.91, [PASSENGERS]: 460 },\n  { [ORIGIN_CODE]: \"ORD\", [ORIGIN_LAT]: 41.98, [ORIGIN_LON]: -87.9, [DEST_CODE]: \"FRA\", [DEST_LAT]: 50.03, [DEST_LON]: 8.57, [PASSENGERS]: 390 },\n  { [ORIGIN_CODE]: \"DXB\", [ORIGIN_LAT]: 25.25, [ORIGIN_LON]: 55.36, [DEST_CODE]: \"LHR\", [DEST_LAT]: 51.47, [DEST_LON]: -0.45, [PASSENGERS]: 705 },\n  { [ORIGIN_CODE]: \"DXB\", [ORIGIN_LAT]: 25.25, [ORIGIN_LON]: 55.36, [DEST_CODE]: \"JFK\", [DEST_LAT]: 40.64, [DEST_LON]: -73.78, [PASSENGERS]: 480 },\n  { [ORIGIN_CODE]: \"SIN\", [ORIGIN_LAT]: 1.35, [ORIGIN_LON]: 103.99, [DEST_CODE]: \"SYD\", [DEST_LAT]: -33.95, [DEST_LON]: 151.18, [PASSENGERS]: 520 },\n  { [ORIGIN_CODE]: \"SIN\", [ORIGIN_LAT]: 1.35, [ORIGIN_LON]: 103.99, [DEST_CODE]: \"NRT\", [DEST_LAT]: 35.76, [DEST_LON]: 140.39, [PASSENGERS]: 445 },\n  { [ORIGIN_CODE]: \"GRU\", [ORIGIN_LAT]: -23.43, [ORIGIN_LON]: -46.47, [DEST_CODE]: \"JFK\", [DEST_LAT]: 40.64, [DEST_LON]: -73.78, [PASSENGERS]: 385 },\n  { [ORIGIN_CODE]: \"GRU\", [ORIGIN_LAT]: -23.43, [ORIGIN_LON]: -46.47, [DEST_CODE]: \"CDG\", [DEST_LAT]: 49.01, [DEST_LON]: 2.55, [PASSENGERS]: 260 },\n  { [ORIGIN_CODE]: \"JNB\", [ORIGIN_LAT]: -26.13, [ORIGIN_LON]: 28.24, [DEST_CODE]: \"DXB\", [DEST_LAT]: 25.25, [DEST_LON]: 55.36, [PASSENGERS]: 300 },\n  { [ORIGIN_CODE]: \"DEL\", [ORIGIN_LAT]: 28.56, [ORIGIN_LON]: 77.1, [DEST_CODE]: \"LHR\", [DEST_LAT]: 51.47, [DEST_LON]: -0.45, [PASSENGERS]: 560 },\n  { [ORIGIN_CODE]: \"PEK\", [ORIGIN_LAT]: 40.08, [ORIGIN_LON]: 116.58, [DEST_CODE]: \"LAX\", [DEST_LAT]: 33.94, [DEST_LON]: -118.41, [PASSENGERS]: 415 },\n  { [ORIGIN_CODE]: \"HKG\", [ORIGIN_LAT]: 22.31, [ORIGIN_LON]: 113.91, [DEST_CODE]: \"SYD\", [DEST_LAT]: -33.95, [DEST_LON]: 151.18, [PASSENGERS]: 330 },\n];\n\n// Plot: reads only data and the constants above\nconst airportsMap = new Map<\n  string,\n  { code: string; lat: number; lon: number; degree: number }\n>();\nfor (const row of data) {\n  const oCode = String(row[ORIGIN_CODE]);\n  const dCode = String(row[DEST_CODE]);\n  if (!airportsMap.has(oCode)) {\n    airportsMap.set(oCode, {\n      code: oCode,\n      lat: Number(row[ORIGIN_LAT]),\n      lon: Number(row[ORIGIN_LON]),\n      degree: 0,\n    });\n  }\n  if (!airportsMap.has(dCode)) {\n    airportsMap.set(dCode, {\n      code: dCode,\n      lat: Number(row[DEST_LAT]),\n      lon: Number(row[DEST_LON]),\n      degree: 0,\n    });\n  }\n  airportsMap.get(oCode)!.degree += 1;\n  airportsMap.get(dCode)!.degree += 1;\n}\nconst airportList = Array.from(airportsMap.values());\n\nconst passengerValues = data.map((r) => Number(r[PASSENGERS]));\nconst minPassengers = Math.min(...passengerValues);\nconst maxPassengers = Math.max(...passengerValues);\n\nconst lons = airportList.map((a) => a.lon);\nconst lats = airportList.map((a) => a.lat);\nconst rawLonMin = Math.min(...lons);\nconst rawLonMax = Math.max(...lons);\nconst rawLatMin = Math.min(...lats);\nconst rawLatMax = Math.max(...lats);\n\nconst { width: W, height: H } = window.ANYPLOT_SIZE;\nconst MARGIN = { top: 82, right: 56, bottom: 52, left: 22 };\nconst X_AXIS_H = 56;\nconst Y_AXIS_W = 68;\nconst DRAW_W = W - MARGIN.left - MARGIN.right - Y_AXIS_W;\nconst DRAW_H = H - MARGIN.top - MARGIN.bottom - X_AXIS_H;\n\nconst meanLatDeg = (rawLatMin + rawLatMax) / 2;\nconst cosMeanLat = Math.cos((meanLatDeg * Math.PI) / 180);\nconst paddedLonSpan = (rawLonMax - rawLonMin) * (1 + 2 * LON_PAD_FRAC);\nconst paddedLatSpan = (rawLatMax - rawLatMin) * (1 + 2 * LAT_PAD_FRAC);\nconst targetAspect = DRAW_W / DRAW_H;\nconst groundAspect = (paddedLonSpan * cosMeanLat) / paddedLatSpan;\n\n// Routes crossing the antimeridian need the whole globe in frame to stay whole\nconst wrapsAntimeridian = data.some(\n  (r) => Math.abs(Number(r[DEST_LON]) - Number(r[ORIGIN_LON])) > 180,\n);\n\n// Regional data widens longitude to keep the ground aspect; a wide frame keeps\n// the latitude range tight instead of padding it with empty bands\nconst finalLonSpan = wrapsAntimeridian\n  ? 360\n  : groundAspect >= targetAspect\n    ? paddedLonSpan\n    : (paddedLatSpan * targetAspect) / cosMeanLat;\nconst finalLatSpan = paddedLatSpan;\n\nconst lonCenter = wrapsAntimeridian ? 0 : (rawLonMin + rawLonMax) / 2;\nconst latCenter = (rawLatMin + rawLatMax) / 2;\nconst LON_MIN = lonCenter - finalLonSpan / 2;\nconst LON_MAX = lonCenter + finalLonSpan / 2;\nconst LAT_MIN = latCenter - finalLatSpan / 2;\nconst LAT_MAX = latCenter + finalLatSpan / 2;\n\nconst neighborThresholdDeg = finalLonSpan * NEIGHBOR_THRESHOLD_SHARE;\nconst airportLabelOffsets: Record<string, { dx: number; dy: number }> = {};\nfor (const a of airportList) {\n  const radius = 5 + a.degree * 1.8;\n  const neighbors = airportList.filter(\n    (b) =>\n      b.code !== a.code &&\n      Math.hypot((b.lon - a.lon) * cosMeanLat, b.lat - a.lat) <\n        neighborThresholdDeg,\n  );\n  if (neighbors.length === 0) {\n    // Isolated label goes on the side away from where its routes leave\n    const partnerLatShift = data.reduce((s, r) => {\n      if (r[ORIGIN_CODE] === a.code) return s + Number(r[DEST_LAT]) - a.lat;\n      if (r[DEST_CODE] === a.code) return s + Number(r[ORIGIN_LAT]) - a.lat;\n      return s;\n    }, 0);\n    airportLabelOffsets[a.code] =\n      partnerLatShift > 0\n        ? { dx: 0, dy: radius + 20 }\n        : { dx: 0, dy: -(radius + 9) };\n  } else {\n    const meanLon = neighbors.reduce((s, n) => s + n.lon, 0) / neighbors.length;\n    const meanLat = neighbors.reduce((s, n) => s + n.lat, 0) / neighbors.length;\n    const vx = (a.lon - meanLon) * cosMeanLat;\n    const vy = -(a.lat - meanLat);\n    const len = Math.hypot(vx, vy);\n    const dist = radius + 16;\n    airportLabelOffsets[a.code] = {\n      dx: (vx / len) * dist * 1.25,\n      dy: (vy / len) * dist + 4,\n    };\n  }\n}\n\nconst lonUnitMatch = ORIGIN_LON.match(/\\(([^)]+)\\)/);\nconst LON_UNIT = lonUnitMatch ? lonUnitMatch[1] : \"\";\nconst latUnitMatch = ORIGIN_LAT.match(/\\(([^)]+)\\)/);\nconst LAT_UNIT = latUnitMatch ? latUnitMatch[1] : \"\";\n\nfunction ConnectionMapLayer() {\n  const xScale = useXScale(\"lon\") as (v: number) => number;\n  const yScale = useYScale(\"lat\") as (v: number) => number;\n  const drawingArea = useDrawingArea();\n\n  return (\n    <g>\n      <defs>\n        <clipPath id=\"worldClip\">\n          <rect\n            x={drawingArea.left}\n            y={drawingArea.top}\n            width={drawingArea.width}\n            height={drawingArea.height}\n          />\n        </clipPath>\n      </defs>\n\n      {/* Simplified land masses */}\n      <g clipPath=\"url(#worldClip)\">\n        {CONTINENTS.map((points, i) => {\n          const d =\n            points\n              .map(\n                ([lon, lat], j) =>\n                  `${j === 0 ? \"M\" : \"L\"} ${xScale(lon)},${yScale(lat)}`,\n              )\n              .join(\" \") + \" Z\";\n          return (\n            <path\n              key={i}\n              d={d}\n              fill={t.grid}\n              fillOpacity={0.6}\n              stroke={t.inkSoft}\n              strokeWidth={1}\n              strokeOpacity={0.5}\n            />\n          );\n        })}\n\n        {/* Geodesic-style connection arcs (splitting trans-antimeridian routes) */}\n        {data.map((row, i) => {\n          const lon1 = Number(row[ORIGIN_LON]);\n          const lat1 = Number(row[ORIGIN_LAT]);\n          const lon2 = Number(row[DEST_LON]);\n          const lat2 = Number(row[DEST_LAT]);\n\n          const pax = Number(row[PASSENGERS]);\n          const ratio =\n            (pax - minPassengers) / (maxPassengers - minPassengers);\n          const strokeWidth = 3 + ratio * 6;\n          const strokeOpacity = 0.45 + ratio * 0.25;\n\n          const segments: Array<[number, number, number, number]> = [];\n          if (Math.abs(lon2 - lon1) <= 180) {\n            segments.push([lon1, lat1, lon2, lat2]);\n          } else {\n            const lon2Unwrapped = lon2 > lon1 ? lon2 - 360 : lon2 + 360;\n            const edgeLon1 = lon1 < 0 ? -180 : 180;\n            const edgeLon2 = -edgeLon1;\n            const frac = (edgeLon1 - lon1) / (lon2Unwrapped - lon1);\n            const crossLat = lat1 + frac * (lat2 - lat1);\n            segments.push([lon1, lat1, edgeLon1, crossLat]);\n            segments.push([edgeLon2, crossLat, lon2, lat2]);\n          }\n\n          return (\n            <g key={`${row[ORIGIN_CODE]}-${row[DEST_CODE]}-${i}`}>\n              {segments.map(([sLon1, sLat1, sLon2, sLat2], sIdx) => {\n                const x1 = xScale(sLon1);\n                const y1 = yScale(sLat1);\n                const x2 = xScale(sLon2);\n                const y2 = yScale(sLat2);\n                const dx = x2 - x1;\n                const dy = y2 - y1;\n                const dist = Math.hypot(dx, dy);\n                const midX = (x1 + x2) / 2;\n                const midY = (y1 + y2) / 2;\n                const bowSign = y1 + y2 < yScale(0) * 2 ? -1 : 1;\n                const bow = dist * ARC_BOW_FACTOR * bowSign;\n                const controlX = midX;\n                const controlY = midY + bow;\n                return (\n                  <path\n                    key={sIdx}\n                    d={`M ${x1},${y1} Q ${controlX},${controlY} ${x2},${y2}`}\n                    fill=\"none\"\n                    stroke={t.palette[0]}\n                    strokeWidth={strokeWidth}\n                    strokeOpacity={strokeOpacity}\n                    strokeLinecap=\"round\"\n                  />\n                );\n              })}\n            </g>\n          );\n        })}\n      </g>\n\n      {/* Airport endpoint markers and collision-avoiding labels */}\n      {airportList.map((airport) => {\n        const cx = xScale(airport.lon);\n        const cy = yScale(airport.lat);\n        const radius = 5 + airport.degree * 1.8;\n        const nudge = airportLabelOffsets[airport.code];\n        return (\n          <g key={airport.code}>\n            <circle\n              cx={cx}\n              cy={cy}\n              r={radius}\n              fill={t.palette[0]}\n              stroke={t.pageBg}\n              strokeWidth={2}\n            />\n            <text\n              x={cx + nudge.dx}\n              y={cy + nudge.dy}\n              textAnchor=\"middle\"\n              fontSize={14}\n              fontWeight={500}\n              fill={t.ink}\n            >\n              {airport.code}\n            </text>\n          </g>\n        );\n      })}\n\n      {/* Title */}\n      <text\n        x={W / 2}\n        y={36}\n        textAnchor=\"middle\"\n        dominantBaseline=\"hanging\"\n        fontSize={22}\n        fontWeight={500}\n        fill={t.ink}\n      >\n        {TITLE}\n      </text>\n\n      {/* Encoding caption */}\n      <text\n        x={drawingArea.left}\n        y={drawingArea.top + drawingArea.height + 68}\n        textAnchor=\"start\"\n        dominantBaseline=\"hanging\"\n        fontSize={14}\n        fontWeight={400}\n        fill={t.inkSoft}\n      >\n        {`Line thickness and opacity encode ${PASSENGERS}; marker size encodes route degree.`}\n      </text>\n    </g>\n  );\n}\n\nexport default function Chart() {\n  return (\n    <div style={{ width: W, height: H, backgroundColor: t.pageBg }}>\n      <ChartsContainer\n        width={W}\n        height={H}\n        margin={MARGIN}\n        series={[]}\n        skipAnimation\n        disableAxisListener\n        xAxis={[\n          {\n            id: \"lon\",\n            scaleType: \"linear\",\n            min: LON_MIN,\n            max: LON_MAX,\n            height: X_AXIS_H,\n            label: `Longitude (${LON_UNIT})`,            valueFormatter: (v: number | null) =>\n              v === null ? \"\" : `${Math.round(v)}${LON_UNIT}`,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n        yAxis={[\n          {\n            id: \"lat\",\n            scaleType: \"linear\",\n            min: LAT_MIN,\n            max: LAT_MAX,\n            width: Y_AXIS_W,\n            label: `Latitude (${LAT_UNIT})`,\n            valueFormatter: (v: number | null) =>\n              v === null ? \"\" : `${Math.round(v)}${LAT_UNIT}`,\n            labelStyle: { fontSize: 16, fill: t.ink },\n            tickLabelStyle: { fontSize: 14, fill: t.inkSoft },\n          },\n        ]}\n      >\n        <ChartsGrid horizontal vertical />\n        <ChartsReferenceLine\n          y={0}\n          axisId=\"lat\"\n          label=\"Equator\"\n          labelAlign=\"end\"\n          lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"6 6\", strokeOpacity: 0.6 }}\n          labelStyle={{ fontSize: 14, fill: t.inkSoft }}\n        />\n        <ChartsReferenceLine\n          x={0}\n          axisId=\"lon\"\n          label=\"Prime Meridian\"\n          labelAlign=\"start\"\n          lineStyle={{ stroke: t.inkSoft, strokeDasharray: \"6 6\", strokeOpacity: 0.6 }}\n          labelStyle={{ fontSize: 14, fill: t.inkSoft }}\n        />\n        <ConnectionMapLayer />\n        <ChartsXAxis axisId=\"lon\" />\n        <ChartsYAxis axisId=\"lat\" />\n      </ChartsContainer>\n    </div>\n  );\n}\n"}