我有以下代码在 PHP 中创建请求以从 Google 距离矩阵 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 并得到了相同的响应。感谢您提供的任何帮助。