![](/img/trans.png)
[英]Google API Client Libraries for react project, Javascript or Node-js ?
[英]google maps, client libraries node js, distance matrix request js
我正在尝试使用节点 JS 谷歌客户端库实现谷歌地图距离矩阵 api 请求。 具体来说
@googlemaps/google-maps-services-js
面临的问题,我只能在文档中找到提升的源代码示例。
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);
});
我需要距离矩阵的源代码示例,以便我可以使用客户端库在节点 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);
});
响应采用以下格式:
[
{
distance: { text: '1,880 km', value: 1880123 },
duration: { text: '20 hours 59 mins', value: 75548 },
status: 'OK'
}
]
这是我的 function 版本,尝试使用地点 ID,但我似乎无法让它工作。 我不断收到以下错误消息: TypeError: Cannot read properties of undefined (reading 'data')
我似乎无法弄清楚我在 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.