3 min readJul 8, 2020
Hi Summerxiantian,
謝謝你的feedback!!
我想您應該是想確認如何從response的結果拿出您要的數據,我這邊舉一個我得到的回傳結果為範例(如下),response的結果會分為三個主要的資料,分別為destinationAddresses、originAddresses、rows,rows 裡面又會包一個elements的Array,要取到裡面這個Array的資料才可以提取距離跟時間的資訊
destinationAddresses:
[“No.205,Hanzhong Road,Wanhua District,Taipei City,Taiwan 108”],
originAddresses:
[“No.192,Kangding Road,Wanhua District,Taipei City,Taiwan 108”],
rows: [
{
elements: [
{
distance: {text: “0.6 km”, value: 640}},
duration: {text: “8 mins”, value: 505}},
status: “OK”,
},
]
}
]
您可以直接使用 response.destinationAddresses 或 response.originAddresses去提取所原始傳送的起始點或終點的地址資訊,如果是想取得兩點的距離或是所需時間資訊,以下面的回傳值為例,則需要像這樣才可以提取出來
distance = response.rows[0].element[0].distance
duration = response.rows[0].element[0].duration
我這邊再附上我使用DistanceMatrixService去取得回傳結果的簡單的程式碼(如下),呼叫service然後得到回傳結果的方式大概是像這樣,給您參考
let distanceMatrixService = new google.maps.DistanceMatrixService;distanceMatrixService.getDistanceMatrix({
origins: origin,
destinations: destinations,
// 舉例 destinations的格式可以像是
[{lat: 25.04081, lng: 121.506566},
{lat: 25.0418973, lng: 121.5047744}], travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.METRIC,
}, function(response, status) { if (status !== google.maps.DistanceMatrixStatus.OK) {
window.alert(‘Error was’ + status); } else { console.log(response);
let origins = response.originAddresses;
let destinations = response.destinationAddresses;
let distance = response.rows[0].element[0].distance
let duration = response.rows[0].element[0].duration }
});
希望以上有回答到您的疑問,若有誤解您的問題,歡迎你指正與近一步討論,謝謝!!