对于每个循环退出工作。
public static function getMiles($to, $from)
{
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$from&destinations=$to&key=MyKey");
$time = 0;
$distance = 0;
/* return as an object for easier notation */
$json=json_decode( $data, false );
$origins = $json->origin_addresses;
$destinations=$json->destination_addresses;
/* if there are multiple rows, use a loop and `$rows[$i]` etc */
$elements=$json->rows[0]->elements;
foreach( $elements as $i => $obj ){
}
//extract the mileage as meters
$miles = $obj->distance->value;
//converting the meters to miles
$distance= round(($miles * '0.000621371192'), 1);
//returning miles
return $distance;
}
最终结果是返回2个地址之间的里程。 错误消息是“为foreach()提供了无效的参数”。
答案 0 :(得分:0)
您的功能可以正常使用了。当我从距离矩阵API请求中混淆我的API密钥时,实际上我只会收到此“为foreach()提供了无效参数”错误。
尝试使用有效 API密钥(代替“ YOUR_KEY”)运行以下代码:
function getMiles($to, $from)
{
$from = urlencode($from);
$to = urlencode($to);
$data = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$from&destinations=$to&key=YOUR_KEY");
$time = 0;
$distance = 0;
/* return as an object for easier notation */
$json=json_decode( $data, false );
$origins = $json->origin_addresses;
$destinations=$json->destination_addresses;
/* if there are multiple rows, use a loop and `$rows[$i]` etc */
$elements=$json->rows[0]->elements;
foreach( $elements as $i => $obj ){
}
//extract the mileage as meters
$miles = $obj->distance->value;
//converting the meters to miles
$distance= round(($miles * '0.000621371192'), 1);
//returning miles
return $distance;
}
echo "\nMiles: " . getMiles("paris,france", "berlin,germany");
您得到的输出应该是Miles: 659
。
我建议您通过these guides仔细检查您的密钥,项目和计费帐户的信誉。
希望这会有所帮助!
答案 1 :(得分:0)
嗯,这是我的错。经过进一步的挖掘,我能够确定我的信用卡已过期。重置我的到期日期,代码再次正常工作。 感谢您帮助我穆罕默德·奥默·阿斯兰(Muhammad Omer Aslam)指出正确的答案。