UNPKG

visual-route

Version:

A simple package to visualize routes and distances using OpenRouteService API.

94 lines (86 loc) 2.88 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Route Visualizer ORS</title> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" ></script> <script src="https://unpkg.com/axios@1.6.0/dist/axios.min.js"></script> <style> #map { height: 600px; width: 100%; } </style> </head> <body> <h2>Route Visualizer ORS</h2> <div id="map"></div> <script> async function fetchApiKey() { const response = await axios.get('/api/getApiKey'); return response.data.apiKey; } async function geocode(place, apiKey) { const res = await axios.get( `https://api.openrouteservice.org/geocode/search`, { params: { api_key: apiKey, text: place, size: 1, }, } ); return res.data.features[0].geometry.coordinates; // [lng, lat] } async function drawRoute(origin, destination) { const apiKey = await fetchApiKey(); const [originLng, originLat] = await geocode(origin, apiKey); const [destLng, destLat] = await geocode(destination, apiKey); const routeRes = await axios.post( 'https://api.openrouteservice.org/v2/directions/driving-car/geojson', { coordinates: [ [originLng, originLat], [destLng, destLat], ], }, { headers: { Authorization: apiKey, 'Content-Type': 'application/json', }, } ); const distance = ( routeRes.data.features[0].properties.summary.distance / 1000 ).toFixed(2); const duration = ( routeRes.data.features[0].properties.summary.duration / 60 ).toFixed(2); const map = L.map('map').setView([originLat, originLng], 8); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="https://openstreetmap.org">OpenStreetMap</a> contributors', }).addTo(map); L.geoJSON(routeRes.data, { style: { color: 'blue', weight: 4 } }).addTo( map ); L.marker([originLat, originLng]) .addTo(map) .bindPopup(`${origin} <br> Distance: ${distance} km`); L.marker([destLat, destLng]) .addTo(map) .bindPopup(`${destination} <br> Duration: ${duration} mins`); } drawRoute('Delhi', 'Agra'); </script> </body> </html>