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,
https://maps.googleapis.com/maps/api/directions/json?destination=Ella, Sri Lanka&origin=Galle, Sri Lanka&mode=walking&key=[Your API Key]
Save as server.js
const express = require('express');
const app = express();
const { Client } = require('@googlemaps/google-maps-services-js');
const googleMapsClient = new Client();
app.use(express.json());
app.get('/calculate-route', async (req, res) => {
const fromLocation = "Galle, Sri Lanka";
const toLocation = "Ella, Sri Lanka";
const apiKey = "Your API Key"; // Replace with your actual API key
try {
const directionsResponse = await googleMapsClient.directions({
params: {
origin: fromLocation,
destination: toLocation,
mode: 'walking',
key: apiKey
},
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}`);
});
npm install @googlemaps/google-maps-services-js express
node server.js
http://localhost:3001/calculate-route