elevation.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. const Elevation = (() => {
  2. const CHART_MAX_PTS = 500;
  3. const PAD = { top: 20, right: 16, bottom: 28, left: 46 };
  4. let canvas = null;
  5. let tooltip = null;
  6. let points = null; // full-res flat [{lat,lon,ele,time,dist}]
  7. let chartPts = null; // downsampled
  8. let bounds = null; // computed after draw: {cw,ch,minE,eRange,totDist}
  9. let trackMeta = null; // {name, trackDate, ...} from the track's meta
  10. // ===== Public API =====
  11. function init() {
  12. canvas = document.getElementById('elevation-canvas');
  13. tooltip = document.getElementById('elevation-tooltip');
  14. if (!canvas) return;
  15. canvas.addEventListener('mousemove', onChartMove);
  16. canvas.addEventListener('mouseleave', onChartLeave);
  17. window.addEventListener('resize', () => { if (points) raf(draw); });
  18. }
  19. function setTrack(pts, meta) {
  20. points = pts;
  21. trackMeta = meta || null;
  22. chartPts = downsample(pts, CHART_MAX_PTS);
  23. bounds = null;
  24. raf(draw);
  25. }
  26. function clear() {
  27. points = chartPts = bounds = trackMeta = null;
  28. hideTooltip();
  29. if (canvas) {
  30. canvas.width = canvas.width; // reset context
  31. }
  32. }
  33. // Called by MapView when hovering a point that belongs to the current track.
  34. // Cursor is on the map, so only draw the indicator — the map tooltip is
  35. // already visible and is closer to the cursor than the chart tooltip would be.
  36. function onMapHover(point) {
  37. if (!bounds || !canvas) return;
  38. drawIndicator(point);
  39. hideTooltip();
  40. }
  41. // Called by MapView when hover leaves the current track
  42. function onMapLeave() {
  43. hideTooltip();
  44. if (bounds) draw();
  45. }
  46. // Shared tooltip formatter used by MapView for the Leaflet map tooltip
  47. function formatTooltip(p, meta) {
  48. const dist = p.dist >= 1000
  49. ? (p.dist / 1000).toFixed(2) + ' km'
  50. : Math.round(p.dist) + ' m';
  51. let html = '';
  52. if (meta?.name) {
  53. html += `<div style="font-weight:600;margin-bottom:2px">${escHtml(meta.name)}</div>`;
  54. }
  55. if (meta?.trackDate) {
  56. const d = new Date(meta.trackDate);
  57. if (!isNaN(d)) html += `<div style="color:rgba(255,255,255,0.75);margin-bottom:4px">${d.toLocaleDateString()}</div>`;
  58. }
  59. html += `<div><b>Dist:</b> ${dist}</div>`;
  60. if (p.ele != null) html += `<div><b>Ele:</b> ${Math.round(p.ele)} m</div>`;
  61. if (p.time) {
  62. const t = new Date(p.time);
  63. if (!isNaN(t)) {
  64. html += `<div><b>Time:</b> ${t.toLocaleTimeString(undefined,
  65. { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</div>`;
  66. }
  67. }
  68. html += `<div style="color:rgba(255,255,255,0.6)">${p.lat.toFixed(5)}, ${p.lon.toFixed(5)}</div>`;
  69. return html;
  70. }
  71. // ===== Internal =====
  72. function raf(fn) {
  73. requestAnimationFrame(() => requestAnimationFrame(fn));
  74. }
  75. function downsample(pts, max) {
  76. if (pts.length <= max) return pts;
  77. const out = [];
  78. const step = (pts.length - 1) / (max - 1);
  79. for (let i = 0; i < max; i++) out.push(pts[Math.round(i * step)]);
  80. return out;
  81. }
  82. // ===== Chart drawing =====
  83. function draw() {
  84. if (!canvas || !chartPts || chartPts.length === 0) return;
  85. const rect = canvas.getBoundingClientRect();
  86. if (!rect.width || !rect.height) return;
  87. const dpr = window.devicePixelRatio || 1;
  88. canvas.width = rect.width * dpr;
  89. canvas.height = rect.height * dpr;
  90. const ctx = canvas.getContext('2d');
  91. ctx.scale(dpr, dpr); // from here on, all coords are CSS pixels
  92. ctx.clearRect(0, 0, rect.width, rect.height);
  93. const hasEle = chartPts.some(p => p.ele != null);
  94. if (!hasEle) {
  95. ctx.fillStyle = '#95a5a6';
  96. ctx.font = '11px sans-serif';
  97. ctx.textAlign = 'center';
  98. ctx.fillText('No elevation data', rect.width / 2, rect.height / 2);
  99. bounds = null;
  100. return;
  101. }
  102. const cw = rect.width - PAD.left - PAD.right;
  103. const ch = rect.height - PAD.top - PAD.bottom;
  104. const eles = chartPts.map(p => p.ele).filter(e => e != null);
  105. const minE = Math.min(...eles);
  106. const maxE = Math.max(...eles);
  107. const eRange = maxE - minE || 1;
  108. const totDist = chartPts[chartPts.length - 1].dist;
  109. drawGrid(ctx, rect, cw, ch, minE, maxE, eRange, totDist);
  110. drawProfile(ctx, cw, ch, minE, eRange, totDist);
  111. bounds = { cw, ch, minE, maxE, eRange, totDist };
  112. }
  113. function drawGrid(ctx, rect, cw, ch, minE, maxE, eRange, totDist) {
  114. ctx.strokeStyle = '#e8e8e8';
  115. ctx.lineWidth = 1;
  116. ctx.fillStyle = '#999';
  117. ctx.font = '10px sans-serif';
  118. // Horizontal grid + elevation labels
  119. for (let i = 0; i <= 4; i++) {
  120. const y = PAD.top + ch * i / 4;
  121. ctx.beginPath();
  122. ctx.moveTo(PAD.left, y);
  123. ctx.lineTo(PAD.left + cw, y);
  124. ctx.stroke();
  125. ctx.textAlign = 'right';
  126. ctx.fillText(Math.round(maxE - eRange * i / 4) + 'm', PAD.left - 4, y + 3);
  127. }
  128. // Distance labels
  129. ctx.textAlign = 'center';
  130. for (let i = 0; i <= 5; i++) {
  131. const x = PAD.left + cw * i / 5;
  132. const d = totDist * i / 5;
  133. const label = d >= 1000 ? (d / 1000).toFixed(1) + 'k' : Math.round(d) + 'm';
  134. ctx.fillText(label, x, rect.height - 5);
  135. }
  136. }
  137. function drawProfile(ctx, cw, ch, minE, eRange, totDist) {
  138. const toX = p => PAD.left + (p.dist / totDist) * cw;
  139. const toY = p => PAD.top + ch - ((p.ele - minE) / eRange) * ch;
  140. // Gradient fill
  141. const grad = ctx.createLinearGradient(0, PAD.top, 0, PAD.top + ch);
  142. grad.addColorStop(0, 'rgba(52,152,219,0.55)');
  143. grad.addColorStop(1, 'rgba(52,152,219,0.07)');
  144. ctx.beginPath();
  145. let first = true;
  146. for (const p of chartPts) {
  147. if (p.ele == null) continue;
  148. if (first) { ctx.moveTo(toX(p), toY(p)); first = false; }
  149. else ctx.lineTo(toX(p), toY(p));
  150. }
  151. ctx.lineTo(PAD.left + cw, PAD.top + ch);
  152. ctx.lineTo(PAD.left, PAD.top + ch);
  153. ctx.closePath();
  154. ctx.fillStyle = grad;
  155. ctx.fill();
  156. // Profile line
  157. ctx.beginPath();
  158. ctx.strokeStyle = '#3498db';
  159. ctx.lineWidth = 1.5;
  160. first = true;
  161. for (const p of chartPts) {
  162. if (p.ele == null) continue;
  163. if (first) { ctx.moveTo(toX(p), toY(p)); first = false; }
  164. else ctx.lineTo(toX(p), toY(p));
  165. }
  166. ctx.stroke();
  167. }
  168. // Draw a vertical cursor + dot at the given point (CSS pixel coords)
  169. function drawIndicator(point) {
  170. if (!bounds || !canvas) return;
  171. draw(); // resets canvas and re-applies ctx.scale(dpr,dpr) — use CSS px below
  172. const { cw, ch, minE, eRange, totDist } = bounds;
  173. const ctx = canvas.getContext('2d');
  174. const x = PAD.left + (point.dist / totDist) * cw;
  175. const y = point.ele != null
  176. ? PAD.top + ch - ((point.ele - minE) / eRange) * ch
  177. : PAD.top + ch / 2;
  178. ctx.save();
  179. // Vertical dashed line
  180. ctx.strokeStyle = 'rgba(231,76,60,0.55)';
  181. ctx.lineWidth = 1;
  182. ctx.setLineDash([4, 4]);
  183. ctx.beginPath();
  184. ctx.moveTo(x, PAD.top);
  185. ctx.lineTo(x, PAD.top + ch);
  186. ctx.stroke();
  187. ctx.setLineDash([]);
  188. // Dot
  189. ctx.fillStyle = '#e74c3c';
  190. ctx.strokeStyle = 'white';
  191. ctx.lineWidth = 1.5;
  192. ctx.beginPath();
  193. ctx.arc(x, y, 4, 0, Math.PI * 2);
  194. ctx.fill();
  195. ctx.stroke();
  196. ctx.restore();
  197. }
  198. // ===== Hover =====
  199. function onChartMove(e) {
  200. if (!bounds || !chartPts) return;
  201. const rect = canvas.getBoundingClientRect();
  202. const x = e.clientX - rect.left;
  203. if (x < PAD.left || x > PAD.left + bounds.cw) {
  204. onChartLeave();
  205. return;
  206. }
  207. const dist = ((x - PAD.left) / bounds.cw) * bounds.totDist;
  208. // Find nearest downsampled point for chart indicator
  209. const chartPt = findNearestByDist(chartPts, dist);
  210. // Find nearest full-res point for map marker
  211. const fullPt = findNearestByDist(points, dist);
  212. if (!chartPt) return;
  213. drawIndicator(chartPt);
  214. positionTooltip(chartPt, x, e.clientY - rect.top);
  215. // Cursor is on the chart, so move the map marker without a Leaflet tooltip —
  216. // the chart tooltip is already visible and is closer to the cursor.
  217. if (fullPt && typeof MapView !== 'undefined') {
  218. MapView.showHoverMarker(fullPt.lat, fullPt.lon, fullPt, trackMeta, true);
  219. }
  220. }
  221. function onChartLeave() {
  222. hideTooltip();
  223. if (typeof MapView !== 'undefined') MapView.hideHoverMarker();
  224. if (bounds) draw();
  225. }
  226. function findNearestByDist(pts, targetDist) {
  227. if (!pts || pts.length === 0) return null;
  228. let nearest = null, nearestD = Infinity;
  229. for (const p of pts) {
  230. const d = Math.abs(p.dist - targetDist);
  231. if (d < nearestD) { nearestD = d; nearest = p; }
  232. }
  233. return nearest;
  234. }
  235. function positionTooltip(point, cx, cy) {
  236. if (!tooltip || !canvas) return;
  237. tooltip.innerHTML = formatTooltip(point, trackMeta);
  238. tooltip.classList.add('visible');
  239. const cRect = canvas.getBoundingClientRect();
  240. const tw = tooltip.offsetWidth;
  241. const th = tooltip.offsetHeight;
  242. const gap = 8;
  243. // Prefer above cursor; fall back to below if not enough room
  244. const topAbove = cy - th - gap;
  245. const top = topAbove >= 0 ? topAbove : cy + gap;
  246. // Prefer right of indicator; clamp to canvas bounds
  247. const leftRight = cx + gap;
  248. const left = Math.min(leftRight, cRect.width - tw - 4);
  249. tooltip.style.left = Math.max(0, left) + 'px';
  250. tooltip.style.top = top + 'px';
  251. }
  252. function hideTooltip() {
  253. if (tooltip) tooltip.classList.remove('visible');
  254. }
  255. return { init, setTrack, clear, formatTooltip, onMapHover, onMapLeave };
  256. })();