const express = require('express');
const app = express();
const { Client } = require('@googlemaps/google-maps-services-js');
const googleMapsClient = new Client({apiKey:"myGoogleApiKey"});
app.use(express.json());
app.get('/calculate-route', async (req, res) => {
const fromLocation = "Galle, Sri Lanka";
const toLocation = "Ella, Sri Lanka";
try {
const directionsResponse = await googleMapsClient.directions({
params: {
origin: fromLocation,
destination: toLocation,
mode: 'walking'
},
timeout: 1000,
});
res.json(directionsResponse.data);
} catch (error) {
console.error('Error calculating route:', error.response.data);
res.status(500).json({ error: 'Failed to calculate route' });
}
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
i am new to node and express. i need to fetch direction data from googles map api and i encounter a problem while fetching the data saying
{"error":"Failed to calculate route"}
I tried to run http://localhost:3001/calculate-route in my local browser to check whether im getting the desired data. but in response i get {"error":"Failed to calculate route"}
i need to data as an object that contains the routes and the steps
Every Map API call needs an API KEY,
Enabled Map Directions API
Get API Key
API Test by Postman
Demo code
Save as
server.jsInstall dependencies
Run server
Access it
Result