简体   繁体   English

谷歌地图,客户端库 node.js,距离矩阵请求 js

[英]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.我正在尝试使用节点 JS 谷歌客户端库实现谷歌地图距离矩阵 api 请求。 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.我需要距离矩阵的源代码示例,以便我可以使用客户端库在节点 JS 中实现点对点距离计算。

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.这是我的 function 版本,尝试使用地点 ID,但我似乎无法让它工作。 I keep getting the following error message: TypeError: Cannot read properties of undefined (reading 'data')我不断收到以下错误消息: 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.我似乎无法弄清楚我在 function 中做错了什么。任何帮助将不胜感激。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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