const canvas = document.getElementById("map"); const ctx = canvas.getContext("2d"); let zoomLevel = 1; let offsetX = 0; let offsetY = 0; /* * -------------------------------- * zoom(n_times) * -------------------------------- */ function zoom(n_times) { zoomLevel = Math.max( 0.25, Math.min(30, n_times) ); vykresliMapu(); } /* * -------------------------------- * GPS → Canvas * -------------------------------- */ function gpsToCanvas(lon, lat) { const x = (lon - mapa.bounds.minLon) * mapaScale; const y = (mapa.bounds.maxLat - lat) * mapaScale; return { x, y }; } /* * -------------------------------- * Vykreslenie mapy * -------------------------------- */ function vykresliMapu() { /* * Reset transformácie */ ctx.setTransform( 1, 0, 0, 1, 0, 0 ); ctx.clearRect( 0, 0, canvas.width, canvas.height ); /* * Zoom + posun */ ctx.setTransform( zoomLevel, 0, 0, zoomLevel, offsetX, offsetY ); /* * Cesty */ for (const road of mapa.roads) { if (!road.nodes) { continue; } ctx.beginPath(); road.nodes.forEach( (node, index) => { const p = gpsToCanvas( node.lon, node.lat ); if (index === 0) { ctx.moveTo( p.x, p.y ); } else { ctx.lineTo( p.x, p.y ); } } ); /* * Typ cesty */ switch (road.highway) { case "motorway": ctx.lineWidth = 5; break; case "primary": ctx.lineWidth = 4; break; case "secondary": ctx.lineWidth = 3; break; case "tertiary": ctx.lineWidth = 2; break; default: ctx.lineWidth = 1; } ctx.strokeStyle = "#777"; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.stroke(); } /* * -------------------------------- * Trasa * -------------------------------- */ if ( mapa.route && mapa.route.points ) { ctx.beginPath(); mapa.route.points.forEach( (point, index) => { const p = gpsToCanvas( point.lon, point.lat ); if (index === 0) { ctx.moveTo( p.x, p.y ); } else { ctx.lineTo( p.x, p.y ); } } ); ctx.lineWidth = 8; ctx.strokeStyle = "red"; ctx.lineCap = "round"; ctx.lineJoin = "round"; ctx.stroke(); } /* * -------------------------------- * START * -------------------------------- */ const start = gpsToCanvas( mapa.start.lon, mapa.start.lat ); ctx.beginPath(); ctx.arc( start.x, start.y, 7, 0, Math.PI * 2 ); ctx.fillStyle = "green"; ctx.fill(); /* * -------------------------------- * CIEĽ * -------------------------------- */ const end = gpsToCanvas( mapa.end.lon, mapa.end.lat ); ctx.beginPath(); ctx.arc( end.x, end.y, 7, 0, Math.PI * 2 ); ctx.fillStyle = "red"; ctx.fill(); } zoom(4); canvas.addEventListener( "wheel", function(e) { e.preventDefault(); if (e.deltaY < 0) { zoomLevel *= 1.2; } else { zoomLevel /= 1.2; } zoomLevel = Math.max( 0.5, Math.min(30, zoomLevel) ); vykresliMapu(); }, { passive: false } );