Google map api call not fetching data

61 views Asked by At
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

1

There are 1 answers

0
Bench Vue On BEST ANSWER

Every Map API call needs an API KEY,

Enabled Map Directions API

enter image description here

Get API Key

enter image description here

API Test by Postman

https://maps.googleapis.com/maps/api/directions/json?destination=Ella, Sri Lanka&origin=Galle, Sri Lanka&mode=walking&key=[Your API Key]

enter image description here

Demo code

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}`);
});

Install dependencies

npm install @googlemaps/google-maps-services-js express

Run server

node server.js

Access it

http://localhost:3001/calculate-route

Result

enter image description here