UNPKG

distance-calculator-openrouteservice

Version:

A free Node.js library to calculate distance between places using OpenRouteService.

50 lines (40 loc) 1.22 kB
import axios from 'axios'; import dotenv from 'dotenv'; // Load environment variables dotenv.config(); const API_KEY = process.env.ORS_API_KEY; async function geocodePlace(place) { const response = await axios.get('https://api.openrouteservice.org/geocode/search', { params: { api_key: API_KEY, text: place, size: 1 } }); const coords = response.data.features[0]?.geometry?.coordinates; return coords ? [coords[0], coords[1]] : null; } async function getDistance(from, to, mode = 'driving-car') { if (typeof from === 'string') from = await geocodePlace(from); if (typeof to === 'string') to = await geocodePlace(to); if (!from || !to) throw new Error('Invalid location provided'); const response = await axios.post( `https://api.openrouteservice.org/v2/directions/${mode}`, { coordinates: [from, to] }, { headers: { Authorization: API_KEY, 'Content-Type': 'application/json' } } ); const { distance, duration } = response.data.routes[0].summary; return { distance_km: (distance / 1000).toFixed(2), duration_minutes: (duration / 60).toFixed(2), mode, from, to }; } export default getDistance;