distance-by-name
Version:
A module to calculate distance and duration between two places using OpenRouteService API.
60 lines (57 loc) • 2.94 kB
JavaScript
const axios = require("axios");
exports.getDistanceByName = async (origin, destination) => {
try {
const apiKey = "5b3ce3597851110001cf6248a6abff523cad4727ac46ea5a903de52d";
if (typeof origin === "string") {
try {
const geocodeUrlOrigin = `https://api.openrouteservice.org/geocode/search?api_key=${apiKey}&text=${encodeURIComponent(origin)}&size=1`;
const geoResOrigin = await axios.get(geocodeUrlOrigin);
if (geoResOrigin.data.features && geoResOrigin.data.features.length > 0) {
origin = geoResOrigin.data.features[0].geometry.coordinates;
} else {
return { status: 0, message: "Origin not found"};
}
} catch (error) {
return { status: 500, message: error };
}
}
if (typeof destination === "string") {
try {
const geocodeUrlDestination = `https://api.openrouteservice.org/geocode/search?api_key=${apiKey}&text=${encodeURIComponent(destination)}&size=1`;
const geoResDestination = await axios.get(geocodeUrlDestination);
if (geoResDestination.data.features && geoResDestination.data.features.length > 0) {
destination = geoResDestination.data.features[0].geometry.coordinates;
} else {
return { status: 0, message: "Destination not found"};
}
} catch (error) {
return { status: 500, message: error };
}
}
const url = `https://api.openrouteservice.org/v2/directions/driving-car`;
const response = await axios.post(url, {
coordinates: [origin, destination]
}, {
headers: {
"Authorization": apiKey,
"Content-Type": "application/json"
}
});
const data = response.data;
if (data.routes && data.routes.length > 0) {
const distance = (data.routes[0].summary.distance / 1000).toFixed(2) + " km"; // meters to km
//const duration = (data.routes[0].summary.duration / 60).toFixed(2) + " mins"; // seconds to mins
const totalSeconds = data.routes[0].summary.duration;
const hours = parseInt(totalSeconds / 3600);
const minutes = parseInt((totalSeconds % 3600) / 60);
const seconds = parseInt(totalSeconds % 60);
const duration = `${hours}h ${minutes}m ${seconds}s`;
// return { distance, duration };
return { status: 1, message: "Find Distance Successfully", result: {distance,duration} };
} else {
return { status: 0, message: "Invalid locations or API error" };
}
} catch (error) {
return { status: 501, message: error };
}
}