我有以下代码在PHP中创建请求以获取Google Distance Matrix API的响应:
//get info from google
$map_url = 'https://maps.googleapis.com/maps/api/distancematrix/json';
$midnight = strtotime('tomorrow midnight');
$params = array(
'units' => 'metric',
'origins' => str_replace(' ', '+', str_replace('.', '', $arr['address'])),
'destinations' => str_replace(' ', '+', str_replace('.', '', $rink_arr['address'])),
'traffic_model' => 'best_guess',
'departure_time' => $midnight + $rink_arr['avg_time'],
'key' => 'API_KEY'
);
//get data
$url = $map_url.'?'.http_build_query($params);
$json = file_get_contents($url);
echo '<pre>';
echo $url.'<br><br>';
print_r($json);
echo '</pre>';
exit();
当我运行此代码时,我得到以下响应:
https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=2141+Southview+Ave%2C+Innisfil%2C+ON+L9S+1H4&destinations=190+Bayview+Dr%2C+Barrie%2C+ON+L5N+9B4&traffic_model=best_guess&departure_time=1479523235&key=API_KEY
{
"destination_addresses" : [],
"origin_addresses" : [],
"rows" : [],
"status" : "INVALID_REQUEST"
}
但是,当我从上面的响应中复制url并将其粘贴到浏览器中时,这就是问题所在。我收到以下回复:
{
"destination_addresses" : [ "190 Bayview Dr, Barrie, ON L4N 2Z4, Canada" ],
"origin_addresses" : [ "2141 Southview Ave, Innisfil, ON L9S 1H4, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "9.0 km",
"value" : 9027
},
"duration" : {
"text" : "13 mins",
"value" : 758
},
"duration_in_traffic" : {
"text" : "12 mins",
"value" : 720
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
有没有人遇到类似的问题,并知道为什么会这样?我尝试过更改URL,但它在浏览器中而不是在file_get_contents中有效是没有意义的。我也试过cURL并得到了相同的回复。感谢您提供的任何帮助。