简体   繁体   中英

google maps, client libraries node js, distance matrix request js

I am trying to implement a google maps distance matrix api request using, node JS google Client library. specifically

@googlemaps/google-maps-services-js

The problem am facing, I can only finds source code example for elevation in the documentation.

const client = new Client({});

client
  .elevation({
    params: {
      locations: [{ lat: 45, lng: -110 }],
      key: "asdf",
    },
    timeout: 1000, // milliseconds
  })
  .then((r) => {
    console.log(r.data.results[0].elevation);
  })
  .catch((e) => {
    console.log(e.response.data.error_message);
  });

I need source code example for Distance Matrix so I can implement point to point distance calculation within node JS, using the client library.

const client = new Client({});

client
  .distanceMatrixrequest()
client
      .distancematrix({
        params: {
          key: '<YOUR_KEY>',
          origins: ['Greenwich, England'],
          destinations: ['Stockholm, Sweden'],
          travelMode: 'DRIVING',
          // Feel free to set more params
        },

        timeout: 1000, // milliseconds
      })
      .then((r) => {
        console.log(r.data.rows[0]?.elements);
        res.json(r.data);
      })
      .catch((e) => {
        console.log(e.response.data.status);
      });

Response comes in this format:

[
  {
    distance: { text: '1,880 km', value: 1880123 },
    duration: { text: '20 hours 59 mins', value: 75548 },
    status: 'OK'
  }
]

Here is my version of this function, trying to use place ID's but I cannot seem to get it to work. I keep getting the following error message: TypeError: Cannot read properties of undefined (reading 'data')

I can't seem to figure out what I am doing wrong in the function. Any help would be appreciated.

const pickupPlace = req.body.pickupPlace;
const dropPlace = req.body.dropPlace;
client
    .distancematrix({
        params: {
            key: 'AIzaSyCxk1SOh0Y5JGtTt6ucRvsTkDKtvis-Q-8',
            origins: [{ place_id: pickupPlace }],
            destinations: [{ place_id: dropPlace }],
            mode: 'driving'
        },
        timeout: 1000, // milliseconds
    })
    .then((data) => {
        console.log(`results: ${data}`);
        res.status(200).send(data);
    })
    .catch((e) => {
        console.log(e.response.data.error_message);
        res.status(403).send(e.response.data.error_message);
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM