elevation.js 8.8 KB

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