skip to Main Content

I’m using the Google Maps API Node Client and calling the distancematrix function, but I’m getting an error that says o.map is not a function.

const {Client} = require("@googlemaps/google-maps-services-js")
const client = new Client

client.distancematrix({
    params: {
        origins: '40,40',
        destinations: '40,41',
        key: process.env.GOOGLE_MAPS_API_KEY
    }
})
.then((r) => {
    console.log(r.data.rows)
})
.catch((e) => {
    console.log(e)
})

I tried looking at the Google Maps services code. I found o.map at line 174 at this link.

2

Answers


  1. Based on this given Google Maps service code, you have to pass the origins & destinations as an array of [lat, lang] values. As you are passing it as a string and string doesn’t have the function call map(), it is throwing an error as o.map is not a function. Try the below code and check

    client.distancematrix({
        params: {
            origins: [40, 40],
            destinations: [40, 41],
            key: process.env.GOOGLE_MAPS_API_KEY
        }
    })
    .then((r) => {
        console.log(r.data.rows)
    })
    .catch((e) => {
        console.log(e)
    })
    origins: '40,40',
            destinations: '40,41'
    

    Happy coding!

    Login or Signup to reply.
  2. The distancematrix function expects an array of origins and destinations, but in your code, you are passing a string for both. Instead, you should provide arrays of coordinates for origins and destinations.

        const { Client } = require("@googlemaps/google-maps-services-js");
    const client = new Client();
    
    client.distancematrix({
      params: {
        origins: ['40,40'], // Pass an array of origins
        destinations: ['40,41'], // Pass an array of destinations
        key: process.env.GOOGLE_MAPS_API_KEY,
      },
    })
      .then((response) => {
        console.log(response.data.rows);
      })
      .catch((error) => {
        console.log(error);
      });
    

    Make sure to pass arrays for origins and destinations, even if you have only one origin and one destination.

    If the issue persists, you may also want to check the version of the @googlemaps/google-maps-services-js package you are using and update it to the latest version to ensure that you have the latest bug fixes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search