![](/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.