我的php代码使用位置编号返回$distance
值但是如何使用位置名称获取距离?
这里代码
$from = "Arlington Heights, IL 60005, United States";
$to = 'Arlington Heights, IL 60004, United States';
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;
foreach($data->rows[0]->elements as $road) {
$time += $road->duration->value;
$distance += $road->distance->value;
}
答案 0 :(得分:0)
好吧,看起来我的逗号是错误的,但是请注意这个查询不需要它们并且可能导致错误,特别是如果你依赖于用户输入。我相信您的问题归结为foreach()
循环,因为如果您只是查询 A 到 B ,则不需要它。此外,您查询数组,就像它不是一个对象。在查询数组中的特定元素时,需要使用方括号[]
。
$from = 'Arlington Heights, IL 60005, United States';
$remFrom = str_replace(',', '', $from); //Remove Commas
$from = urlencode($remFrom);
$to = 'Arlington Heights, IL 60004, United States';
$remTo = str_replace(',', '', $to); //Remove Commas
$to = urlencode($remTo);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data, true);
$time = $data['rows'][0]['elements'][0]['duration']['text']; //Text for String and Value for INT
$distance = $data['rows'][0]['elements'][0]['distance']['text'];//Text for String and Value for INT
echo 'Distance: ' . $distance . '<br>';
echo 'Time: ' . $time;
<强>输出:强>
Distance: 5.7 km
Time: 11 mins
见:
https://developers.google.com/maps/documentation/distance-matrix/intro