1 回答

TA貢獻1963條經驗 獲得超6個贊
我還沒有嘗試運行它,但從文檔來看,您似乎應該用|
.
起點- 計算行駛距離和時間的起點。您可以以地址、緯度/經度坐標或地點 ID 的形式提供一個或多個由豎線字符 (|) 分隔的位置:
和
目的地— 一個或多個位置,用作計算行駛距離和時間的終點。目的地參數的選項?與起源參數的選項相同,如上所述
因此,此代碼循環遍歷目的地并使用值創建第二個數組x,y
,然后implode()
使用|
...
$dests = [[
? ? ? ? "id" => 695,
? ? ? ? "lat" => "2.9315257",
? ? ? ? "long" => "101.7638137"
? ? ? ? ],
? ? ? ? [
? ? ? ? "id" => 696,
? ? ? ? "lat" => "2.9660291",
? ? ? ? "long" => "101.7499998"
? ? ? ? ],
? ? ? ? [
? ? ? ? "id" => 700,
? ? ? ? "lat" => "2.937143099999999",
? ? ? ? "long" => "101.7779784"
]];
$coords = array_map(function($data) { return? $data['lat'].",".$data['long']; }, $dests );
$from_latlong = implode("|", $coords);
$distance_data = file_get_contents(
? ? ? ? 'https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='.$from_latlong.'&destinations='.$to_latlong.'&key='.$googleApi
? ? ? ? );
所以目的地看起來像......
2.9315257,101.7638137|2.9660291,101.7499998|2.937143099999999,101.7779784
編輯
從您發布的額外代碼來看,它會是這樣的......
$distance_arr = json_decode($distance_data);
foreach ( $distance_arr->rows[0] as $key => $element )? {
? ? $distance = $element->distance->text;
? ? $duration = $element->duration->text;
? ? // The matching ID
? ? $id = $dests[$key];
? ??
? ? $distance = preg_replace("/[^0-9.]/", "",? $distance);
? ? $duration = preg_replace("/[^0-9.]/", "",? $duration);
? ??
? ? $distance=$distance * 1.609344;
? ? $distance=number_format($distance, 1, '.', '');
? ? $duration=number_format($duration, 1, '.', '');??
}
將foreach循環遍歷元素,然后$key將是元素的索引以及目標,因此您可以從源數組中的匹配元素中挑選出 ID。
- 1 回答
- 0 關注
- 125 瀏覽
添加回答
舉報