Search code examples
javascriptnode.jsgoogle-distancematrix-api

Getting error: "o.map is not a function" when using google maps distance matrix api in Node.js


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.


Solution

  • 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!